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/writer.go

143 lines
2.6 KiB

package buf
7 years ago
import (
"io"
"v2ray.com/core/common/errors"
)
// BufferToBytesWriter is a Writer that writes alloc.Buffer into underlying writer.
type BufferToBytesWriter struct {
writer io.Writer
}
// Write implements Writer.Write(). Write() takes ownership of the given buffer.
func (w *BufferToBytesWriter) Write(mb MultiBuffer) error {
defer mb.Release()
bs := mb.ToNetBuffers()
_, err := bs.WriteTo(w.writer)
8 years ago
return err
}
8 years ago
type writerAdapter struct {
writer MultiBufferWriter
}
8 years ago
// Write implements buf.MultiBufferWriter.
8 years ago
func (w *writerAdapter) Write(mb MultiBuffer) error {
8 years ago
return w.writer.WriteMultiBuffer(mb)
8 years ago
}
type mergingWriter struct {
writer io.Writer
buffer []byte
}
func (w *mergingWriter) Write(mb MultiBuffer) error {
defer mb.Release()
for !mb.IsEmpty() {
nBytes, _ := mb.Read(w.buffer)
if _, err := w.writer.Write(w.buffer[:nBytes]); err != nil {
return err
}
}
return nil
}
8 years ago
type seqWriter struct {
writer io.Writer
}
func (w *seqWriter) Write(mb MultiBuffer) error {
defer mb.Release()
for _, b := range mb {
if b.IsEmpty() {
continue
}
if _, err := w.writer.Write(b.Bytes()); err != nil {
return err
}
}
return nil
}
8 years ago
var (
_ MultiBufferWriter = (*bytesToBufferWriter)(nil)
)
type bytesToBufferWriter struct {
writer Writer
}
8 years ago
// Write implements io.Writer.
8 years ago
func (w *bytesToBufferWriter) Write(payload []byte) (int, error) {
mb := NewMultiBuffer()
mb.Write(payload)
8 years ago
if err := w.writer.Write(mb); err != nil {
return 0, err
}
8 years ago
return len(payload), nil
}
8 years ago
func (w *bytesToBufferWriter) WriteMultiBuffer(mb MultiBuffer) error {
return w.writer.Write(mb)
}
func (w *bytesToBufferWriter) ReadFrom(reader io.Reader) (int64, error) {
mbReader := NewReader(reader)
totalBytes := int64(0)
eof := false
for !eof {
mb, err := mbReader.Read()
if err == io.EOF {
eof = true
} else if err != nil {
return totalBytes, err
}
totalBytes += int64(mb.Len())
if err := w.writer.Write(mb); err != nil {
return totalBytes, err
}
}
return totalBytes, nil
}
type noOpWriter struct{}
func (noOpWriter) Write(b MultiBuffer) error {
b.Release()
return nil
}
7 years ago
type noOpBytesWriter struct{}
func (noOpBytesWriter) Write(b []byte) (int, error) {
return len(b), nil
}
func (noOpBytesWriter) ReadFrom(reader io.Reader) (int64, error) {
b := New()
defer b.Release()
totalBytes := int64(0)
for {
err := b.Reset(ReadFrom(reader))
totalBytes += int64(b.Len())
if err != nil {
if errors.Cause(err) == io.EOF {
return totalBytes, nil
}
return totalBytes, err
}
}
}
var (
7 years ago
Discard Writer = noOpWriter{}
DiscardBytes io.Writer = noOpBytesWriter{}
)