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

42 lines
949 B
Go
Raw Normal View History

2016-02-01 11:22:29 +00:00
package io
import (
"io"
2016-04-12 19:43:13 +00:00
"github.com/v2ray/v2ray-core/common"
2016-02-01 11:22:29 +00:00
"github.com/v2ray/v2ray-core/common/alloc"
)
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 {
nBytes, err := this.writer.Write(buffer.Value)
if nBytes < buffer.Len() {
_, err = this.writer.Write(buffer.Value[nBytes:])
}
2016-04-18 16:44:10 +00:00
buffer.Release()
2016-02-01 11:22:29 +00:00
return err
}
2016-03-11 22:51:58 +00:00
func (this *AdaptiveWriter) Release() {
this.writer = nil
}