From d46e0d2ddfbe503ce0af62066f4b790ecfbdb442 Mon Sep 17 00:00:00 2001 From: Philippe PITTOLI Date: Thu, 23 May 2024 09:16:55 +0200 Subject: [PATCH] Add a FIFO class. --- src/fifo.cr | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/fifo.cr diff --git a/src/fifo.cr b/src/fifo.cr new file mode 100644 index 0000000..b0f013a --- /dev/null +++ b/src/fifo.cr @@ -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