buffered_writer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. defer this.buffer.Clear()
  67. for !this.buffer.IsEmpty() {
  68. nBytes, err := this.writer.Write(this.buffer.Value)
  69. if err != nil {
  70. return err
  71. }
  72. this.buffer.SliceFrom(nBytes)
  73. }
  74. return nil
  75. }
  76. func (this *BufferedWriter) Cached() bool {
  77. return this.cached
  78. }
  79. func (this *BufferedWriter) SetCached(cached bool) {
  80. this.cached = cached
  81. if !cached && !this.buffer.IsEmpty() {
  82. this.Flush()
  83. }
  84. }
  85. func (this *BufferedWriter) Release() {
  86. this.Flush()
  87. this.Lock()
  88. defer this.Unlock()
  89. this.buffer.Release()
  90. this.buffer = nil
  91. this.writer = nil
  92. }