...

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

Documentation: log/slog/internal/buffer

     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 adapted from go/src/fmt/print.go
    11  type Buffer []byte
    12  
    13  // Having an initial size gives a dramatic speedup.
    14  var bufPool = sync.Pool{
    15  	New: func() any {
    16  		b := make([]byte, 0, 1024)
    17  		return (*Buffer)(&b)
    18  	},
    19  }
    20  
    21  func New() *Buffer {
    22  	return bufPool.Get().(*Buffer)
    23  }
    24  
    25  func (b *Buffer) Free() {
    26  	// To reduce peak allocation, return only smaller buffers to the pool.
    27  	const maxBufferSize = 16 << 10
    28  	if cap(*b) <= maxBufferSize {
    29  		*b = (*b)[:0]
    30  		bufPool.Put(b)
    31  	}
    32  }
    33  
    34  func (b *Buffer) Reset() {
    35  	b.SetLen(0)
    36  }
    37  
    38  func (b *Buffer) Write(p []byte) (int, error) {
    39  	*b = append(*b, p...)
    40  	return len(p), nil
    41  }
    42  
    43  func (b *Buffer) WriteString(s string) (int, error) {
    44  	*b = append(*b, s...)
    45  	return len(s), nil
    46  }
    47  
    48  func (b *Buffer) WriteByte(c byte) error {
    49  	*b = append(*b, c)
    50  	return nil
    51  }
    52  
    53  func (b *Buffer) String() string {
    54  	return string(*b)
    55  }
    56  
    57  func (b *Buffer) Len() int {
    58  	return len(*b)
    59  }
    60  
    61  func (b *Buffer) SetLen(n int) {
    62  	*b = (*b)[:n]
    63  }
    64  

View as plain text