v2ray-core/transport/internet/kcp/output.go

56 lines
862 B
Go
Raw Normal View History

2016-06-27 20:52:48 +00:00
package kcp
import (
2016-06-29 08:34:34 +00:00
"io"
2016-06-27 20:52:48 +00:00
"sync"
2016-12-09 10:35:27 +00:00
"v2ray.com/core/common/buf"
2016-06-27 20:52:48 +00:00
)
2016-07-02 19:26:50 +00:00
type SegmentWriter interface {
2016-07-04 12:17:42 +00:00
Write(seg Segment)
2016-07-02 19:26:50 +00:00
}
type BufferedSegmentWriter struct {
2016-06-27 20:52:48 +00:00
sync.Mutex
mtu uint32
2016-12-09 10:35:27 +00:00
buffer *buf.Buffer
2016-12-08 15:27:41 +00:00
writer io.Writer
2016-06-27 20:52:48 +00:00
}
2016-12-08 15:27:41 +00:00
func NewSegmentWriter(writer io.Writer, mtu uint32) *BufferedSegmentWriter {
2016-07-02 19:26:50 +00:00
return &BufferedSegmentWriter{
2016-12-08 15:27:41 +00:00
mtu: mtu,
2016-06-27 20:52:48 +00:00
writer: writer,
2016-12-09 11:08:25 +00:00
buffer: buf.NewSmall(),
2016-06-27 20:52:48 +00:00
}
}
2016-11-27 20:39:09 +00:00
func (v *BufferedSegmentWriter) Write(seg Segment) {
v.Lock()
defer v.Unlock()
2016-06-27 20:52:48 +00:00
nBytes := seg.ByteSize()
2016-11-27 20:39:09 +00:00
if uint32(v.buffer.Len()+nBytes) > v.mtu {
v.FlushWithoutLock()
2016-06-27 20:52:48 +00:00
}
2016-12-09 11:08:25 +00:00
v.buffer.AppendSupplier(seg.Bytes())
2016-06-27 20:52:48 +00:00
}
2016-11-27 20:39:09 +00:00
func (v *BufferedSegmentWriter) FlushWithoutLock() {
2016-12-08 15:27:41 +00:00
v.writer.Write(v.buffer.Bytes())
v.buffer.Clear()
2016-06-27 20:52:48 +00:00
}
2016-11-27 20:39:09 +00:00
func (v *BufferedSegmentWriter) Flush() {
v.Lock()
defer v.Unlock()
2016-06-27 20:52:48 +00:00
2016-12-08 15:27:41 +00:00
if v.buffer.IsEmpty() {
2016-06-27 20:52:48 +00:00
return
}
2016-11-27 20:39:09 +00:00
v.FlushWithoutLock()
2016-06-27 20:52:48 +00:00
}