buffered_writer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. nBytes, err := this.writer.Write(this.buffer.Value)
  33. this.buffer.SliceFrom(nBytes)
  34. if !this.buffer.IsEmpty() {
  35. nBytes, err = this.writer.Write(this.buffer.Value)
  36. this.buffer.SliceFrom(nBytes)
  37. }
  38. if this.buffer.IsEmpty() {
  39. this.buffer.Clear()
  40. }
  41. return err
  42. }
  43. func (this *BufferedWriter) Cached() bool {
  44. return this.cached
  45. }
  46. func (this *BufferedWriter) SetCached(cached bool) {
  47. this.cached = cached
  48. if !cached && !this.buffer.IsEmpty() {
  49. this.flush()
  50. }
  51. }
  52. func (this *BufferedWriter) Release() {
  53. this.buffer.Release()
  54. }