1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-19 19:06:43 -05:00
v2fly/transport/internet/kcp/output.go

80 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-08-06 15:59:22 -04:00
"github.com/v2ray/v2ray-core/transport/internet"
2016-06-27 16:52:48 -04:00
)
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 {
2016-07-17 06:59:57 -04:00
this.buffer = alloc.NewLocalBuffer(2048).Clear()
2016-06-27 16:52:48 -04:00
}
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-07-12 11:37:12 -04:00
go this.writer.Write(this.buffer)
2016-06-27 16:52:48 -04:00
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 {
2016-08-06 15:59:22 -04:00
Authenticator internet.Authenticator
2016-06-29 04:34:34 -04:00
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 {
2016-08-06 15:59:22 -04:00
return effectiveConfig.Mtu - uint32(this.Authenticator.Overhead())
2016-07-02 02:45:31 -04:00
}