PageRenderTime 19ms CodeModel.GetById 8ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 1ms

/deps/mochiweb/src/mochiweb_io.erl

http://github.com/zotonic/zotonic
Erlang | 43 lines | 27 code | 10 blank | 6 comment | 0 complexity | aba45bd4d614a7e2e23908344168081a MD5 | raw file
 1%% @author Bob Ippolito <bob@mochimedia.com>
 2%% @copyright 2007 Mochi Media, Inc.
 3
 4%% @doc Utilities for dealing with IO devices (open files).
 5
 6-module(mochiweb_io).
 7-author('bob@mochimedia.com').
 8
 9-export([iodevice_stream/3, iodevice_stream/2]).
10-export([iodevice_foldl/4, iodevice_foldl/3]).
11-export([iodevice_size/1]).
12-define(READ_SIZE, 8192).
13
14iodevice_foldl(F, Acc, IoDevice) ->
15    iodevice_foldl(F, Acc, IoDevice, ?READ_SIZE).
16
17iodevice_foldl(F, Acc, IoDevice, BufferSize) ->
18    case file:read(IoDevice, BufferSize) of
19        eof ->
20            Acc;
21        {ok, Data} ->
22            iodevice_foldl(F, F(Data, Acc), IoDevice, BufferSize)
23    end.
24
25iodevice_stream(Callback, IoDevice) ->
26    iodevice_stream(Callback, IoDevice, ?READ_SIZE).
27
28iodevice_stream(Callback, IoDevice, BufferSize) ->
29    F = fun (Data, ok) -> Callback(Data) end,
30    ok = iodevice_foldl(F, ok, IoDevice, BufferSize).
31
32iodevice_size(IoDevice) ->
33    {ok, Size} = file:position(IoDevice, eof),
34    {ok, 0} = file:position(IoDevice, bof),
35    Size.
36
37
38%%
39%% Tests
40%%
41-ifdef(TEST).
42-include_lib("eunit/include/eunit.hrl").
43-endif.