forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffered_reader.go
68 lines (55 loc) · 1.06 KB
/
buffered_reader.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
package io
import (
"io"
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
)
type BufferedReader struct {
sync.Mutex
reader io.Reader
buffer *alloc.Buffer
cached bool
}
func NewBufferedReader(rawReader io.Reader) *BufferedReader {
return &BufferedReader{
reader: rawReader,
buffer: alloc.NewBuffer().Clear(),
cached: true,
}
}
func (this *BufferedReader) Release() {
this.Lock()
defer this.Unlock()
this.buffer.Release()
this.buffer = nil
this.reader = nil
}
func (this *BufferedReader) Cached() bool {
return this.cached
}
func (this *BufferedReader) SetCached(cached bool) {
this.cached = cached
}
func (this *BufferedReader) Read(b []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.reader == nil {
return 0, io.EOF
}
if !this.cached {
if !this.buffer.IsEmpty() {
return this.buffer.Read(b)
}
return this.reader.Read(b)
}
if this.buffer.IsEmpty() {
_, err := this.buffer.FillFrom(this.reader)
if err != nil {
return 0, err
}
}
if this.buffer.IsEmpty() {
return 0, nil
}
return this.buffer.Read(b)
}