aboutsummaryrefslogtreecommitdiff
path: root/internal/bufpool
diff options
context:
space:
mode:
authorGravatar Runxi Yu2025-11-23 08:00:00 +0800
committerGravatar Runxi Yu2025-11-23 08:00:00 +0800
commit7eaa8614c897a97d241335982f4c04f1f27b0715 (patch)
treeab39c63adecab22464b3fa50be7073647bb817d4 /internal/bufpool
parentobj: Add ReadObjectTypeRaw (diff)
signatureNo signature
bufpool: Return bytes.Buffer, rather than a pointer to it
It's silly to allocate a bytes.Buffer struct, however small it is, every time Borrow is called, since the entire purpose is to reduce allocations.
Diffstat (limited to 'internal/bufpool')
-rw-r--r--internal/bufpool/buffers.go17
1 files changed, 9 insertions, 8 deletions
diff --git a/internal/bufpool/buffers.go b/internal/bufpool/buffers.go
index 27c017bd..439e7e04 100644
--- a/internal/bufpool/buffers.go
+++ b/internal/bufpool/buffers.go
@@ -23,10 +23,11 @@ const (
// pooled buffer, the caller should invoke Release() to return it to the pool.
//
// Buffers must not be copied after first use; doing so can cause double-returns
-// to the pool and data races. A zero-value Buffer is not valid for use. Use
-// the pointer type (*Buffer) returned by Borrow/FromOwned to avoid accidental
-// copies.
+// to the pool and data races.
+//
+//go:nocopy
type Buffer struct {
+ _ struct{} // for nocopy
buf []byte
pool poolIndex
}
@@ -69,28 +70,28 @@ var bufferPools = func() []sync.Pool {
// unpooled buffer is allocated.
//
// The caller must call Release() when finished using the returned Buffer.
-func Borrow(capHint int) *Buffer {
+func Borrow(capHint int) Buffer {
if capHint < DefaultBufferCap {
capHint = DefaultBufferCap
}
classIdx, classCap, pooled := classFor(capHint)
if !pooled {
newBuf := make([]byte, 0, capHint)
- return &Buffer{buf: newBuf, pool: unpooled}
+ return Buffer{buf: newBuf, pool: unpooled}
}
buf := bufferPools[classIdx].Get().(*[]byte)
if cap(*buf) < classCap {
*buf = make([]byte, 0, classCap)
}
slice := (*buf)[:0]
- return &Buffer{buf: slice, pool: poolIndex(classIdx)}
+ return Buffer{buf: slice, pool: poolIndex(classIdx)}
}
// FromOwned constructs a Buffer from a caller-owned byte slice. The resulting
// Buffer does not participate in pooling and will never be returned to the
// internal pool when released.
-func FromOwned(buf []byte) *Buffer {
- return &Buffer{buf: buf, pool: unpooled}
+func FromOwned(buf []byte) Buffer {
+ return Buffer{buf: buf, pool: unpooled}
}
// Resize adjusts the length of the buffer to n bytes. If n exceeds the current