buffered_writer.go 1.1 KB

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