chain_writer.go 723 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package io
  2. import (
  3. "io"
  4. "sync"
  5. "github.com/v2ray/v2ray-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. if this.writer == nil {
  18. return 0, io.EOF
  19. }
  20. size := len(payload)
  21. buffer := alloc.NewBufferWithSize(size).Clear()
  22. buffer.Append(payload)
  23. this.Lock()
  24. defer this.Unlock()
  25. if this.writer == nil {
  26. return 0, io.EOF
  27. }
  28. err := this.writer.Write(buffer)
  29. if err != nil {
  30. return 0, err
  31. }
  32. return size, nil
  33. }
  34. func (this *ChainWriter) Release() {
  35. this.Lock()
  36. this.writer.Release()
  37. this.writer = nil
  38. this.Unlock()
  39. }