1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-16 04:35:24 +00:00
v2fly/common/io/writer.go

45 lines
938 B
Go
Raw Normal View History

2016-02-01 11:22:29 +00:00
package io
import (
"io"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
2016-02-01 11:22:29 +00:00
)
2016-02-06 21:28:35 +00:00
// Writer extends io.Writer with alloc.Buffer.
2016-02-01 11:22:29 +00:00
type Writer interface {
2016-04-12 19:43:13 +00:00
common.Releasable
2016-02-06 21:28:35 +00:00
// Write writes an alloc.Buffer into underlying writer.
2016-02-01 11:22:29 +00:00
Write(*alloc.Buffer) error
}
2016-02-06 21:28:35 +00:00
// AdaptiveWriter is a Writer that writes alloc.Buffer into underlying writer.
2016-02-01 11:22:29 +00:00
type AdaptiveWriter struct {
writer io.Writer
}
2016-02-06 21:28:35 +00:00
// NewAdaptiveWriter creates a new AdaptiveWriter.
2016-02-01 11:22:29 +00:00
func NewAdaptiveWriter(writer io.Writer) *AdaptiveWriter {
return &AdaptiveWriter{
writer: writer,
}
}
2016-04-28 20:31:33 +00:00
// Write implements Writer.Write(). Write() takes ownership of the given buffer.
2016-02-01 11:22:29 +00:00
func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error {
2016-05-11 17:54:20 +00: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 11:22:29 +00:00
}
2016-05-11 17:54:20 +00:00
return nil
2016-02-01 11:22:29 +00:00
}
2016-03-11 22:51:58 +00:00
func (this *AdaptiveWriter) Release() {
this.writer = nil
}