-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
126 lines (106 loc) · 2.06 KB
/
writer.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package bufio
import (
"io"
"sync"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
)
type BufferedWriter struct {
sync.Mutex
writer io.Writer
buffer *buf.Buffer
cached bool
}
func NewWriter(rawWriter io.Writer) *BufferedWriter {
return &BufferedWriter{
writer: rawWriter,
buffer: buf.NewSmall(),
cached: true,
}
}
func (v *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
v.Lock()
defer v.Unlock()
if v.writer == nil {
return 0, io.ErrClosedPipe
}
totalBytes := int64(0)
for {
oriSize := v.buffer.Len()
err := v.buffer.AppendSupplier(buf.ReadFrom(reader))
totalBytes += int64(v.buffer.Len() - oriSize)
if err != nil {
if errors.Cause(err) == io.EOF {
return totalBytes, nil
}
return totalBytes, err
}
v.FlushWithoutLock()
}
}
func (v *BufferedWriter) Write(b []byte) (int, error) {
v.Lock()
defer v.Unlock()
if v.writer == nil {
return 0, io.ErrClosedPipe
}
if !v.cached {
return v.writer.Write(b)
}
nBytes, err := v.buffer.Write(b)
if err != nil {
return 0, err
}
if v.buffer.IsFull() {
err := v.FlushWithoutLock()
if err != nil {
return 0, err
}
if nBytes < len(b) {
if _, err := v.writer.Write(b[nBytes:]); err != nil {
return nBytes, err
}
}
}
return len(b), nil
}
func (v *BufferedWriter) Flush() error {
v.Lock()
defer v.Unlock()
if v.writer == nil {
return io.ErrClosedPipe
}
return v.FlushWithoutLock()
}
func (v *BufferedWriter) FlushWithoutLock() error {
defer v.buffer.Clear()
for !v.buffer.IsEmpty() {
nBytes, err := v.writer.Write(v.buffer.Bytes())
if err != nil {
return err
}
v.buffer.SliceFrom(nBytes)
}
return nil
}
func (v *BufferedWriter) Cached() bool {
return v.cached
}
func (v *BufferedWriter) SetCached(cached bool) {
v.cached = cached
if !cached && !v.buffer.IsEmpty() {
v.Flush()
}
}
func (v *BufferedWriter) Release() {
v.Flush()
v.Lock()
defer v.Unlock()
v.buffer.Release()
v.buffer = nil
if releasable, ok := v.writer.(common.Releasable); ok {
releasable.Release()
}
v.writer = nil
}