1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-03 10:15:20 -04:00
v2fly/common/io/chain_writer.go

53 lines
817 B
Go
Raw Normal View History

package io
import (
"io"
"sync"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/alloc"
)
type ChainWriter struct {
sync.Mutex
writer Writer
}
func NewChainWriter(writer Writer) *ChainWriter {
return &ChainWriter{
writer: writer,
}
}
func (this *ChainWriter) Write(payload []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.writer == nil {
2016-11-17 17:21:44 -05:00
return 0, io.ErrClosedPipe
}
2016-11-18 19:50:09 -05:00
size := len(payload)
for size > 0 {
buffer := alloc.NewBuffer().Clear()
if size > alloc.BufferSize {
buffer.Append(payload[:alloc.BufferSize])
size -= alloc.BufferSize
} else {
buffer.Append(payload)
size = 0
}
err := this.writer.Write(buffer)
if err != nil {
return 0, err
}
}
2016-11-18 19:50:09 -05:00
return size, nil
}
func (this *ChainWriter) Release() {
this.Lock()
this.writer.Release()
this.writer = nil
this.Unlock()
}