From 011348b33aeaf349d40d183028d02fa72d00e924 Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Sun, 12 Jan 2020 15:12:01 +0100 Subject: [PATCH] start_offset, end_offset added in each and to_a. --- spec/test.cr | 16 ++++++++++++++++ src/dodb.cr | 29 ++++++++++++++++++++++++----- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/spec/test.cr b/spec/test.cr index 803cb55..8cb48e5 100644 --- a/spec/test.cr +++ b/spec/test.cr @@ -174,6 +174,22 @@ describe "DODB::DataBase" do item.should eq Ship.all_ships.reverse[index] end end + + it "respects the provided offsets if any" do + db = DODB::SpecDataBase.new + + Ship.all_ships.each do |ship| + db << ship + end + + db.to_a(start_offset: 0, end_offset: 0)[0]?.should eq Ship.mutsuki + db.to_a(start_offset: 1, end_offset: 1)[0]?.should eq Ship.kisaragi + db.to_a(start_offset: 2, end_offset: 2)[0]?.should eq Ship.yayoi + + db.to_a(start_offset: 0, end_offset: 2).should eq [ + Ship.mutsuki, Ship.kisaragi, Ship.yayoi + ] + end end describe "indices" do diff --git a/src/dodb.cr b/src/dodb.cr index 108bb1b..7014ba1 100644 --- a/src/dodb.cr +++ b/src/dodb.cr @@ -197,10 +197,21 @@ class DODB::DataBase(V) ## # CAUTION: Very slow. Try not to use. # Can be useful for making dumps or to restore a database, however. - def each_with_index(reversed = false) + def each_with_index(reversed : Bool = false, start_offset = 0, end_offset : Int32? = nil) dirname = data_path + offset = -1 + each_key(reversed) do |key, path| + offset += 1 + + if offset < start_offset + next + end + if !end_offset.nil? && offset > end_offset + next + end + begin # FIXME: Only intercept JSON parsing errors. field = read path @@ -211,18 +222,26 @@ class DODB::DataBase(V) yield field, key end end - def each(reversed = false) - each_with_index(reversed: reversed) do |item, index| + def each(reversed : Bool = false, start_offset = 0, end_offset : Int32? = nil) + each_with_index( + reversed: reversed, + start_offset: start_offset, + end_offset: end_offset + ) do |item, index| yield item end end ## # CAUTION: Very slow. Try not to use. - def to_a(reversed = false) + def to_a(reversed : Bool = false, start_offset = 0, end_offset : Int32? = nil) array = ::Array(V).new - each(reversed) do |value| + each( + reversed: reversed, + start_offset: start_offset, + end_offset: end_offset + ) do |value| array << value end