github.com/vedadiyan/sqlparser@v1.0.0/pkg/bytes2/buffer.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package bytes2 18 19 import "unsafe" 20 21 // Buffer implements a subset of the write portion of 22 // bytes.Buffer, but more efficiently. This is meant to 23 // be used in very high QPS operations, especially for 24 // WriteByte, and without abstracting it as a Writer. 25 // Function signatures contain errors for compatibility, 26 // but they do not return errors. 27 type Buffer struct { 28 bytes []byte 29 } 30 31 // NewBuffer is equivalent to bytes.NewBuffer. 32 func NewBuffer(b []byte) *Buffer { 33 return &Buffer{bytes: b} 34 } 35 36 // Write is equivalent to bytes.Buffer.Write. 37 func (buf *Buffer) Write(b []byte) (int, error) { 38 buf.bytes = append(buf.bytes, b...) 39 return len(b), nil 40 } 41 42 // WriteString is equivalent to bytes.Buffer.WriteString. 43 func (buf *Buffer) WriteString(s string) (int, error) { 44 buf.bytes = append(buf.bytes, s...) 45 return len(s), nil 46 } 47 48 // WriteByte is equivalent to bytes.Buffer.WriteByte. 49 func (buf *Buffer) WriteByte(b byte) error { 50 buf.bytes = append(buf.bytes, b) 51 return nil 52 } 53 54 // Bytes is equivalent to bytes.Buffer.Bytes. 55 func (buf *Buffer) Bytes() []byte { 56 return buf.bytes 57 } 58 59 // Strings is equivalent to bytes.Buffer.Strings. 60 func (buf *Buffer) String() string { 61 return string(buf.bytes) 62 } 63 64 // StringUnsafe is equivalent to String, but the copy of the string that it returns 65 // is _not_ allocated, so modifying this buffer after calling StringUnsafe will lead 66 // to undefined behavior. 67 func (buf *Buffer) StringUnsafe() string { 68 return *(*string)(unsafe.Pointer(&buf.bytes)) 69 } 70 71 // Reset is equivalent to bytes.Buffer.Reset. 72 func (buf *Buffer) Reset() { 73 buf.bytes = buf.bytes[:0] 74 } 75 76 // Len is equivalent to bytes.Buffer.Len. 77 func (buf *Buffer) Len() int { 78 return len(buf.bytes) 79 }