-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbuffer.go
More file actions
66 lines (60 loc) · 1.23 KB
/
buffer.go
File metadata and controls
66 lines (60 loc) · 1.23 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) 2025 KIDTSUNAMI
// Author: alex@kidtsunami.com
package log
import (
"bytes"
"iter"
"sync"
)
// RingBuffer stores capacity messages (always a power of 2). Useful
// with MultiWriter or as general write backend for logging and
// allows retrieval of the last N historic messages.
//
// buf := NewRingBuffer(128)
//
// // replace stdlog backend
// log.Log.Logger().SetOutput(buf)
//
// // attach to current backend
// log.Log.Attach(buf)
type RingBuffer struct {
mu sync.RWMutex
buf [][]byte
head uint64
mask uint64
}
func NewRingBuffer(capacity int) *RingBuffer {
size := uint64(1)
for size < uint64(capacity) {
size <<= 1
}
return &RingBuffer{
buf: make([][]byte, size),
mask: size - 1,
}
}
func (rb *RingBuffer) Write(buf []byte) (int, error) {
rb.mu.Lock()
defer rb.mu.Unlock()
idx := rb.head & rb.mask
rb.buf[idx] = bytes.Clone(buf)
rb.head++
return len(buf), nil
}
func (rb *RingBuffer) Last(n int) iter.Seq[[]byte] {
return func(yield func([]byte) bool) {
rb.mu.RLock()
defer rb.mu.RUnlock()
n = min(n, len(rb.buf), int(rb.head))
if n <= 0 {
return
}
idx := (rb.head - uint64(n)) & rb.mask
for range n {
if !yield(rb.buf[idx]) {
return
}
idx = (idx + 1) & rb.mask
}
}
}