codeberg.org/gruf/go-format@v1.0.6/buffer.go (about) 1 package format 2 3 import ( 4 "io" 5 "unicode/utf8" 6 "unsafe" 7 ) 8 9 // ensure we conform to io.Writer. 10 var _ io.Writer = (*Buffer)(nil) 11 12 // Buffer is a simple wrapper around a byte slice. 13 type Buffer struct { 14 B []byte 15 } 16 17 // Write will append given byte slice to buffer, fulfilling io.Writer. 18 func (buf *Buffer) Write(b []byte) (int, error) { 19 buf.B = append(buf.B, b...) 20 return len(b), nil 21 } 22 23 // AppendByte appends given byte to the buffer. 24 func (buf *Buffer) AppendByte(b byte) { 25 buf.B = append(buf.B, b) 26 } 27 28 // AppendRune appends given rune to the buffer. 29 func (buf *Buffer) AppendRune(r rune) { 30 if r < utf8.RuneSelf { 31 buf.B = append(buf.B, byte(r)) 32 return 33 } 34 35 l := buf.Len() 36 for i := 0; i < utf8.UTFMax; i++ { 37 buf.B = append(buf.B, 0) 38 } 39 40 n := utf8.EncodeRune(buf.B[l:buf.Len()], r) 41 buf.B = buf.B[:l+n] 42 } 43 44 // Append will append given byte slice to the buffer. 45 func (buf *Buffer) Append(b []byte) { 46 buf.B = append(buf.B, b...) 47 } 48 49 // AppendString appends given string to the buffer. 50 func (buf *Buffer) AppendString(s string) { 51 buf.B = append(buf.B, s...) 52 } 53 54 // Len returns the length of the buffer's underlying byte slice. 55 func (buf *Buffer) Len() int { 56 return len(buf.B) 57 } 58 59 // Cap returns the capacity of the buffer's underlying byte slice. 60 func (buf *Buffer) Cap() int { 61 return cap(buf.B) 62 } 63 64 // Truncate will reduce the length of the buffer by 'n'. 65 func (buf *Buffer) Truncate(n int) { 66 if n > len(buf.B) { 67 n = len(buf.B) 68 } 69 buf.B = buf.B[:buf.Len()-n] 70 } 71 72 // Reset will reset the buffer length to 0 (retains capacity). 73 func (buf *Buffer) Reset() { 74 buf.B = buf.B[:0] 75 } 76 77 // String returns the underlying byte slice as a string. Please note 78 // this value is tied directly to the underlying byte slice, if you 79 // write to the buffer then returned string values will also change. 80 func (buf *Buffer) String() string { 81 return *(*string)(unsafe.Pointer(&buf.B)) 82 }