pipe.go 906 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. "sync"
  8. )
  9. type pipe struct {
  10. b buffer
  11. c sync.Cond
  12. m sync.Mutex
  13. }
  14. // Read waits until data is available and copies bytes
  15. // from the buffer into p.
  16. func (r *pipe) Read(p []byte) (n int, err error) {
  17. r.c.L.Lock()
  18. defer r.c.L.Unlock()
  19. for r.b.Len() == 0 && !r.b.closed {
  20. r.c.Wait()
  21. }
  22. return r.b.Read(p)
  23. }
  24. // Write copies bytes from p into the buffer and wakes a reader.
  25. // It is an error to write more data than the buffer can hold.
  26. func (w *pipe) Write(p []byte) (n int, err error) {
  27. w.c.L.Lock()
  28. defer w.c.L.Unlock()
  29. defer w.c.Signal()
  30. return w.b.Write(p)
  31. }
  32. func (c *pipe) Close(err error) {
  33. c.c.L.Lock()
  34. defer c.c.L.Unlock()
  35. defer c.c.Signal()
  36. c.b.Close(err)
  37. }