PageRenderTime 26ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/mochiweb_io.erl

http://github.com/basho/mochiweb
Erlang | 61 lines | 27 code | 10 blank | 24 comment | 0 complexity | b906b2e8a4b207c787cd422ef71daa90 MD5 | raw file
Possible License(s): MIT
  1. %% @author Bob Ippolito <bob@mochimedia.com>
  2. %% @copyright 2007 Mochi Media, Inc.
  3. %%
  4. %% Permission is hereby granted, free of charge, to any person obtaining a
  5. %% copy of this software and associated documentation files (the "Software"),
  6. %% to deal in the Software without restriction, including without limitation
  7. %% the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. %% and/or sell copies of the Software, and to permit persons to whom the
  9. %% Software is furnished to do so, subject to the following conditions:
  10. %%
  11. %% The above copyright notice and this permission notice shall be included in
  12. %% all copies or substantial portions of the Software.
  13. %%
  14. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. %% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. %% DEALINGS IN THE SOFTWARE.
  21. %% @doc Utilities for dealing with IO devices (open files).
  22. -module(mochiweb_io).
  23. -author('bob@mochimedia.com').
  24. -export([iodevice_stream/3, iodevice_stream/2]).
  25. -export([iodevice_foldl/4, iodevice_foldl/3]).
  26. -export([iodevice_size/1]).
  27. -define(READ_SIZE, 8192).
  28. iodevice_foldl(F, Acc, IoDevice) ->
  29. iodevice_foldl(F, Acc, IoDevice, ?READ_SIZE).
  30. iodevice_foldl(F, Acc, IoDevice, BufferSize) ->
  31. case file:read(IoDevice, BufferSize) of
  32. eof ->
  33. Acc;
  34. {ok, Data} ->
  35. iodevice_foldl(F, F(Data, Acc), IoDevice, BufferSize)
  36. end.
  37. iodevice_stream(Callback, IoDevice) ->
  38. iodevice_stream(Callback, IoDevice, ?READ_SIZE).
  39. iodevice_stream(Callback, IoDevice, BufferSize) ->
  40. F = fun (Data, ok) -> Callback(Data) end,
  41. ok = iodevice_foldl(F, ok, IoDevice, BufferSize).
  42. iodevice_size(IoDevice) ->
  43. {ok, Size} = file:position(IoDevice, eof),
  44. {ok, 0} = file:position(IoDevice, bof),
  45. Size.
  46. %%
  47. %% Tests
  48. %%
  49. -ifdef(TEST).
  50. -include_lib("eunit/include/eunit.hrl").
  51. -endif.