deep_causality_rand/traits/
sample_range.rs

1/*
2 * SPDX-License-Identifier: MIT
3 * Copyright (c) "2025" . The DeepCausality Authors and Contributors. All Rights Reserved.
4 */
5use crate::{Rng, RngError};
6use std::ops::Range;
7
8pub trait SampleRange<T> {
9    fn sample_single<R: Rng + ?Sized>(self, rng: &mut R) -> Result<T, RngError>;
10
11    fn is_empty(&self) -> bool;
12}
13
14impl SampleRange<f32> for Range<f32> {
15    fn sample_single<R: Rng + ?Sized>(self, rng: &mut R) -> Result<f32, RngError> {
16        if self.is_empty() {
17            return Err(RngError::InvalidRange(
18                "Invalid range: low must be less than high".to_string(),
19            ));
20        }
21        let random_val: f32 = rng.random(); // Generates a random f32 in [0.0, 1.0)
22        Ok(self.start + (self.end - self.start) * random_val)
23    }
24
25    fn is_empty(&self) -> bool {
26        self.start >= self.end
27    }
28}
29
30impl SampleRange<f64> for Range<f64> {
31    fn sample_single<R: Rng + ?Sized>(self, rng: &mut R) -> Result<f64, RngError> {
32        if self.is_empty() {
33            return Err(RngError::InvalidRange(
34                "Invalid range: low must be less than high".to_string(),
35            ));
36        }
37        let random_val: f64 = rng.random(); // Generates a random f64 in [0.0, 1.0)
38        Ok(self.start + (self.end - self.start) * random_val)
39    }
40
41    fn is_empty(&self) -> bool {
42        self.start >= self.end
43    }
44}