Compare commits

..

2 Commits

Author SHA1 Message Date
acd71238df Specs: fifo. 2024-05-25 02:22:52 +02:00
543e1ce80f Fix FIFO. 2024-05-25 02:22:31 +02:00
4 changed files with 45 additions and 4 deletions

View File

@ -26,10 +26,10 @@ end
class SPECDB::FIFO(V) < DODB::Storage::Stacked(V)
property storage_dir : String
def initialize(storage_ext = "", @max_entries = 100_000, remove_previous_data = true)
def initialize(storage_ext = "", @max_entries : UInt32 = 5_000, remove_previous_data = true)
@storage_dir = "specdb-storage-fifo-#{@max_entries}#{storage_ext}"
::FileUtils.rm_rf storage_dir if remove_previous_data
super storage_dir
super storage_dir, max_entries
end
def rm_storage_dir

41
spec/test-fifo.cr Normal file
View File

@ -0,0 +1,41 @@
require "spec"
require "./db-cars.cr"
describe "FIFO" do
it "add and remove values" do
fifo = FIFO(Int32).new 3 # Only 3 allowed entries.
(fifo << 1).should be_nil # there is still room in the stack
(fifo << 2).should be_nil # there is still room in the stack
(fifo << 3).should be_nil # last entry without exceeding the allowed size
(fifo << 4).should eq 1 # -> 1 (least recently used data)
(fifo << 4).should be_nil # -> nil (already in the stack)
(fifo << 2).should be_nil # -> nil (already in the stack)
(fifo << 5).should eq 3 # -> 3 (least recently used data)
fifo.data.should eq([5, 2, 4] of Int32)
end
end
describe "SPECDB::FIFO" do
it "basics, 3 values" do
car0 = Car.new "Corvet-0", "red", [] of String
car1 = Car.new "Corvet-1", "red", [] of String
car2 = Car.new "Corvet-2", "red", [] of String
car3 = Car.new "Corvet-3", "red", [] of String
db = SPECDB::FIFO(Car).new("", 3)
db.data.keys.sort.should eq([] of Int32)
db << car0
db.data.keys.sort.should eq([0] of Int32)
db << car1
db.data.keys.sort.should eq([0, 1] of Int32)
db << car2
db.data.keys.sort.should eq([0, 1, 2] of Int32)
db << car3
db.data.keys.sort.should eq([1, 2, 3] of Int32)
end
end

View File

@ -37,7 +37,7 @@ class DODB::Storage::Stacked(V) < DODB::Storage::Cached(V)
property stack : FIFO(Int32)
# Initializes the `StackedDataBase` with a maximum number of entries in the cache.
def initialize(@directory_name : String, max_entries : UInt32 = 100_000)
def initialize(@directory_name : String, max_entries : UInt32)
@stack = FIFO(Int32).new max_entries
Dir.mkdir_p data_path
Dir.mkdir_p locks_directory

View File

@ -30,7 +30,7 @@ class FIFO(V)
# NOTE: `#<<(v : V)` is (almost) the only function since it's enough for the intended use, feel free to improve this.
# WARNING: implementation is extremely simple (3 lines) and not designed to be highly efficient.
def <<(v : V) : V?
@data.select! { |x| v != v } # remove dups
@data.select! { |x| v != x } # remove dups
@data.unshift v # push on top of the stack
@data.pop if @data.size > @max_entries # remove least recently used entry if `@data` is too big
end