1// Copyright 2022 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// Package buffer provides a pool-allocated byte buffer. 6package buffer 7 8import "sync" 9 10// Buffer is a byte buffer. 11// 12// This implementation is adapted from the unexported type buffer 13// in go/src/fmt/print.go. 14type Buffer []byte 15 16// Having an initial size gives a dramatic speedup. 17var bufPool = sync.Pool{ 18 New: func() any { 19 b := make([]byte, 0, 1024) 20 return (*Buffer)(&b) 21 }, 22} 23 24func New() *Buffer { 25 return bufPool.Get().(*Buffer) 26} 27 28func (b *Buffer) Free() { 29 // To reduce peak allocation, return only smaller buffers to the pool. 30 const maxBufferSize = 16 << 10 31 if cap(*b) <= maxBufferSize { 32 *b = (*b)[:0] 33 bufPool.Put(b) 34 } 35} 36 37func (b *Buffer) Reset() { 38 b.SetLen(0) 39} 40 41func (b *Buffer) Write(p []byte) (int, error) { 42 *b = append(*b, p...) 43 return len(p), nil 44} 45 46func (b *Buffer) WriteString(s string) (int, error) { 47 *b = append(*b, s...) 48 return len(s), nil 49} 50 51func (b *Buffer) WriteByte(c byte) error { 52 *b = append(*b, c) 53 return nil 54} 55 56func (b *Buffer) String() string { 57 return string(*b) 58} 59 60func (b *Buffer) Len() int { 61 return len(*b) 62} 63 64func (b *Buffer) SetLen(n int) { 65 *b = (*b)[:n] 66} 67