buffer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // buffer is an io.ReadWriteCloser backed by a fixed size buffer.
  9. // It never allocates, but moves old data as new data is written.
  10. type buffer struct {
  11. buf []byte
  12. r, w int
  13. closed bool
  14. err error // err to return to reader
  15. }
  16. var (
  17. errReadEmpty = errors.New("read from empty buffer")
  18. errWriteClosed = errors.New("write on closed 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, errWriteClosed
  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. }