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

93 lines
2.1 KiB

package buf
import (
"io"
8 years ago
"v2ray.com/core/common/errors"
)
// BufferedWriter is an io.Writer with internal buffer. It writes to underlying writer when buffer is full or on demand.
// This type is not thread safe.
type BufferedWriter struct {
writer io.Writer
buffer *Buffer
buffered bool
}
// NewBufferedWriter creates a new BufferedWriter.
func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
return &BufferedWriter{
writer: rawWriter,
buffer: NewLocal(1024),
buffered: true,
}
}
8 years ago
// ReadFrom implements io.ReaderFrom.ReadFrom().
8 years ago
func (v *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
totalBytes := int64(0)
for {
8 years ago
oriSize := v.buffer.Len()
err := v.buffer.AppendSupplier(ReadFrom(reader))
8 years ago
totalBytes += int64(v.buffer.Len() - oriSize)
if err != nil {
if errors.Cause(err) == io.EOF {
return totalBytes, nil
}
return totalBytes, err
}
if err := v.Flush(); err != nil {
return totalBytes, err
}
}
}
8 years ago
func (v *BufferedWriter) Write(b []byte) (int, error) {
if !v.buffered || v.buffer == nil {
8 years ago
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.Flush()
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
// Flush writes all buffered content into underlying writer, if any.
8 years ago
func (v *BufferedWriter) Flush() 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
// IsBuffered returns true if this BufferedWriter holds a buffer.
func (v *BufferedWriter) IsBuffered() bool {
return v.buffered
}
8 years ago
// SetBuffered controls whether the BufferedWriter holds a buffer for writing. If not buffered, any write() calls into underlying writer directly.
func (v *BufferedWriter) SetBuffered(cached bool) error {
v.buffered = cached
8 years ago
if !cached && !v.buffer.IsEmpty() {
return v.Flush()
}
return nil
}