ferravex_play/ai/
scheduler.rs

1/// Round-robin slots over the host's stable dense agent array. Deletion/reordering
2/// is allowed between calls. Every remaining index is visited within ceil(n/k)
3/// calls while population and allowance stay fixed. No per-call allocation.
4#[derive(Clone, Copy, Debug, Default)]
5pub struct RoundRobin {
6    cursor: usize,
7}
8impl RoundRobin {
9    pub fn reset(&mut self) {
10        self.cursor = 0;
11    }
12    pub fn next(&mut self, population: usize, allowance: usize) -> Slots {
13        let count = population.min(allowance);
14        let start = if population == 0 {
15            0
16        } else {
17            self.cursor % population
18        };
19        self.cursor = if population == 0 {
20            0
21        } else {
22            if count >= population - start {
23                count - (population - start)
24            } else {
25                start + count
26            }
27        };
28        Slots {
29            start,
30            count,
31            population,
32            emitted: 0,
33        }
34    }
35}
36pub struct Slots {
37    start: usize,
38    count: usize,
39    population: usize,
40    emitted: usize,
41}
42impl Iterator for Slots {
43    type Item = usize;
44    fn next(&mut self) -> Option<usize> {
45        if self.emitted == self.count {
46            return None;
47        }
48        // Avoid overflow for arbitrary usize populations.
49        let tail = self.population - self.start;
50        let value = if self.emitted < tail {
51            self.start + self.emitted
52        } else {
53            self.emitted - tail
54        };
55        self.emitted += 1;
56        Some(value)
57    }
58    fn size_hint(&self) -> (usize, Option<usize>) {
59        let n = self.count - self.emitted;
60        (n, Some(n))
61    }
62}
63impl ExactSizeIterator for Slots {}