diff options
Diffstat (limited to 'src/index.erl')
-rw-r--r-- | src/index.erl | 41 |
1 files changed, 24 insertions, 17 deletions
diff --git a/src/index.erl b/src/index.erl index 7871215..a2b5c4a 100644 --- a/src/index.erl +++ b/src/index.erl @@ -11,7 +11,7 @@ %% TODO: Checksums -module(index). --export([get/2, add/3, addlast/2, truncate/2]). +-export([get/2, getrange/3, add/3, addlast/2, truncate/2]). -define(ENTRYSIZE, 32). -define(ENTRYSIZEINFILE, (?ENTRYSIZE*2+1)). @@ -54,31 +54,38 @@ truncate(Basepath, Index) -> addlast(Basepath, Entry) -> add(Basepath, last, Entry). -%% From lib/stdlib/src/lists.erl. For supporting < R17. --spec droplast(nonempty_list()) -> list(). -droplast([_T]) -> []; -droplast([H|T]) -> [H|droplast(T)]. +decodedata(Binary) -> + lists:reverse(decodedata(Binary, [])). -decodedata(EntryText) when length(EntryText) == ?ENTRYSIZEINFILE -> - case [lists:last(EntryText)] of - "\n" -> - hex:hexstr_to_bin(droplast(EntryText)); - _ -> - util:exit_with_error(badformat, readindex, - "Index line not ending with linefeed") - end. +decodedata(<<>>, Acc) -> + Acc; +decodedata(<<Entry:?ENTRYSIZE/binary-unit:16, "\n", Rest/binary>>, Acc) -> + decodedata(Rest, [mochihex:to_bin(binary_to_list(Entry)) | Acc]); +decodedata(<<_:?ENTRYSIZE/binary-unit:16, _>>, _Acc) -> + util:exit_with_error(badformat, readindex, + "Index line not ending with linefeed"). -spec get(string(), integer()) -> binary(). get(Basepath, Index) -> + case getrange(Basepath, Index, Index) of + noentry -> + noentry; + [Entry] -> + Entry + end. + +-spec getrange(string(), integer(), integer()) -> [binary()]. +getrange(Basepath, Start, End) when Start =< End -> case file:open(Basepath, [read, binary]) of {ok, File} -> {ok, Filesize} = file:position(File, eof), if - Index * ?ENTRYSIZEINFILE + ?ENTRYSIZEINFILE =< Filesize -> + End * ?ENTRYSIZEINFILE + ?ENTRYSIZEINFILE =< Filesize -> {ok, _Position} = file:position(File, - Index * ?ENTRYSIZEINFILE), - {ok, EntryText} = file:read(File, ?ENTRYSIZEINFILE), - Entry = decodedata(binary_to_list(EntryText)), + Start * ?ENTRYSIZEINFILE), + {ok, EntryText} = + file:read(File, ?ENTRYSIZEINFILE * (End - Start + 1)), + Entry = decodedata(EntryText), file:close(File), Entry; true -> |