PageRenderTime 319ms CodeModel.GetById 74ms app.highlight 92ms RepoModel.GetById 107ms app.codeStats 1ms

/src/mochiweb_io.erl

http://github.com/basho/mochiweb
Erlang | 61 lines | 27 code | 10 blank | 24 comment | 0 complexity | b906b2e8a4b207c787cd422ef71daa90 MD5 | raw file
 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
22%% @doc Utilities for dealing with IO devices (open files).
23
24-module(mochiweb_io).
25-author('bob@mochimedia.com').
26
27-export([iodevice_stream/3, iodevice_stream/2]).
28-export([iodevice_foldl/4, iodevice_foldl/3]).
29-export([iodevice_size/1]).
30-define(READ_SIZE, 8192).
31
32iodevice_foldl(F, Acc, IoDevice) ->
33    iodevice_foldl(F, Acc, IoDevice, ?READ_SIZE).
34
35iodevice_foldl(F, Acc, IoDevice, BufferSize) ->
36    case file:read(IoDevice, BufferSize) of
37        eof ->
38            Acc;
39        {ok, Data} ->
40            iodevice_foldl(F, F(Data, Acc), IoDevice, BufferSize)
41    end.
42
43iodevice_stream(Callback, IoDevice) ->
44    iodevice_stream(Callback, IoDevice, ?READ_SIZE).
45
46iodevice_stream(Callback, IoDevice, BufferSize) ->
47    F = fun (Data, ok) -> Callback(Data) end,
48    ok = iodevice_foldl(F, ok, IoDevice, BufferSize).
49
50iodevice_size(IoDevice) ->
51    {ok, Size} = file:position(IoDevice, eof),
52    {ok, 0} = file:position(IoDevice, bof),
53    Size.
54
55
56%%
57%% Tests
58%%
59-ifdef(TEST).
60-include_lib("eunit/include/eunit.hrl").
61-endif.