1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 17:27:50 -04:00
v2fly/common/io/writer.go
2016-11-27 21:39:09 +01:00

45 lines
926 B
Go

package io
import (
"io"
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
)
// Writer extends io.Writer with alloc.Buffer.
type Writer interface {
common.Releasable
// Write writes an alloc.Buffer into underlying writer.
Write(*alloc.Buffer) error
}
// AdaptiveWriter is a Writer that writes alloc.Buffer into underlying writer.
type AdaptiveWriter struct {
writer io.Writer
}
// NewAdaptiveWriter creates a new AdaptiveWriter.
func NewAdaptiveWriter(writer io.Writer) *AdaptiveWriter {
return &AdaptiveWriter{
writer: writer,
}
}
// Write implements Writer.Write(). Write() takes ownership of the given buffer.
func (v *AdaptiveWriter) Write(buffer *alloc.Buffer) error {
defer buffer.Release()
for !buffer.IsEmpty() {
nBytes, err := v.writer.Write(buffer.Value)
if err != nil {
return err
}
buffer.SliceFrom(nBytes)
}
return nil
}
func (v *AdaptiveWriter) Release() {
v.writer = nil
}