buffer.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. errWriteClosed = errors.New("write on closed buffer")
  20. errWriteFull = errors.New("write on full buffer")
  21. )
  22. // Read copies bytes from the buffer into p.
  23. // It is an error to read when no data is available.
  24. func (b *buffer) Read(p []byte) (n int, err error) {
  25. n = copy(p, b.buf[b.r:b.w])
  26. b.r += n
  27. if b.closed && b.r == b.w {
  28. err = b.err
  29. } else if b.r == b.w && n == 0 {
  30. err = errReadEmpty
  31. }
  32. return n, err
  33. }
  34. // Len returns the number of bytes of the unread portion of the buffer.
  35. func (b *buffer) Len() int {
  36. return b.w - b.r
  37. }
  38. // Write copies bytes from p into the buffer.
  39. // It is an error to write more data than the buffer can hold.
  40. func (b *buffer) Write(p []byte) (n int, err error) {
  41. if b.closed {
  42. return 0, errWriteClosed
  43. }
  44. // Slide existing data to beginning.
  45. if b.r > 0 && len(p) > len(b.buf)-b.w {
  46. copy(b.buf, b.buf[b.r:b.w])
  47. b.w -= b.r
  48. b.r = 0
  49. }
  50. // Write new data.
  51. n = copy(b.buf[b.w:], p)
  52. b.w += n
  53. if n < len(p) {
  54. err = errWriteFull
  55. }
  56. return n, err
  57. }
  58. // Close marks the buffer as closed. Future calls to Write will
  59. // return an error. Future calls to Read, once the buffer is
  60. // empty, will return err.
  61. func (b *buffer) Close(err error) {
  62. if !b.closed {
  63. b.closed = true
  64. b.err = err
  65. }
  66. }