output.go 1.2 KB

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