1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-10-31 00:08:08 -04:00
v2fly/common/buf/writer.go

47 lines
925 B
Go
Raw Normal View History

2016-12-09 07:17:34 -05:00
package buf
2016-12-27 14:53:29 -05:00
import "io"
2016-12-09 07:17:34 -05:00
// 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 (v *BufferToBytesWriter) Write(buffer *Buffer) error {
defer buffer.Release()
for {
nBytes, err := v.writer.Write(buffer.Bytes())
if err != nil {
return err
}
if nBytes == buffer.Len() {
break
}
buffer.SliceFrom(nBytes)
}
return nil
}
2017-02-20 04:33:35 -05:00
type bytesToBufferWriter struct {
2016-12-09 07:17:34 -05:00
writer Writer
}
2017-02-20 04:33:35 -05:00
func (v *bytesToBufferWriter) Write(payload []byte) (int, error) {
2016-12-09 07:17:34 -05:00
bytesWritten := 0
size := len(payload)
for size > 0 {
buffer := New()
nBytes, _ := buffer.Write(payload)
size -= nBytes
payload = payload[nBytes:]
bytesWritten += nBytes
err := v.writer.Write(buffer)
if err != nil {
return bytesWritten, err
}
}
return bytesWritten, nil
}