chain_writer.go 817 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package io
  2. import (
  3. "io"
  4. "sync"
  5. "v2ray.com/core/common/alloc"
  6. )
  7. type ChainWriter struct {
  8. sync.Mutex
  9. writer Writer
  10. }
  11. func NewChainWriter(writer Writer) *ChainWriter {
  12. return &ChainWriter{
  13. writer: writer,
  14. }
  15. }
  16. func (this *ChainWriter) Write(payload []byte) (int, error) {
  17. this.Lock()
  18. defer this.Unlock()
  19. if this.writer == nil {
  20. return 0, io.ErrClosedPipe
  21. }
  22. size := len(payload)
  23. for size > 0 {
  24. buffer := alloc.NewBuffer().Clear()
  25. if size > alloc.BufferSize {
  26. buffer.Append(payload[:alloc.BufferSize])
  27. size -= alloc.BufferSize
  28. } else {
  29. buffer.Append(payload)
  30. size = 0
  31. }
  32. err := this.writer.Write(buffer)
  33. if err != nil {
  34. return 0, err
  35. }
  36. }
  37. return size, nil
  38. }
  39. func (this *ChainWriter) Release() {
  40. this.Lock()
  41. this.writer.Release()
  42. this.writer = nil
  43. this.Unlock()
  44. }