buffer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2014 The Go Authors.
  2. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  3. // Licensed under the same terms as Go itself:
  4. // https://code.google.com/p/go/source/browse/LICENSE
  5. package http2
  6. import (
  7. "errors"
  8. )
  9. // buffer is an io.ReadWriteCloser backed by a fixed size buffer.
  10. // It never allocates, but moves old data as new data is written.
  11. type buffer struct {
  12. buf []byte
  13. r, w int
  14. closed bool
  15. err error // err to return to reader
  16. }
  17. var (
  18. errReadEmpty = errors.New("read from empty buffer")
  19. errWriteFull = errors.New("write on full buffer")
  20. )
  21. // Read copies bytes from the buffer into p.
  22. // It is an error to read when no data is available.
  23. func (b *buffer) Read(p []byte) (n int, err error) {
  24. n = copy(p, b.buf[b.r:b.w])
  25. b.r += n
  26. if b.closed && b.r == b.w {
  27. err = b.err
  28. } else if b.r == b.w && n == 0 {
  29. err = errReadEmpty
  30. }
  31. return n, err
  32. }
  33. // Len returns the number of bytes of the unread portion of the buffer.
  34. func (b *buffer) Len() int {
  35. return b.w - b.r
  36. }
  37. // Write copies bytes from p into the buffer.
  38. // It is an error to write more data than the buffer can hold.
  39. func (b *buffer) Write(p []byte) (n int, err error) {
  40. if b.closed {
  41. return 0, errors.New("closed")
  42. }
  43. // Slide existing data to beginning.
  44. if b.r > 0 && len(p) > len(b.buf)-b.w {
  45. copy(b.buf, b.buf[b.r:b.w])
  46. b.w -= b.r
  47. b.r = 0
  48. }
  49. // Write new data.
  50. n = copy(b.buf[b.w:], p)
  51. b.w += n
  52. if n < len(p) {
  53. err = errWriteFull
  54. }
  55. return n, err
  56. }
  57. // Close marks the buffer as closed. Future calls to Write will
  58. // return an error. Future calls to Read, once the buffer is
  59. // empty, will return err.
  60. func (b *buffer) Close(err error) {
  61. if !b.closed {
  62. b.closed = true
  63. b.err = err
  64. }
  65. }