2016-05-25 03:32:26 -04:00
|
|
|
package io
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
|
2016-08-20 14:55:45 -04:00
|
|
|
"v2ray.com/core/common/alloc"
|
2016-05-25 03:32:26 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type ChainWriter struct {
|
|
|
|
sync.Mutex
|
|
|
|
writer Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewChainWriter(writer Writer) *ChainWriter {
|
|
|
|
return &ChainWriter{
|
|
|
|
writer: writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *ChainWriter) Write(payload []byte) (int, error) {
|
|
|
|
v.Lock()
|
|
|
|
defer v.Unlock()
|
|
|
|
if v.writer == nil {
|
2016-11-17 17:21:44 -05:00
|
|
|
return 0, io.ErrClosedPipe
|
2016-05-25 03:32:26 -04:00
|
|
|
}
|
|
|
|
|
2016-11-19 16:38:24 -05:00
|
|
|
bytesWritten := 0
|
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
|
2016-11-19 15:12:52 -05:00
|
|
|
payload = payload[alloc.BufferSize:]
|
2016-11-19 16:38:24 -05:00
|
|
|
bytesWritten += alloc.BufferSize
|
2016-11-18 19:50:09 -05:00
|
|
|
} else {
|
|
|
|
buffer.Append(payload)
|
2016-11-19 16:38:24 -05:00
|
|
|
bytesWritten += size
|
2016-11-18 19:50:09 -05:00
|
|
|
size = 0
|
|
|
|
}
|
2016-11-27 15:39:09 -05:00
|
|
|
err := v.writer.Write(buffer)
|
2016-11-18 19:50:09 -05:00
|
|
|
if err != nil {
|
2016-11-19 16:38:24 -05:00
|
|
|
return bytesWritten, err
|
2016-11-18 19:50:09 -05:00
|
|
|
}
|
2016-05-25 03:32:26 -04:00
|
|
|
}
|
2016-11-18 19:50:09 -05:00
|
|
|
|
2016-11-19 16:38:24 -05:00
|
|
|
return bytesWritten, nil
|
2016-05-25 03:32:26 -04:00
|
|
|
}
|
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *ChainWriter) Release() {
|
|
|
|
v.Lock()
|
|
|
|
v.writer.Release()
|
|
|
|
v.writer = nil
|
|
|
|
v.Unlock()
|
2016-05-25 03:32:26 -04:00
|
|
|
}
|