buffered_writer.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. go this.Flush()
  32. }
  33. return nBytes, nil
  34. }
  35. func (this *BufferedWriter) Flush() error {
  36. this.Lock()
  37. defer this.Unlock()
  38. if this.writer == nil {
  39. return io.EOF
  40. }
  41. defer this.buffer.Clear()
  42. for !this.buffer.IsEmpty() {
  43. nBytes, err := this.writer.Write(this.buffer.Value)
  44. if err != nil {
  45. return err
  46. }
  47. this.buffer.SliceFrom(nBytes)
  48. }
  49. return nil
  50. }
  51. func (this *BufferedWriter) Cached() bool {
  52. return this.cached
  53. }
  54. func (this *BufferedWriter) SetCached(cached bool) {
  55. this.cached = cached
  56. if !cached && !this.buffer.IsEmpty() {
  57. this.Flush()
  58. }
  59. }
  60. func (this *BufferedWriter) Release() {
  61. this.Flush()
  62. this.Lock()
  63. defer this.Unlock()
  64. this.buffer.Release()
  65. this.buffer = nil
  66. this.writer = nil
  67. }