-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
85 lines (73 loc) · 1.35 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
80
81
82
83
84
85
package tsbuffer
import (
"bytes"
"sync"
"github.com/pkg/errors"
)
var ErrBufferClosed = errors.New("buffer closed")
func New() *TSBuffer {
return &TSBuffer{
buffer: &bytes.Buffer{},
closed: false,
mu: &sync.RWMutex{},
cursor: 0,
}
}
type TSBuffer struct {
buffer *bytes.Buffer
closed bool
mu *sync.RWMutex
cursor int
}
func (sb *TSBuffer) Len() int {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.buffer.Len()
}
func (sb *TSBuffer) Read(p []byte) (n int, err error) {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.buffer.Read(p)
}
func (sb *TSBuffer) String() string {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.buffer.String()
}
func (sb *TSBuffer) Bytes() []byte {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.buffer.Bytes()
}
func (sb *TSBuffer) Close() error {
sb.mu.Lock()
defer sb.mu.Unlock()
sb.closed = true
return nil
}
func (sb *TSBuffer) Write(p []byte) (n int, err error) {
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.closed {
err = ErrBufferClosed
return
}
return sb.buffer.Write(p)
}
func (sb *TSBuffer) WriteString(str string) (n int, err error) {
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.closed {
err = ErrBufferClosed
return
}
return sb.buffer.WriteString(str)
}
func (sb *TSBuffer) Truncate(n int) {
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.closed {
return
}
sb.buffer.Truncate(n)
}