flow.go 1.1 KB

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