Skip to main content

des_sim/modeling/sampler/instance/
constant.rs

1//! The `constant` module provides the `ConstantSampler`, a simple `DurationSampler`
2//! that always returns a fixed, predefined duration.
3//!
4//! This is useful for modeling deterministic delays or intervals in a simulation,
5//! where no randomness or variability is required.
6
7use crate::modeling::sampler::{DurationSampler, PendingDuration};
8use crate::primitive::time::SimTime;
9use rand::Rng;
10
11/// A sampler that consistently returns a constant value.
12#[derive(Debug, Clone)]
13pub struct ConstantSampler {
14    value: f64,
15}
16
17impl DurationSampler for ConstantSampler {
18    fn sample(&mut self, _rng: &mut dyn Rng, _current_tick: SimTime) -> PendingDuration {
19        // Returns the fixed constant value regardless of RNG or simulation time.
20        PendingDuration::new(self.value)
21    }
22}
23
24impl ConstantSampler {
25    /// Creates a new `ConstantSampler` with the given `value`.
26    pub fn new(value: f64) -> Self {
27        Self { value }
28    }
29
30    /// Returns the constant value held by this sampler.
31    pub fn value(&self) -> f64 {
32        self.value
33    }
34
35    /// A convenience method to retrieve the `PendingDuration` without needing an RNG or `SimTime`.
36    pub fn constant_sample(&self) -> PendingDuration {
37        PendingDuration::new(self.value)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use rand::SeedableRng;
45    use rand::rngs::SmallRng;
46
47    #[test]
48    fn test_constant_sampler() {
49        let mut rng = SmallRng::seed_from_u64(2);
50        let mut sampler = ConstantSampler::new(100.0);
51
52        let sample = sampler.sample(&mut rng, SimTime::from_ticks(0));
53        assert_eq!(sample.raw_value(), 100.0);
54    }
55}