From e2f2cf4e11d13602c787ccc7b90f5824ce87dab3 Mon Sep 17 00:00:00 2001 From: Linus Nordberg Date: Thu, 9 Oct 2014 18:30:27 +0200 Subject: Make get_by_indices() handle non-existing entries. - Limit End to size - 1. - Return [] for start < 0 and bound end < start. --- src/db.erl | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) (limited to 'src/db.erl') diff --git a/src/db.erl b/src/db.erl index d90282f..4bcdc1c 100644 --- a/src/db.erl +++ b/src/db.erl @@ -35,9 +35,7 @@ stop() -> add(LeafHash, EntryHash, Data, Index) -> gen_server:call(?MODULE, {add, {LeafHash, EntryHash, Data, Index}}). --spec get_by_indices(non_neg_integer(), - non_neg_integer(), - {sorted, true|false}) -> +-spec get_by_indices(integer(), integer(), {sorted, true|false}) -> [{non_neg_integer(), binary(), binary()}]. get_by_indices(Start, End, {sorted, Sorted}) -> gen_server:call(?MODULE, {get_by_indices, {Start, End, Sorted}}). @@ -114,6 +112,21 @@ leafhash_for_index(Index) -> leafhash_for_entryhash(EntryHash) -> perm:readfile(entryhash_root_path(), EntryHash). +get_by_indices_helper(Start, _End) when Start < 0 -> + []; +get_by_indices_helper(Start, End) -> + EndBound = min(End, size() - 1), + case Start =< EndBound of + true -> + lists:map(fun (Index) -> + LeafHash = leafhash_for_index(Index), + Entry = entry_for_leafhash(LeafHash), + {Index, LeafHash, Entry} + end, lists:seq(Start, EndBound)); + false -> + [] + end. + handle_call(stop, _From, State) -> {stop, normal, stopped, State}; @@ -127,12 +140,7 @@ handle_call({add, {LeafHash, EntryHash, Data, Index}}, _From, State) -> {reply, ok, State}; handle_call({get_by_indices, {Start, End, _Sorted}}, _From, State) -> - R = lists:map(fun (Index) -> - LeafHash = leafhash_for_index(Index), - Entry = entry_for_leafhash(LeafHash), - {Index, LeafHash, Entry} - end, lists:seq(Start, End)), - {reply, R, State}; + {reply, get_by_indices_helper(Start, End), State}; handle_call({get_by_index, Index}, _From, State) -> LeafHash = leafhash_for_index(Index), -- cgit v1.1