You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/bufio/writer.go

122 lines
2.0 KiB

package bufio
import (
"io"
"sync"
8 years ago
"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,
8 years ago
buffer: buf.NewSmall(),
cached: true,
}
}
8 years ago
func (v *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
v.Lock()
defer v.Unlock()
8 years ago
if v.writer == nil {
return 0, io.ErrClosedPipe
}
totalBytes := int64(0)
for {
8 years ago
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
}
8 years ago
v.FlushWithoutLock()
}
}
8 years ago
func (v *BufferedWriter) Write(b []byte) (int, error) {
v.Lock()
defer v.Unlock()
8 years ago
if v.writer == nil {
return 0, io.ErrClosedPipe
}
8 years ago
if !v.cached {
return v.writer.Write(b)
}
nBytes, err := v.buffer.Write(b)
if err != nil {
return 0, err
}
8 years ago
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
}
8 years ago
func (v *BufferedWriter) Flush() error {
v.Lock()
defer v.Unlock()
8 years ago
if v.writer == nil {
return io.ErrClosedPipe
}
8 years ago
return v.FlushWithoutLock()
}
8 years ago
func (v *BufferedWriter) FlushWithoutLock() error {
defer v.buffer.Clear()
for !v.buffer.IsEmpty() {
nBytes, err := v.writer.Write(v.buffer.Bytes())
9 years ago
if err != nil {
return err
}
8 years ago
v.buffer.SliceFrom(nBytes)
}
9 years ago
return nil
}
8 years ago
func (v *BufferedWriter) Cached() bool {
return v.cached
}
8 years ago
func (v *BufferedWriter) SetCached(cached bool) {
v.cached = cached
if !cached && !v.buffer.IsEmpty() {
v.Flush()
}
}
8 years ago
func (v *BufferedWriter) Release() {
v.Flush()
8 years ago
v.Lock()
defer v.Unlock()
8 years ago
v.buffer.Release()
v.buffer = nil
v.writer = nil
}