Skip to main content

atomr_core/routing/
round_robin.rs

1//! Round-robin router.
2
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5use crate::actor::ActorRef;
6
7pub struct RoundRobinRouter<M: Send + Clone + 'static> {
8    routees: Vec<ActorRef<M>>,
9    cursor: AtomicUsize,
10}
11
12impl<M: Send + Clone + 'static> RoundRobinRouter<M> {
13    pub fn new(routees: Vec<ActorRef<M>>) -> Self {
14        Self { routees, cursor: AtomicUsize::new(0) }
15    }
16
17    pub fn route(&self, msg: M) {
18        if self.routees.is_empty() {
19            return;
20        }
21        let idx = self.cursor.fetch_add(1, Ordering::Relaxed) % self.routees.len();
22        self.routees[idx].tell(msg);
23    }
24}