1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-07 02:38:10 -05:00
v2fly/common/io/writer.go

45 lines
938 B
Go
Raw Normal View History

2016-02-01 06:22:29 -05:00
package io
import (
"io"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
2016-02-01 06:22:29 -05:00
)
2016-02-06 16:28:35 -05:00
// Writer extends io.Writer with alloc.Buffer.
2016-02-01 06:22:29 -05:00
type Writer interface {
2016-04-12 15:43:13 -04:00
common.Releasable
2016-02-06 16:28:35 -05:00
// Write writes an alloc.Buffer into underlying writer.
2016-02-01 06:22:29 -05:00
Write(*alloc.Buffer) error
}
2016-02-06 16:28:35 -05:00
// AdaptiveWriter is a Writer that writes alloc.Buffer into underlying writer.
2016-02-01 06:22:29 -05:00
type AdaptiveWriter struct {
writer io.Writer
}
2016-02-06 16:28:35 -05:00
// NewAdaptiveWriter creates a new AdaptiveWriter.
2016-02-01 06:22:29 -05:00
func NewAdaptiveWriter(writer io.Writer) *AdaptiveWriter {
return &AdaptiveWriter{
writer: writer,
}
}
2016-04-28 16:31:33 -04:00
// Write implements Writer.Write(). Write() takes ownership of the given buffer.
2016-02-01 06:22:29 -05:00
func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error {
2016-05-11 13:54:20 -04:00
defer buffer.Release()
for !buffer.IsEmpty() {
nBytes, err := this.writer.Write(buffer.Value)
if err != nil {
return err
}
buffer.SliceFrom(nBytes)
2016-02-01 06:22:29 -05:00
}
2016-05-11 13:54:20 -04:00
return nil
2016-02-01 06:22:29 -05:00
}
2016-03-11 17:51:58 -05:00
func (this *AdaptiveWriter) Release() {
this.writer = nil
}