output.go 920 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package kcp
  2. import (
  3. "sync"
  4. "github.com/v2ray/v2ray-core/common/alloc"
  5. v2io "github.com/v2ray/v2ray-core/common/io"
  6. )
  7. type SegmentWriter struct {
  8. sync.Mutex
  9. mtu uint32
  10. buffer *alloc.Buffer
  11. writer v2io.Writer
  12. }
  13. func NewSegmentWriter(mtu uint32, writer v2io.Writer) *SegmentWriter {
  14. return &SegmentWriter{
  15. mtu: mtu,
  16. writer: writer,
  17. }
  18. }
  19. func (this *SegmentWriter) Write(seg ISegment) {
  20. this.Lock()
  21. defer this.Unlock()
  22. nBytes := seg.ByteSize()
  23. if uint32(this.buffer.Len()+nBytes) > this.mtu {
  24. this.FlushWithoutLock()
  25. }
  26. if this.buffer == nil {
  27. this.buffer = alloc.NewSmallBuffer().Clear()
  28. }
  29. this.buffer.Value = seg.Bytes(this.buffer.Value)
  30. }
  31. func (this *SegmentWriter) FlushWithoutLock() {
  32. this.writer.Write(this.buffer)
  33. this.buffer = nil
  34. }
  35. func (this *SegmentWriter) Flush() {
  36. this.Lock()
  37. defer this.Unlock()
  38. if this.buffer.Len() == 0 {
  39. return
  40. }
  41. this.FlushWithoutLock()
  42. }