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/io/buffered_writer.go

66 lines
1.1 KiB

package io
import (
"io"
"github.com/v2ray/v2ray-core/common/alloc"
)
type BufferedWriter struct {
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) Write(b []byte) (int, error) {
if !this.cached {
return this.writer.Write(b)
}
nBytes, _ := this.buffer.Write(b)
if this.buffer.IsFull() {
err := this.Flush()
if err != nil {
return nBytes, err
}
}
return nBytes, nil
}
func (this *BufferedWriter) Flush() error {
9 years ago
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)
}
9 years ago
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() {
9 years ago
this.Flush()
this.buffer.Release()
this.buffer = nil
this.writer = nil
}