forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffered_writer.go
108 lines (89 loc) · 1.78 KB
/
buffered_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
package io
import (
"io"
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
)
type BufferedWriter struct {
sync.Mutex
writer io.Writer
buffer *alloc.Buffer
cached bool
}
func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
return &BufferedWriter{
writer: rawWriter,
buffer: alloc.NewBuffer().Clear(),
cached: true,
}
}
func (this *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return 0, io.EOF
}
totalBytes := int64(0)
for {
nBytes, err := this.buffer.FillFrom(reader)
totalBytes += int64(nBytes)
if err != nil {
if err == io.EOF {
return totalBytes, nil
}
return totalBytes, err
}
this.FlushWithoutLock()
}
}
func (this *BufferedWriter) Write(b []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return 0, io.EOF
}
if !this.cached {
return this.writer.Write(b)
}
nBytes, _ := this.buffer.Write(b)
if this.buffer.IsFull() {
this.FlushWithoutLock()
}
return nBytes, nil
}
func (this *BufferedWriter) Flush() error {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return io.EOF
}
return this.FlushWithoutLock()
}
func (this *BufferedWriter) FlushWithoutLock() error {
defer this.buffer.Clear()
for !this.buffer.IsEmpty() {
nBytes, err := this.writer.Write(this.buffer.Value)
if err != nil {
return err
}
this.buffer.SliceFrom(nBytes)
}
return nil
}
func (this *BufferedWriter) Cached() bool {
return this.cached
}
func (this *BufferedWriter) SetCached(cached bool) {
this.cached = cached
if !cached && !this.buffer.IsEmpty() {
this.Flush()
}
}
func (this *BufferedWriter) Release() {
this.Flush()
this.Lock()
defer this.Unlock()
this.buffer.Release()
this.buffer = nil
this.writer = nil
}