writer.go 904 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package io
  2. import (
  3. "io"
  4. "github.com/v2ray/v2ray-core/common"
  5. "github.com/v2ray/v2ray-core/common/alloc"
  6. )
  7. // Writer extends io.Writer with alloc.Buffer.
  8. type Writer interface {
  9. common.Releasable
  10. // Write writes an alloc.Buffer into underlying writer.
  11. Write(*alloc.Buffer) error
  12. }
  13. // AdaptiveWriter is a Writer that writes alloc.Buffer into underlying writer.
  14. type AdaptiveWriter struct {
  15. writer io.Writer
  16. }
  17. // NewAdaptiveWriter creates a new AdaptiveWriter.
  18. func NewAdaptiveWriter(writer io.Writer) *AdaptiveWriter {
  19. return &AdaptiveWriter{
  20. writer: writer,
  21. }
  22. }
  23. // Write implements Writer.Write().
  24. func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error {
  25. nBytes, err := this.writer.Write(buffer.Value)
  26. if nBytes < buffer.Len() {
  27. _, err = this.writer.Write(buffer.Value[nBytes:])
  28. }
  29. buffer.Release()
  30. return err
  31. }
  32. func (this *AdaptiveWriter) Release() {
  33. this.writer = nil
  34. }