1
0

handle zero allocation in buffered writer

This commit is contained in:
Arpad Ryszka 2026-03-26 18:12:49 +01:00
parent 9d7bed320b
commit 66d5e49c06
3 changed files with 17 additions and 3 deletions

View File

@ -2,9 +2,9 @@
Pooled Buffer IO for Go programs. Pooled Buffer IO for Go programs.
Package buffer provides a reader implementation similar to bufio.Reader. The underlying memory buffers can be Package buffer provides a reader implementation similar to bufio.Reader, and a writer implementation to batch
used from a synchronized pool. It also supports scenarios similar to io.Pipe, where a content writer process is write operations targeting an underlying writer. The used memory buffers can be taken from a synchronized pool.
wrapped by a buffered reader. It also supports scenarios similar to io.Pipe, where a content writer process is wrapped by a buffered reader.
Find the documentation here: Find the documentation here:

View File

@ -28,6 +28,10 @@ func (w *writer) write(p []byte) (int, error) {
if len(w.buffer) == 0 { if len(w.buffer) == 0 {
w.buffer, w.err = w.options.Pool.Get() w.buffer, w.err = w.options.Pool.Get()
if len(w.buffer) == 0 && w.err == nil {
w.err = ErrZeroAllocation
}
continue continue
} }

View File

@ -402,4 +402,14 @@ func TestWriter(t *testing.T) {
t.Fatal(string(w.written)) t.Fatal(string(w.written))
} }
}) })
t.Run("zero allocation", func(t *testing.T) {
w := &writer{}
p := &fakePool{}
o := buffer.Options{Pool: p}
b := buffer.BufferedWriter(w, o)
if n, err := b.Write([]byte("123")); n != 0 || !errors.Is(err, buffer.ErrZeroAllocation) {
t.Fatal(n, err)
}
})
} }