chain_writer.go 857 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. payload = payload[alloc.BufferSize:]
  29. } else {
  30. buffer.Append(payload)
  31. size = 0
  32. }
  33. err := this.writer.Write(buffer)
  34. if err != nil {
  35. return 0, err
  36. }
  37. }
  38. return size, nil
  39. }
  40. func (this *ChainWriter) Release() {
  41. this.Lock()
  42. this.writer.Release()
  43. this.writer = nil
  44. this.Unlock()
  45. }