field_fmt.go (1466B)
1 //go:build !kvformat 2 // +build !kvformat 3 4 package kv 5 6 import ( 7 "fmt" 8 "sync" 9 10 "codeberg.org/gruf/go-byteutil" 11 ) 12 13 // bufPool is a memory pool of byte buffers. 14 var bufPool = sync.Pool{ 15 New: func() interface{} { 16 return &byteutil.Buffer{B: make([]byte, 0, 512)} 17 }, 18 } 19 20 // AppendFormat will append formatted format of Field to 'buf'. See .String() for details. 21 func (f Field) AppendFormat(buf *byteutil.Buffer, vbose bool) { 22 var fmtstr string 23 if vbose /* verbose */ { 24 fmtstr = `%#v` 25 } else /* regular */ { 26 fmtstr = `%+v` 27 } 28 AppendQuoteString(buf, f.K) 29 buf.WriteByte('=') 30 appendValuef(buf, fmtstr, f.V) 31 } 32 33 // Value returns the formatted value string of this Field. 34 func (f Field) Value(vbose bool) string { 35 var fmtstr string 36 if vbose /* verbose */ { 37 fmtstr = `%#v` 38 } else /* regular */ { 39 fmtstr = `%+v` 40 } 41 buf := byteutil.Buffer{B: make([]byte, 0, bufsize/2)} 42 appendValuef(&buf, fmtstr, f.V) 43 return buf.String() 44 } 45 46 // appendValuef appends a quoted value string (formatted by fmt.Appendf) to 'buf'. 47 func appendValuef(buf *byteutil.Buffer, format string, args ...interface{}) { 48 // Write format string to a byte buffer 49 fmtbuf := bufPool.Get().(*byteutil.Buffer) 50 fmtbuf.B = fmt.Appendf(fmtbuf.B, format, args...) 51 52 // Append quoted value to dst buffer 53 AppendQuoteValue(buf, fmtbuf.String()) 54 55 // Drop overly large capacity buffers 56 if fmtbuf.Cap() > int(^uint16(0)) { 57 return 58 } 59 60 // Replace buffer in pool 61 fmtbuf.Reset() 62 bufPool.Put(fmtbuf) 63 }