-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.go
More file actions
57 lines (47 loc) · 895 Bytes
/
buffer.go
File metadata and controls
57 lines (47 loc) · 895 Bytes
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
50
51
52
53
54
55
56
57
// Copyright (c) CattleCloud LLC
// SPDX-License-Identifier: BSD-3-Clause
package circlebuffer
import "iter"
type Array[T any] interface {
All() iter.Seq[T]
Insert(T)
Size() int
Empty() bool
}
func New[T any](capacity int) Array[T] {
return &array[T]{
data: make([]T, capacity),
}
}
type array[T any] struct {
data []T
head int
size int
}
func (b *array[T]) Size() int {
return b.size
}
func (b *array[T]) Empty() bool {
return b.Size() == 0
}
func (b *array[T]) Insert(item T) {
b.data[b.head] = item
if b.size < len(b.data) {
b.size++
}
b.head = (b.head + 1) % len(b.data)
}
func (b *array[T]) All() iter.Seq[T] {
return func(yield func(T) bool) {
if b.size == 0 {
return
}
start := (b.head - b.size + len(b.data)) % len(b.data)
for i := 0; i < b.size; i++ {
index := (start + i) % len(b.data)
if !yield(b.data[index]) {
return
}
}
}
}