fixed_buffer.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package http2
  5. import (
  6. "errors"
  7. )
  8. // fixedBuffer is an io.ReadWriter backed by a fixed size buffer.
  9. // It never allocates, but moves old data as new data is written.
  10. type fixedBuffer struct {
  11. buf []byte
  12. r, w int
  13. }
  14. var (
  15. errReadEmpty = errors.New("read from empty fixedBuffer")
  16. errWriteFull = errors.New("write on full fixedBuffer")
  17. )
  18. // Read copies bytes from the buffer into p.
  19. // It is an error to read when no data is available.
  20. func (b *fixedBuffer) Read(p []byte) (n int, err error) {
  21. if b.r == b.w {
  22. return 0, errReadEmpty
  23. }
  24. n = copy(p, b.buf[b.r:b.w])
  25. b.r += n
  26. if b.r == b.w {
  27. b.r = 0
  28. b.w = 0
  29. }
  30. return n, nil
  31. }
  32. // Len returns the number of bytes of the unread portion of the buffer.
  33. func (b *fixedBuffer) Len() int {
  34. return b.w - b.r
  35. }
  36. // Write copies bytes from p into the buffer.
  37. // It is an error to write more data than the buffer can hold.
  38. func (b *fixedBuffer) Write(p []byte) (n int, err error) {
  39. // Slide existing data to beginning.
  40. if b.r > 0 && len(p) > len(b.buf)-b.w {
  41. copy(b.buf, b.buf[b.r:b.w])
  42. b.w -= b.r
  43. b.r = 0
  44. }
  45. // Write new data.
  46. n = copy(b.buf[b.w:], p)
  47. b.w += n
  48. if n < len(p) {
  49. err = errWriteFull
  50. }
  51. return n, err
  52. }