buffered_writer.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package io
  2. import (
  3. "io"
  4. "sync"
  5. "fmt"
  6. "v2ray.com/core/common/alloc"
  7. )
  8. type BufferedWriter struct {
  9. sync.Mutex
  10. writer io.Writer
  11. buffer *alloc.Buffer
  12. cached bool
  13. }
  14. func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
  15. return &BufferedWriter{
  16. writer: rawWriter,
  17. buffer: alloc.NewBuffer().Clear(),
  18. cached: true,
  19. }
  20. }
  21. func (this *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
  22. this.Lock()
  23. defer this.Unlock()
  24. if this.writer == nil {
  25. return 0, io.ErrClosedPipe
  26. }
  27. totalBytes := int64(0)
  28. for {
  29. nBytes, err := this.buffer.FillFrom(reader)
  30. totalBytes += int64(nBytes)
  31. if err != nil {
  32. if err == io.EOF {
  33. return totalBytes, nil
  34. }
  35. return totalBytes, err
  36. }
  37. this.FlushWithoutLock()
  38. }
  39. }
  40. func (this *BufferedWriter) Write(b []byte) (int, error) {
  41. this.Lock()
  42. defer this.Unlock()
  43. if this.writer == nil {
  44. return 0, io.ErrClosedPipe
  45. }
  46. fmt.Printf("BufferedWriter writing: %v\n", b)
  47. if !this.cached {
  48. return this.writer.Write(b)
  49. }
  50. nBytes, _ := this.buffer.Write(b)
  51. if this.buffer.IsFull() {
  52. this.FlushWithoutLock()
  53. }
  54. fmt.Printf("BufferedWriter content: %v\n", this.buffer.Value)
  55. return nBytes, nil
  56. }
  57. func (this *BufferedWriter) Flush() error {
  58. this.Lock()
  59. defer this.Unlock()
  60. if this.writer == nil {
  61. return io.ErrClosedPipe
  62. }
  63. return this.FlushWithoutLock()
  64. }
  65. func (this *BufferedWriter) FlushWithoutLock() error {
  66. fmt.Println("BufferedWriter flushing")
  67. defer this.buffer.Clear()
  68. for !this.buffer.IsEmpty() {
  69. nBytes, err := this.writer.Write(this.buffer.Value)
  70. fmt.Printf("BufferedWriting flushed %d bytes.\n", nBytes)
  71. if err != nil {
  72. return err
  73. }
  74. this.buffer.SliceFrom(nBytes)
  75. }
  76. return nil
  77. }
  78. func (this *BufferedWriter) Cached() bool {
  79. return this.cached
  80. }
  81. func (this *BufferedWriter) SetCached(cached bool) {
  82. this.cached = cached
  83. if !cached && !this.buffer.IsEmpty() {
  84. this.Flush()
  85. }
  86. }
  87. func (this *BufferedWriter) Release() {
  88. this.Flush()
  89. this.Lock()
  90. defer this.Unlock()
  91. this.buffer.Release()
  92. this.buffer = nil
  93. this.writer = nil
  94. }