Skip to main content

apigate_core/balancing/
round_robin.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2
3use super::{BalanceCtx, Balancer};
4
5#[derive(Debug, Default)]
6pub struct RoundRobin {
7    next: AtomicUsize,
8}
9
10impl RoundRobin {
11    pub fn new() -> Self {
12        Self {
13            next: AtomicUsize::new(0),
14        }
15    }
16}
17
18impl Balancer for RoundRobin {
19    fn pick<'a>(&self, ctx: &'a BalanceCtx<'a>) -> Option<usize> {
20        let len = ctx.candidate_len();
21        if len == 0 {
22            return None;
23        }
24
25        let pos = self.next.fetch_add(1, Ordering::Relaxed) % len;
26        ctx.candidate_index(pos)
27    }
28}