1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00

segment writer

This commit is contained in:
v2ray 2016-06-27 22:52:48 +02:00
parent beea2528ce
commit 41b230994e
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169

View File

@ -0,0 +1,54 @@
package kcp
import (
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
)
type SegmentWriter struct {
sync.Mutex
mtu uint32
buffer *alloc.Buffer
writer v2io.Writer
}
func NewSegmentWriter(mtu uint32, writer v2io.Writer) *SegmentWriter {
return &SegmentWriter{
mtu: mtu,
writer: writer,
}
}
func (this *SegmentWriter) Write(seg ISegment) {
this.Lock()
defer this.Unlock()
nBytes := seg.ByteSize()
if uint32(this.buffer.Len()+nBytes) > this.mtu {
this.FlushWithoutLock()
}
if this.buffer == nil {
this.buffer = alloc.NewSmallBuffer().Clear()
}
this.buffer.Value = seg.Bytes(this.buffer.Value)
}
func (this *SegmentWriter) FlushWithoutLock() {
this.writer.Write(this.buffer)
this.buffer = nil
}
func (this *SegmentWriter) Flush() {
this.Lock()
defer this.Unlock()
if this.buffer.Len() == 0 {
return
}
this.FlushWithoutLock()
}