Skip to main content

picodata_driver/
strategy.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2
3use rand::RngExt;
4
5/// Boxed strategy alias.
6pub type BoxStrategy = Box<dyn Strategy>;
7
8/// Wildcard strategy definition.
9pub trait Strategy: Send + Sync + 'static {
10    fn next(&self, len: usize) -> usize;
11}
12
13/// Returns next index element within it's collection len.
14pub struct RoundRobin {
15    counter: AtomicUsize,
16}
17
18impl RoundRobin {
19    /// Creates a new round-robin strategy starting from index 0.
20    #[must_use]
21    pub fn new() -> Self {
22        Self {
23            counter: AtomicUsize::new(0),
24        }
25    }
26}
27
28impl Default for RoundRobin {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Strategy for RoundRobin {
35    fn next(&self, len: usize) -> usize {
36        self.counter.fetch_add(1, Ordering::Relaxed) % len
37    }
38}
39
40/// Returns random index element within it's collection len.
41pub struct Random;
42
43impl Strategy for Random {
44    fn next(&self, len: usize) -> usize {
45        rand::rng().random_range(0..len)
46    }
47}