-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
58 lines (50 loc) · 1006 Bytes
/
stream.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
package goetf
import (
"bytes"
"fmt"
"io"
"sync"
)
type streamer struct {
// buffer
buf []byte
// start of next data in buf
written int64
// writer buffer method
w io.Writer
}
var streamerPool = sync.Pool{
New: func() any {
return &streamer{}
},
}
func newStreamer(w io.Writer) *streamer {
stream := streamerPool.Get().(*streamer)
stream.written = 0
if w != nil {
stream.w = w
} else {
stream.buf = make([]byte, 0)
stream.w = bytes.NewBuffer(stream.buf)
}
return stream
}
func (s *streamer) writeByte(b byte) error {
_, err := s.write([]byte{b})
return err
}
func (s *streamer) write(p []byte) (int, error) {
n, err := s.w.Write(p)
s.add(n)
return n, err
}
func (s *streamer) readAll() ([]byte, error) {
r, ok := s.w.(io.Reader)
if !ok {
return nil, fmt.Errorf("writer should implements the io.Reader interface")
}
return io.ReadAll(r)
}
func (s *streamer) add(steps int) {
s.written += int64(steps)
}