flow.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. // Flow control
  6. package http2
  7. // flow is the flow control window's size.
  8. type flow struct {
  9. // n is the number of DATA bytes we're allowed to send.
  10. // A flow is kept both on a conn and a per-stream.
  11. n int32
  12. // conn points to the shared connection-level flow that is
  13. // shared by all streams on that conn. It is nil for the flow
  14. // that's on the conn directly.
  15. conn *flow
  16. }
  17. func (f *flow) setConnFlow(cf *flow) { f.conn = cf }
  18. func (f *flow) available() int32 {
  19. n := f.n
  20. if f.conn != nil && f.conn.n < n {
  21. n = f.conn.n
  22. }
  23. return n
  24. }
  25. func (f *flow) take(n int32) {
  26. if n > f.available() {
  27. panic("internal error: took too much")
  28. }
  29. f.n -= n
  30. if f.conn != nil {
  31. f.conn.n -= n
  32. }
  33. }
  34. // add adds n bytes (positive or negative) to the flow control window.
  35. // It returns false if the sum would exceed 2^31-1.
  36. func (f *flow) add(n int32) bool {
  37. remain := (1<<31 - 1) - f.n
  38. if n > remain {
  39. return false
  40. }
  41. f.n += n
  42. return true
  43. }