github.com/searKing/golang/go@v1.2.117/log/slog/internal/buffer/bytes_buffer_pool.go (about) 1 // Copyright 2023 The searKing Author. 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 6 7 import ( 8 "bytes" 9 "encoding/json" 10 "sync" 11 ) 12 13 // Having an initial size gives a dramatic speedup. 14 var bufPool = sync.Pool{ 15 New: func() any { return new(Buffer) }, 16 } 17 18 type Buffer struct { 19 bytes.Buffer 20 } 21 22 func New() *Buffer { 23 return bufPool.Get().(*Buffer) 24 } 25 26 func (b *Buffer) Free() { 27 // To reduce peak allocation, return only smaller buffers to the pool. 28 const maxBufferSize = 16 << 10 29 if b.Cap() <= maxBufferSize { 30 b.Buffer.Reset() 31 bufPool.Put(b) 32 } 33 } 34 35 func (b *Buffer) WritePosInt(i int) { 36 b.WritePosIntWidth(i, 0) 37 } 38 39 // WritePosIntWidth writes non-negative integer i to the buffer, padded on the left 40 // by zeroes to the given width. Use a width of 0 to omit padding. 41 func (b *Buffer) WritePosIntWidth(i, width int) { 42 // Cheap integer to fixed-width decimal ASCII. 43 // Copied from log/log.go. 44 45 if i < 0 { 46 panic("negative int") 47 } 48 49 // Assemble decimal in reverse order. 50 var bb [20]byte 51 bp := len(bb) - 1 52 for i >= 10 || width > 1 { 53 width-- 54 q := i / 10 55 bb[bp] = byte('0' + i - q*10) 56 bp-- 57 i = q 58 } 59 // i < 10 60 bb[bp] = byte('0' + i) 61 b.Write(bb[bp:]) 62 } 63 64 // AppendJSONMarshal writes string represents v to the buffer. 65 func (b *Buffer) AppendJSONMarshal(v any) error { 66 // Use a json.Encoder to avoid escaping HTML. 67 var bb bytes.Buffer 68 enc := json.NewEncoder(&bb) 69 enc.SetEscapeHTML(false) 70 if err := enc.Encode(v); err != nil { 71 return err 72 } 73 bs := bb.Bytes() 74 b.Write(bs[:len(bs)-1]) // remove final newline 75 return nil 76 }