picodata-driver 3.0.0

A native asyncronous cluster-aware Picodata client
Documentation
use std::sync::atomic::{AtomicUsize, Ordering};

use rand::RngExt;

/// Boxed strategy alias.
pub type BoxStrategy = Box<dyn Strategy>;

/// Wildcard strategy definition.
pub trait Strategy: Send + Sync + 'static {
    fn next(&self, len: usize) -> usize;
}

/// Returns next index element within it's collection len.
pub struct RoundRobin {
    counter: AtomicUsize,
}

impl RoundRobin {
    /// Creates a new round-robin strategy starting from index 0.
    #[must_use]
    pub fn new() -> Self {
        Self {
            counter: AtomicUsize::new(0),
        }
    }
}

impl Default for RoundRobin {
    fn default() -> Self {
        Self::new()
    }
}

impl Strategy for RoundRobin {
    fn next(&self, len: usize) -> usize {
        self.counter.fetch_add(1, Ordering::Relaxed) % len
    }
}

/// Returns random index element within it's collection len.
pub struct Random;

impl Strategy for Random {
    fn next(&self, len: usize) -> usize {
        rand::rng().random_range(0..len)
    }
}