-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenringbuffer.go
More file actions
52 lines (43 loc) · 1.29 KB
/
genringbuffer.go
File metadata and controls
52 lines (43 loc) · 1.29 KB
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
package genringbuffer
import "time"
// Ringbuffer is a fixed length FIFO queue that drops new items when full and allows non-blocking polling for new items with optional timeout
type Ringbuffer[T any] chan T
// NewRingbuffer creates a new ringbuffer with the given fixed number of items.
func NewRingBuffer[T any](size int) Ringbuffer[T] {
return Ringbuffer[T](make(chan T, size))
}
// Offer adds an item to the ringbuffer. If the buffer is full, it returns immediately. Returns true if added.
func (r Ringbuffer[T]) Offer(input T) bool {
select {
case r <- input:
return true
default:
return false
}
}
// Poll gets an item from the ringbuffer, or blocks until one is available, until dur duration passed. Returns true if an item was returned.
func (r Ringbuffer[T]) Poll(dur time.Duration) (obj T, res bool) {
select {
case obj = <-r:
res = true
case <-time.After(dur):
res = false
}
return
}
// Get gets an item from the ringbuffer, or blocks until one is available.
func (r Ringbuffer[T]) Get() T {
return <-r
}
// Len returns the number of items in the ringbuffer.
func (r Ringbuffer[T]) Len() int {
return len(r)
}
// Cap returns the capacity of the ringbuffer.
func (r Ringbuffer[T]) Cap() int {
return cap(r)
}
// Close closes the ringbuffer.
func (r Ringbuffer[T]) Close() {
close(r)
}