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

64 lines
1.3 KiB

package buf
import "io"
// 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 {
if mw, ok := w.writer.(MultiBufferWriter); ok {
_, err := mw.WriteMultiBuffer(mb)
return err
}
defer mb.Release()
bs := mb.ToNetBuffers()
_, err := bs.WriteTo(w.writer)
8 years ago
return err
}
type bytesToBufferWriter struct {
writer Writer
}
8 years ago
func (w *bytesToBufferWriter) Write(payload []byte) (int, error) {
mb := NewMultiBuffer()
for p := payload; len(p) > 0; {
b := New()
nBytes, _ := b.Write(p)
p = p[nBytes:]
mb.Append(b)
}
if err := w.writer.Write(mb); err != nil {
return 0, err
}
8 years ago
return len(payload), nil
}
8 years ago
func (w *bytesToBufferWriter) WriteMulteBuffer(mb MultiBuffer) (int, error) {
return mb.Len(), 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
}