Add a FIFO class.

toying-with-ramdb
Philippe PITTOLI 2024-05-23 09:16:55 +02:00
parent 375f3bdf69
commit d46e0d2ddf
1 changed files with 37 additions and 0 deletions

37
src/fifo.cr Normal file
View File

@ -0,0 +1,37 @@
# This class enables to keep track of used data.
#
# Each time a value is pushed, it is put on top of a FIFO stack.
# Stack size is configurable, so in case the stack size exceeds what is allowed,
# the least recently used value is removed.
#
# ```
# fifo = FIFO(Int32).new 3 # Only 3 allowed entries.
#
# pp! fifo << 1 # -> nil (there is still room in the stack)
# pp! fifo << 2 # -> nil (there is still room in the stack)
# pp! fifo << 3 # -> nil (last entry without exceeding the allowed size)
# pp! fifo << 4 # -> 1 (least recently used data)
# pp! fifo << 4 # -> nil (already in the stack)
# pp! fifo << 2 # -> nil (already in the stack)
# pp! fifo << 5 # -> 3 (least recently used data)
# ```
class FIFO(V)
# This array is used as a *stack*.
property data : Array(V)
# Maximum allowed entries in the stack.
property max_entries : UInt32
def initialize(@max_entries : UInt32)
@data = Array(V).new
end
# Pushes a value in the FIFO and gets the oldest value whether it exceeds the allowed number of entries.
# NOTE: `#<<(v : V)` is 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.unshift v # push on top of the stack
@data.uniq! # remove dups
@data.pop if @data.size > @max_entries # remove least recently used entry if `@data` is too big
end
end