hopr_transport_session/balancer/
simple.rs1use crate::balancer::{BalancerControllerBounds, SurbBalancerController};
2
3#[derive(Clone, Debug, Default)]
10pub struct SimpleBalancerController {
11 bounds: BalancerControllerBounds,
12}
13
14impl SurbBalancerController for SimpleBalancerController {
15 fn bounds(&self) -> BalancerControllerBounds {
16 self.bounds
17 }
18
19 fn set_target_and_limit(&mut self, bounds: BalancerControllerBounds) {
20 self.bounds = bounds;
21 }
22
23 fn next_control_output(&mut self, current_buffer_level: u64) -> u64 {
24 let ratio = current_buffer_level as f64 / self.bounds.target() as f64;
25 (self.bounds.output_limit() as f64 * ratio.clamp(0.0, 1.0)).floor() as u64
26 }
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn test_simple_balancer() {
35 let mut controller = SimpleBalancerController::default();
36 controller.set_target_and_limit(BalancerControllerBounds::new(100, 100));
37 assert_eq!(100, controller.bounds.target());
38
39 let outputs: Vec<_> = [10, 100, 101]
40 .iter()
41 .map(|&level| controller.next_control_output(level))
42 .collect();
43 assert_eq!(outputs, [10, 100, 100]);
44 assert_eq!(100, controller.bounds.target());
45 }
46}