dodb.cr/spec/test-lru.cr

55 lines
1.7 KiB
Crystal
Raw Normal View History

2024-12-13 23:31:25 +01:00
require "spec"
require "../src/lru.cr"
describe "LRU" do
it "add and remove values" do
lru = LRU(Int32).new 3 # Only 3 allowed entries.
(lru << 1).should be_nil # there is still room in the lru
(lru << 2).should be_nil # there is still room in the lru
(lru << 3).should be_nil # last entry without exceeding the allowed size
(lru << 4).should eq 1 # -> 1 (least recently used data)
(lru << 4).should be_nil # -> nil (already in the lru)
(lru << 2).should be_nil # -> nil (already in the lru)
(lru << 5).should eq 3 # -> 3 (least recently used data)
lru.data.should eq([5, 2, 4] of Int32)
lru.delete 2
lru.data.should eq([5, 4] of Int32)
end
end
describe "EfficientLRU" do
it "add and remove values" do
lru = EfficientLRU(Int32).new 3 # Only 3 allowed entries.
(lru << 1).should be_nil # there is still room in the lru
(lru << 2).should be_nil # there is still room in the lru
(lru << 3).should be_nil # last entry without exceeding the allowed size
(lru << 4).should eq 1 # -> 1 (least recently used data)
(lru << 4).should be_nil # -> nil (already in the lru)
(lru << 2).should be_nil # -> nil (already in the lru)
(lru << 5).should eq 3 # -> 3 (least recently used data)
lru.list.to_s.should eq "[ 5, 2, 4 ]"
lru.delete 2
lru.list.to_s.should eq "[ 5, 4 ]"
(lru << 4).should be_nil # -> nil (just a re-order)
lru.list.to_s.should eq "[ 4, 5 ]"
lru.delete 5
(lru << 0).should be_nil
lru.list.to_s.should eq "[ 0, 4 ]"
(lru << 1).should be_nil
lru.list.to_s.should eq "[ 1, 0, 4 ]"
lru.delete 4
lru.list.to_s.should eq "[ 1, 0 ]"
lru.delete 4
lru.list.to_s.should eq "[ 1, 0 ]"
lru.list.size.should eq 2
lru.hash.size.should eq 2
end
end