buffer.go 808 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package ioutils
  2. import (
  3. "errors"
  4. "io"
  5. )
  6. var errBufferFull = errors.New("buffer is full")
  7. type fixedBuffer struct {
  8. buf []byte
  9. pos int
  10. lastRead int
  11. }
  12. func (b *fixedBuffer) Write(p []byte) (int, error) {
  13. n := copy(b.buf[b.pos:cap(b.buf)], p)
  14. b.pos += n
  15. if n < len(p) {
  16. if b.pos == cap(b.buf) {
  17. return n, errBufferFull
  18. }
  19. return n, io.ErrShortWrite
  20. }
  21. return n, nil
  22. }
  23. func (b *fixedBuffer) Read(p []byte) (int, error) {
  24. n := copy(p, b.buf[b.lastRead:b.pos])
  25. b.lastRead += n
  26. return n, nil
  27. }
  28. func (b *fixedBuffer) Len() int {
  29. return b.pos - b.lastRead
  30. }
  31. func (b *fixedBuffer) Cap() int {
  32. return cap(b.buf)
  33. }
  34. func (b *fixedBuffer) Reset() {
  35. b.pos = 0
  36. b.lastRead = 0
  37. b.buf = b.buf[:0]
  38. }
  39. func (b *fixedBuffer) String() string {
  40. return string(b.buf[b.lastRead:b.pos])
  41. }