tower_web/util/buf_stream/size_hint.rs
1//! `SizeHint` type and builder
2
3/// A `BufStream` size hint
4///
5/// The default implementation returns:
6///
7/// * 0 for `available`
8/// * 0 for `lower`
9/// * `None` for `upper`.
10#[derive(Debug, Default, Clone)]
11pub struct SizeHint {
12 available: usize,
13 lower: usize,
14 upper: Option<usize>,
15}
16
17/// Build a `SizeHint`
18#[derive(Debug)]
19pub struct Builder {
20 hint: SizeHint,
21}
22
23impl Builder {
24 /// Create a new `Builder` configured with default values.
25 pub fn new() -> Builder {
26 Builder {
27 hint: SizeHint {
28 available: 0,
29 lower: 0,
30 upper: None,
31 },
32 }
33 }
34
35 /// Sets the `available` hint value.
36 pub fn available(&mut self, val: usize) -> &mut Self {
37 self.hint.available = val;
38
39 if self.hint.lower < val {
40 self.hint.lower = val;
41
42 match self.hint.upper {
43 Some(ref mut upper) if *upper < val => {
44 *upper = val;
45 }
46 _ => {}
47 }
48 }
49
50 self
51 }
52
53 /// Sets the `lower` hint value.
54 ///
55 /// # Panics
56 ///
57 /// This function panics if `val` is smaller than `available`.
58 pub fn lower(&mut self, val: usize) -> &mut Self {
59 assert!(val >= self.hint.available);
60
61 self.hint.lower = val;
62 self
63 }
64
65 /// Set the `upper` hint value.
66 ///
67 /// # Panics
68 ///
69 /// This function panics if `val` is smaller than `lower`.
70 pub fn upper(&mut self, val: usize) -> &mut Self {
71 // There is no need to check `available` as that is guaranteed to be
72 // less than or equal to `lower`.
73 assert!(val >= self.hint.lower, "`val` is smaller than `lower`");
74
75 self.hint.upper = Some(val);
76 self
77 }
78
79 /// Build the `SizeHint`
80 pub fn build(&self) -> SizeHint {
81 self.hint.clone()
82 }
83}
84
85impl SizeHint {
86 /// Returns the **lower bound** of the amount of data that can be read from
87 /// the `BufStream` without `NotReady` being returned.
88 ///
89 /// It is possible that more data is currently available.
90 pub fn available(&self) -> usize {
91 self.available
92 }
93
94 /// Returns the lower bound of data that the `BufStream` will yield before
95 /// completing.
96 pub fn lower(&self) -> usize {
97 self.lower
98 }
99
100 /// Returns the upper bound of data the `BufStream` will yield before
101 /// completing, or `None` if the value is unknown.
102 pub fn upper(&self) -> Option<usize> {
103 self.upper
104 }
105}