1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-09 06:44:30 -04:00
v2fly/transport/internet/kcp/output.go

79 lines
1.5 KiB
Go
Raw Normal View History

2016-06-27 16:52:48 -04:00
package kcp
import (
2016-06-29 04:34:34 -04:00
"io"
2016-06-27 16:52:48 -04:00
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
)
2016-07-02 15:26:50 -04:00
type SegmentWriter interface {
2016-07-04 08:17:42 -04:00
Write(seg Segment)
2016-07-02 15:26:50 -04:00
}
type BufferedSegmentWriter struct {
2016-06-27 16:52:48 -04:00
sync.Mutex
mtu uint32
buffer *alloc.Buffer
writer v2io.Writer
}
2016-07-02 15:26:50 -04:00
func NewSegmentWriter(writer *AuthenticationWriter) *BufferedSegmentWriter {
return &BufferedSegmentWriter{
2016-07-02 02:45:31 -04:00
mtu: writer.Mtu(),
2016-06-27 16:52:48 -04:00
writer: writer,
}
}
2016-07-04 08:17:42 -04:00
func (this *BufferedSegmentWriter) Write(seg Segment) {
2016-06-27 16:52:48 -04:00
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()
}
2016-07-05 08:08:08 -04:00
this.buffer.Value = seg.Bytes(this.buffer.Value)
2016-06-27 16:52:48 -04:00
}
2016-07-02 15:26:50 -04:00
func (this *BufferedSegmentWriter) FlushWithoutLock() {
2016-06-27 16:52:48 -04:00
this.writer.Write(this.buffer)
this.buffer = nil
}
2016-07-02 15:26:50 -04:00
func (this *BufferedSegmentWriter) Flush() {
2016-06-27 16:52:48 -04:00
this.Lock()
defer this.Unlock()
if this.buffer.Len() == 0 {
return
}
this.FlushWithoutLock()
}
2016-06-29 04:34:34 -04:00
type AuthenticationWriter struct {
Authenticator Authenticator
Writer io.Writer
}
func (this *AuthenticationWriter) Write(payload *alloc.Buffer) error {
defer payload.Release()
this.Authenticator.Seal(payload)
_, err := this.Writer.Write(payload.Value)
return err
}
func (this *AuthenticationWriter) Release() {}
2016-07-02 02:45:31 -04:00
func (this *AuthenticationWriter) Mtu() uint32 {
return effectiveConfig.Mtu - uint32(this.Authenticator.HeaderSize())
}