From 2c4fcaaf07a1f1a48992c5042c2955b463003bd7 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Fri, 10 Jul 2020 15:48:43 +0000 Subject: [PATCH] [LIB][Util] Add Ring Buffer data structure --- src/Util/ds/RingBuffer.php | 58 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/Util/ds/RingBuffer.php diff --git a/src/Util/ds/RingBuffer.php b/src/Util/ds/RingBuffer.php new file mode 100644 index 0000000000..99307bc5a7 --- /dev/null +++ b/src/Util/ds/RingBuffer.php @@ -0,0 +1,58 @@ +. +// }}} + +namespace App\Util\ds; + +use Ds\Deque; +use Functional as F; + +class RingBuffer implements \Serializable +{ + private int $capacity; + private Deque $elements; + + public function __construct(int $c) + { + $this->capacity = $c; + $this->elements = new Deque(); + } + + public function serialize() + { + return serialize($this->capacity) . serialize($this->elements); + } + + public function unserialize($data) + { + list($this->capacity, $this->elements) = F\map(explode(';', $data), F\ary('unserialize', 1)); + } + + public function add($e) + { + if ($this->capacity !== 0 && $this->elements->count() >= $this->capacity) { + $this->elements->shift(); + } + $this->elements->unshift($e); + } + + public function remove(int $index) + { + return $this->elements->remove($index); + } +}