summaryrefslogtreecommitdiffhomepage
path: root/util/ringbuffer/ringbuffer.go
diff options
context:
space:
mode:
authorAndrew Dunham <andrew@du.nham.ca>2023-02-21 14:01:07 -0500
committerAndrew Dunham <andrew@tailscale.com>2023-02-21 19:11:08 +0000
commite220fa65dd03b417ace0eb22d372d342fceb183c (patch)
treee4ca58034637342182eb9d709cb490a03d790cf8 /util/ringbuffer/ringbuffer.go
parentcd18bb68a49608b86f60e22cb081f0156d3d11b5 (diff)
downloadtailscale-e220fa65dd03b417ace0eb22d372d342fceb183c.tar.xz
tailscale-e220fa65dd03b417ace0eb22d372d342fceb183c.zip
util/ringbuffer: move generic ringbuffer from corp repo
Also add some basic tests for this implementation. Signed-off-by: Andrew Dunham <andrew@du.nham.ca> Change-Id: I307ebb6db91d0c172657befb276b38ccb638f828
Diffstat (limited to 'util/ringbuffer/ringbuffer.go')
-rw-r--r--util/ringbuffer/ringbuffer.go72
1 files changed, 72 insertions, 0 deletions
diff --git a/util/ringbuffer/ringbuffer.go b/util/ringbuffer/ringbuffer.go
new file mode 100644
index 000000000..00310baea
--- /dev/null
+++ b/util/ringbuffer/ringbuffer.go
@@ -0,0 +1,72 @@
+// Copyright (c) Tailscale Inc & AUTHORS
+// SPDX-License-Identifier: BSD-3-Clause
+
+// Package ringbuffer contains a fixed-size concurrency-safe generic ring
+// buffer.
+package ringbuffer
+
+import "sync"
+
+// New creates a new RingBuffer containing at most max items.
+func New[T any](max int) *RingBuffer[T] {
+ return &RingBuffer[T]{
+ max: max,
+ }
+}
+
+// RingBuffer is a concurrency-safe ring buffer.
+type RingBuffer[T any] struct {
+ mu sync.Mutex
+ pos int
+ buf []T
+ max int
+}
+
+// Add appends a new item to the RingBuffer, possibly overwriting the oldest
+// item in the buffer if it is already full.
+func (rb *RingBuffer[T]) Add(t T) {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ if len(rb.buf) < rb.max {
+ rb.buf = append(rb.buf, t)
+ } else {
+ rb.buf[rb.pos] = t
+ rb.pos = (rb.pos + 1) % rb.max
+ }
+}
+
+// GetAll returns a copy of all the entries in the ring buffer in the order they
+// were added.
+func (rb *RingBuffer[T]) GetAll() []T {
+ if rb == nil {
+ return nil
+ }
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ out := make([]T, len(rb.buf))
+ for i := 0; i < len(rb.buf); i++ {
+ x := (rb.pos + i) % rb.max
+ out[i] = rb.buf[x]
+ }
+ return out
+}
+
+// Len returns the number of elements in the ring buffer. Note that this value
+// could change immediately after being returned if a concurrent caller
+// modifies the buffer.
+func (rb *RingBuffer[T]) Len() int {
+ if rb == nil {
+ return 0
+ }
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ return len(rb.buf)
+}
+
+// Clear will empty the ring buffer.
+func (rb *RingBuffer[T]) Clear() {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ rb.pos = 0
+ rb.buf = nil
+}