buffered_writer.go 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package buffered_writer
  2. import (
  3. "bytes"
  4. "io"
  5. )
  6. var _ = io.WriteCloser(&BufferedWriteCloser{})
  7. type BufferedWriteCloser struct {
  8. buffer bytes.Buffer
  9. bufferLimit int
  10. position int64
  11. nextFlushOffset int64
  12. FlushFunc func([]byte, int64) error
  13. CloseFunc func() error
  14. }
  15. func NewBufferedWriteCloser(bufferLimit int) *BufferedWriteCloser {
  16. return &BufferedWriteCloser{
  17. bufferLimit: bufferLimit,
  18. }
  19. }
  20. func (b *BufferedWriteCloser) Write(p []byte) (n int, err error) {
  21. if b.buffer.Len()+len(p) >= b.bufferLimit {
  22. if err := b.FlushFunc(b.buffer.Bytes(), b.nextFlushOffset); err != nil {
  23. return 0, err
  24. }
  25. b.nextFlushOffset += int64(b.buffer.Len())
  26. b.buffer.Reset()
  27. }
  28. return b.buffer.Write(p)
  29. }
  30. func (b *BufferedWriteCloser) Close() error {
  31. if b.buffer.Len() > 0 {
  32. if err := b.FlushFunc(b.buffer.Bytes(), b.nextFlushOffset); err != nil {
  33. return err
  34. }
  35. }
  36. if b.CloseFunc != nil {
  37. if err := b.CloseFunc(); err != nil {
  38. return err
  39. }
  40. }
  41. return nil
  42. }