limq/limitors/
optlenlim.rs

1use std::{cmp, collections::VecDeque, marker::PhantomData};
2
3use super::{CheckErr, Controller};
4
5/// [`LimQ`](crate::LimQ) controller that imposes an _optional_ queue length
6/// limit.
7pub struct OptLenLim<T> {
8  q_len: usize,
9  max_len: Option<usize>,
10  len_hwm: usize,
11  _phantom: PhantomData<T>
12}
13
14impl<T> OptLenLim<T> {
15  /// Create a new object for limiting queue to a configured length.
16  ///
17  /// # Panics
18  /// `max_len` must not be `0`.
19  #[must_use]
20  pub fn new(max_len: Option<usize>) -> Self {
21    assert!(!matches!(max_len, Some(0)), "zero-length limit");
22    Self {
23      q_len: 0,
24      max_len,
25      len_hwm: 0,
26      _phantom: PhantomData
27    }
28  }
29
30  /// Return the current maximum length setting.
31  #[must_use]
32  pub const fn get_max_len(&self) -> Option<usize> {
33    self.max_len
34  }
35
36  /// Update the maximum queue length.
37  ///
38  /// # Panics
39  /// `max_len` must not be `0`.
40  pub fn set_max_len(&mut self, max_len: Option<usize>) {
41    assert!(!matches!(max_len, Some(0)), "zero-length limit");
42    self.max_len = max_len;
43  }
44
45  /// Retreive the current queue length high-water mark.
46  #[must_use]
47  pub const fn get_len_hwm(&self) -> usize {
48    self.len_hwm
49  }
50
51  /// Set the queue length high-water mark to the current queue length.
52  pub const fn reset_len_hwm(&mut self) {
53    self.len_hwm = self.q_len;
54  }
55
56  /// Set the queue length high-water mark to `0`.
57  pub const fn clear_len_hwm(&mut self) {
58    self.len_hwm = 0;
59  }
60}
61
62impl<T> Controller for OptLenLim<T> {
63  type Item = T;
64
65  fn size_hint(&self) -> Option<usize> {
66    self.max_len
67  }
68
69  fn is_full(&self, q: &VecDeque<T>) -> bool {
70    self.max_len.is_some_and(|max_len| q.len() >= max_len)
71  }
72
73  fn is_overflow(&self, q: &VecDeque<T>) -> bool {
74    self.max_len.is_some_and(|max_len| q.len() > max_len)
75  }
76
77  fn check(
78    &self,
79    q: &VecDeque<Self::Item>,
80    _n: &Self::Item
81  ) -> Result<(), CheckErr> {
82    self
83      .max_len
84      .is_some_and(|max_len| q.len() < max_len)
85      .then_some(())
86      .ok_or(CheckErr::WontFit)
87  }
88
89  fn reg(&mut self, _q: &VecDeque<Self::Item>, _n: &Self::Item) {
90    self.q_len += 1;
91    self.len_hwm = cmp::max(self.len_hwm, self.q_len);
92  }
93
94  fn dereg(&mut self, _n: &Self::Item) {
95    self.q_len -= 1;
96  }
97}
98
99// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :