summaryrefslogtreecommitdiff
path: root/internal/datas/rbuffer.go
blob: df8f622392d47963a7b5eb94d95b022aff1b0376 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
}