pipe.go 867 B

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