1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 02:26:49 -05:00
v2fly/transport/internet/kcp/output.go

81 lines
1.4 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"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/alloc"
v2io "v2ray.com/core/common/io"
"v2ray.com/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-11-27 15:39:09 -05:00
func (v *BufferedSegmentWriter) Write(seg Segment) {
v.Lock()
defer v.Unlock()
2016-06-27 16:52:48 -04:00
nBytes := seg.ByteSize()
2016-11-27 15:39:09 -05:00
if uint32(v.buffer.Len()+nBytes) > v.mtu {
v.FlushWithoutLock()
2016-06-27 16:52:48 -04:00
}
2016-11-27 15:39:09 -05:00
if v.buffer == nil {
v.buffer = alloc.NewSmallBuffer().Clear()
2016-06-27 16:52:48 -04:00
}
2016-11-27 15:39:09 -05:00
v.buffer.Value = seg.Bytes(v.buffer.Value)
2016-06-27 16:52:48 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *BufferedSegmentWriter) FlushWithoutLock() {
v.writer.Write(v.buffer)
v.buffer = nil
2016-06-27 16:52:48 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *BufferedSegmentWriter) Flush() {
v.Lock()
defer v.Unlock()
2016-06-27 16:52:48 -04:00
2016-11-27 15:39:09 -05:00
if v.buffer.Len() == 0 {
2016-06-27 16:52:48 -04:00
return
}
2016-11-27 15:39:09 -05:00
v.FlushWithoutLock()
2016-06-27 16:52:48 -04:00
}
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
2016-10-02 17:43:58 -04:00
Config *Config
2016-06-29 04:34:34 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *AuthenticationWriter) Write(payload *alloc.Buffer) error {
2016-06-29 04:34:34 -04:00
defer payload.Release()
2016-11-27 15:39:09 -05:00
v.Authenticator.Seal(payload)
_, err := v.Writer.Write(payload.Value)
2016-06-29 04:34:34 -04:00
return err
}
2016-11-27 15:39:09 -05:00
func (v *AuthenticationWriter) Release() {}
2016-07-02 02:45:31 -04:00
2016-11-27 15:39:09 -05:00
func (v *AuthenticationWriter) Mtu() uint32 {
return v.Config.Mtu.GetValue() - uint32(v.Authenticator.Overhead())
2016-07-02 02:45:31 -04:00
}