github.phpd.cn/cilium/cilium@v1.6.12/test/helpers/buffer.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package helpers 16 17 import ( 18 "bytes" 19 20 "github.com/cilium/cilium/pkg/lock" 21 ) 22 23 // A Buffer is a variable-sized buffer of bytes with Read and Write methods. 24 // The zero value for Buffer is an empty buffer ready to use. 25 type Buffer struct { 26 buffer bytes.Buffer 27 mutex lock.Mutex 28 } 29 30 // Write appends the contents of p to the buffer, growing the buffer as 31 // needed. The return value n is the length of p; err is always nil. If the 32 // buffer becomes too large, Write will panic with ErrTooLarge. 33 func (buf *Buffer) Write(p []byte) (n int, err error) { 34 buf.mutex.Lock() 35 r, err := buf.buffer.Write(p) 36 buf.mutex.Unlock() 37 return r, err 38 } 39 40 // String returns the contents of the unread portion of the buffer 41 // as a string. If the Buffer is a nil pointer, it returns "<nil>". 42 // 43 // To build strings more efficiently, see the strings.Builder type. 44 func (buf *Buffer) String() string { 45 buf.mutex.Lock() 46 r := buf.buffer.String() 47 buf.mutex.Unlock() 48 return r 49 } 50 51 // Reset resets the buffer to be empty, 52 // but it retains the underlying storage for use by future writes. 53 // Reset is the same as Truncate(0). 54 func (buf *Buffer) Reset() { 55 buf.mutex.Lock() 56 buf.buffer.Reset() 57 buf.mutex.Unlock() 58 } 59 60 // Len returns the number of bytes of the unread portion of the buffer; 61 // b.Len() == len(b.Bytes()). 62 func (buf *Buffer) Len() int { 63 buf.mutex.Lock() 64 r := buf.buffer.Len() 65 buf.mutex.Unlock() 66 return r 67 } 68 69 // Bytes returns a slice of length b.Len() holding the unread portion of the buffer. 70 // The slice is valid for use only until the next buffer modification (that is, 71 // only until the next call to a method like Read, Write, Reset, or Truncate). 72 // The slice aliases the buffer content at least until the next buffer modification, 73 // so immediate changes to the slice will affect the result of future reads. 74 func (buf *Buffer) Bytes() []byte { 75 buf.mutex.Lock() 76 r := buf.buffer.Bytes() 77 buf.mutex.Unlock() 78 return r 79 }