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