Source file src/log/slog/internal/buffer/buffer.go

     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.
     6  package buffer
     7  
     8  import "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.
    14  type Buffer []byte
    15  
    16  // Having an initial size gives a dramatic speedup.
    17  var bufPool = sync.Pool{
    18  	New: func() any {
    19  		b := make([]byte, 0, 1024)
    20  		return (*Buffer)(&b)
    21  	},
    22  }
    23  
    24  func New() *Buffer {
    25  	return bufPool.Get().(*Buffer)
    26  }
    27  
    28  func (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  
    37  func (b *Buffer) Reset() {
    38  	b.SetLen(0)
    39  }
    40  
    41  func (b *Buffer) Write(p []byte) (int, error) {
    42  	*b = append(*b, p...)
    43  	return len(p), nil
    44  }
    45  
    46  func (b *Buffer) WriteString(s string) (int, error) {
    47  	*b = append(*b, s...)
    48  	return len(s), nil
    49  }
    50  
    51  func (b *Buffer) WriteByte(c byte) error {
    52  	*b = append(*b, c)
    53  	return nil
    54  }
    55  
    56  func (b *Buffer) String() string {
    57  	return string(*b)
    58  }
    59  
    60  func (b *Buffer) Len() int {
    61  	return len(*b)
    62  }
    63  
    64  func (b *Buffer) SetLen(n int) {
    65  	*b = (*b)[:n]
    66  }
    67  

View as plain text