1use enum_dispatch::enum_dispatch;
16use rand::seq::IndexedRandom;
17
18#[enum_dispatch]
19pub trait LoadBalance {
20 fn get_index<'a>(&self, candidates: &'a [usize]) -> Option<&'a usize>;
21}
22
23#[enum_dispatch(LoadBalance)]
24#[derive(Debug)]
25pub enum Loadbalancer {
26 Random,
27}
28
29impl Default for Loadbalancer {
30 fn default() -> Self {
31 Loadbalancer::from(Random)
32 }
33}
34
35#[derive(Debug)]
36pub struct Random;
37
38impl LoadBalance for Random {
39 fn get_index<'a>(&self, candidates: &'a [usize]) -> Option<&'a usize> {
40 candidates.choose(&mut rand::rng())
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use std::collections::HashSet;
47
48 use super::{LoadBalance, Random};
49
50 #[test]
51 fn test_random_lb() {
52 let candidates = vec![0, 1, 2, 3];
53 let all: HashSet<usize> = candidates.iter().copied().collect();
54
55 let random = Random;
56 for _ in 0..100 {
57 let index = random.get_index(&candidates).unwrap();
58 assert!(all.contains(index));
59 }
60 }
61}