buffer.go (2341B)
1 package bytes 2 3 import ( 4 "unicode/utf8" 5 ) 6 7 // Buffer is a very simple buffer implementation that allows 8 // access to and reslicing of the underlying byte slice. 9 type Buffer struct { 10 B []byte 11 } 12 13 func NewBuffer(b []byte) Buffer { 14 return Buffer{ 15 B: b, 16 } 17 } 18 19 func (b *Buffer) Write(p []byte) (int, error) { 20 b.Grow(len(p)) 21 return copy(b.B[b.Len()-len(p):], p), nil 22 } 23 24 func (b *Buffer) WriteString(s string) (int, error) { 25 b.Grow(len(s)) 26 return copy(b.B[b.Len()-len(s):], s), nil 27 } 28 29 func (b *Buffer) WriteByte(c byte) error { 30 l := b.Len() 31 b.Grow(1) 32 b.B[l] = c 33 return nil 34 } 35 36 func (b *Buffer) WriteRune(r rune) (int, error) { 37 if r < utf8.RuneSelf { 38 b.WriteByte(byte(r)) 39 return 1, nil 40 } 41 42 l := b.Len() 43 b.Grow(utf8.UTFMax) 44 n := utf8.EncodeRune(b.B[l:b.Len()], r) 45 b.B = b.B[:l+n] 46 47 return n, nil 48 } 49 50 func (b *Buffer) WriteAt(p []byte, start int64) (int, error) { 51 b.Grow(len(p) - int(int64(b.Len())-start)) 52 return copy(b.B[start:], p), nil 53 } 54 55 func (b *Buffer) WriteStringAt(s string, start int64) (int, error) { 56 b.Grow(len(s) - int(int64(b.Len())-start)) 57 return copy(b.B[start:], s), nil 58 } 59 60 func (b *Buffer) Truncate(size int) { 61 b.B = b.B[:b.Len()-size] 62 } 63 64 func (b *Buffer) ShiftByte(index int) { 65 copy(b.B[index:], b.B[index+1:]) 66 } 67 68 func (b *Buffer) Shift(start int64, size int) { 69 copy(b.B[start:], b.B[start+int64(size):]) 70 } 71 72 func (b *Buffer) DeleteByte(index int) { 73 b.ShiftByte(index) 74 b.Truncate(1) 75 } 76 77 func (b *Buffer) Delete(start int64, size int) { 78 b.Shift(start, size) 79 b.Truncate(size) 80 } 81 82 func (b *Buffer) InsertByte(index int64, c byte) { 83 l := b.Len() 84 b.Grow(1) 85 copy(b.B[index+1:], b.B[index:l]) 86 b.B[index] = c 87 } 88 89 func (b *Buffer) Insert(index int64, p []byte) { 90 l := b.Len() 91 b.Grow(len(p)) 92 copy(b.B[index+int64(len(p)):], b.B[index:l]) 93 copy(b.B[index:], p) 94 } 95 96 func (b *Buffer) Bytes() []byte { 97 return b.B 98 } 99 100 func (b *Buffer) String() string { 101 return string(b.B) 102 } 103 104 func (b *Buffer) StringPtr() string { 105 return BytesToString(b.B) 106 } 107 108 func (b *Buffer) Cap() int { 109 return cap(b.B) 110 } 111 112 func (b *Buffer) Len() int { 113 return len(b.B) 114 } 115 116 func (b *Buffer) Reset() { 117 b.B = b.B[:0] 118 } 119 120 func (b *Buffer) Grow(size int) { 121 b.Guarantee(size) 122 b.B = b.B[:b.Len()+size] 123 } 124 125 func (b *Buffer) Guarantee(size int) { 126 if size > b.Cap()-b.Len() { 127 nb := make([]byte, 2*b.Cap()+size) 128 copy(nb, b.B) 129 b.B = nb[:b.Len()] 130 } 131 }