-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.go
More file actions
51 lines (43 loc) · 1.11 KB
/
Copy pathbuffer.go
File metadata and controls
51 lines (43 loc) · 1.11 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
package bytepool
import (
"sync/atomic"
)
// Buffer represents a reference-counted byte buffer that can be safely shared
type Buffer struct {
buf atomic.Pointer[[]byte] // use type-safe atomic.Pointer
refCount int32
pools *BytePool
}
// Bytes returns the buffer data and a release function
// The caller must call the release function when done with the data
func (b *Buffer) Bytes() ([]byte, func()) {
b.Retain()
// atomically read buf pointer
bufPtr := b.buf.Load()
if bufPtr == nil {
return nil, func() {}
}
return *bufPtr, b.Release
}
// Release decrements the reference count and returns the buffer to pool when count reaches zero
func (b *Buffer) Release() {
if atomic.AddInt32(&b.refCount, -1) == 0 {
bufPtr := b.buf.Swap(nil)
if bufPtr != nil {
b.pools.Put(*bufPtr)
}
}
}
// Retain increments the reference count
func (b *Buffer) Retain() {
atomic.AddInt32(&b.refCount, 1)
}
// NewBuffer creates a new Buffer with the given data and pool reference
func NewBuffer(data []byte, pools *BytePool) *Buffer {
buf := &Buffer{
refCount: 1,
pools: pools,
}
buf.buf.Store(&data)
return buf
}