github.com/AndrienkoAleksandr/go@v0.0.19/src/log/slog/internal/buffer/buffer.go (about) 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 = (*b)[: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) WritePosInt(i int) { 54 b.WritePosIntWidth(i, 0) 55 } 56 57 // WritePosIntWidth writes non-negative integer i to the buffer, padded on the left 58 // by zeroes to the given width. Use a width of 0 to omit padding. 59 func (b *Buffer) WritePosIntWidth(i, width int) { 60 // Cheap integer to fixed-width decimal ASCII. 61 // Copied from log/log.go. 62 63 if i < 0 { 64 panic("negative int") 65 } 66 67 // Assemble decimal in reverse order. 68 var bb [20]byte 69 bp := len(bb) - 1 70 for i >= 10 || width > 1 { 71 width-- 72 q := i / 10 73 bb[bp] = byte('0' + i - q*10) 74 bp-- 75 i = q 76 } 77 // i < 10 78 bb[bp] = byte('0' + i) 79 b.Write(bb[bp:]) 80 } 81 82 func (b *Buffer) String() string { 83 return string(*b) 84 }