buffered_writer.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package io
  2. import (
  3. "io"
  4. "sync"
  5. "github.com/v2ray/v2ray-core/common/alloc"
  6. )
  7. type BufferedWriter struct {
  8. sync.Mutex
  9. writer io.Writer
  10. buffer *alloc.Buffer
  11. cached bool
  12. }
  13. func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
  14. return &BufferedWriter{
  15. writer: rawWriter,
  16. buffer: alloc.NewBuffer().Clear(),
  17. cached: true,
  18. }
  19. }
  20. func (this *BufferedWriter) Write(b []byte) (int, error) {
  21. this.Lock()
  22. defer this.Unlock()
  23. if this.writer == nil {
  24. return 0, io.EOF
  25. }
  26. if !this.cached {
  27. return this.writer.Write(b)
  28. }
  29. nBytes, _ := this.buffer.Write(b)
  30. if this.buffer.IsFull() {
  31. err := this.Flush()
  32. if err != nil {
  33. return nBytes, err
  34. }
  35. }
  36. return nBytes, nil
  37. }
  38. func (this *BufferedWriter) Flush() error {
  39. this.Lock()
  40. defer this.Unlock()
  41. if this.writer == nil {
  42. return io.EOF
  43. }
  44. defer this.buffer.Clear()
  45. for !this.buffer.IsEmpty() {
  46. nBytes, err := this.writer.Write(this.buffer.Value)
  47. if err != nil {
  48. return err
  49. }
  50. this.buffer.SliceFrom(nBytes)
  51. }
  52. return nil
  53. }
  54. func (this *BufferedWriter) Cached() bool {
  55. return this.cached
  56. }
  57. func (this *BufferedWriter) SetCached(cached bool) {
  58. this.cached = cached
  59. if !cached && !this.buffer.IsEmpty() {
  60. this.Flush()
  61. }
  62. }
  63. func (this *BufferedWriter) Release() {
  64. this.Lock()
  65. defer this.Unlock()
  66. this.Flush()
  67. this.buffer.Release()
  68. this.buffer = nil
  69. this.writer = nil
  70. }