summaryrefslogtreecommitdiff
path: root/internal/datas/rbuffer.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/datas/rbuffer.go')
-rw-r--r--internal/datas/rbuffer.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/internal/datas/rbuffer.go b/internal/datas/rbuffer.go
new file mode 100644
index 0000000..df8f622
--- /dev/null
+++ b/internal/datas/rbuffer.go
@@ -0,0 +1,49 @@
+package datas
+
+import "fmt"
+
+// RBuffer is a simple circular string ring buffer data structure.
+type RBuffer struct {
+ Capacity int
+ size int
+ readPos int
+ writePos int
+ data []string
+}
+
+// NewRBuffer creates a new string ring buffer.
+func NewRBuffer(capacity int) (*RBuffer, error) {
+ if capacity < 1 {
+ return nil, fmt.Errorf("RBuffer capacity must not be less than 1")
+ }
+
+ r := RBuffer{
+ Capacity: capacity,
+ size: capacity + 1,
+ data: make([]string, capacity+1),
+ }
+
+ return &r, nil
+}
+
+// Add a value.
+func (r *RBuffer) Add(value string) {
+ r.data[r.writePos] = value
+ r.writePos = (r.writePos + 1) % r.size
+
+ if r.writePos == r.readPos {
+ r.readPos = (r.readPos + 1) % r.size
+ }
+}
+
+// Get a value.
+func (r *RBuffer) Get() (string, bool) {
+ if r.readPos == r.writePos {
+ // RBuffer is empty.
+ return "", false
+ }
+
+ value := r.data[r.readPos]
+ r.readPos = (r.readPos + 1) % r.size
+ return value, true
+}