Trait rand::distributions::range::RangeImpl [] [src]

pub trait RangeImpl: Sized {
    type X: PartialOrd;
    fn new(low: Self::X, high: Self::X) -> Self;
fn new_inclusive(low: Self::X, high: Self::X) -> Self;
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X; fn sample_single<R: Rng + ?Sized>(
        low: Self::X,
        high: Self::X,
        rng: &mut R
    ) -> Self::X { ... } }

Helper trait handling actual range sampling.

If you want to implement Range sampling for your own type, then implement both this trait and SampleRange:

use rand::{Rng, thread_rng};
use rand::distributions::Distribution;
use rand::distributions::range::{Range, SampleRange, RangeImpl, RangeFloat};

#[derive(Clone, Copy, PartialEq, PartialOrd)]
struct MyF32(f32);

#[derive(Clone, Copy, Debug)]
struct RangeMyF32 {
    inner: RangeFloat<f32>,
}
impl RangeImpl for RangeMyF32 {
    type X = MyF32;
    fn new(low: Self::X, high: Self::X) -> Self {
        RangeMyF32 {
            inner: RangeFloat::<f32>::new(low.0, high.0),
        }
    }
    fn new_inclusive(low: Self::X, high: Self::X) -> Self {
        RangeImpl::new(low, high)
    }
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        MyF32(self.inner.sample(rng))
    }
}

impl SampleRange for MyF32 {
    type T = RangeMyF32;
}

let (low, high) = (MyF32(17.0f32), MyF32(22.0f32));
let range = Range::new(low, high);
let x = range.sample(&mut thread_rng());

Associated Types

The type sampled by this implementation.

Required Methods

Construct self, with inclusive lower bound and exclusive upper bound [low, high).

Usually users should not call this directly but instead use Range::new, which asserts that low < high before calling this.

Construct self, with inclusive bounds [low, high].

Usually users should not call this directly but instead use Range::new_inclusive, which asserts that low < high before calling this.

Sample a value.

Provided Methods

Sample a single value uniformly from a range with inclusive lower bound and exclusive upper bound [low, high).

Usually users should not call this directly but instead use Range::sample_single, which asserts that low < high before calling this.

Via this method range implementations can provide a method optimized for sampling only a limited number of values from range. The default implementation just sets up a range with RangeImpl::new and samples from that.

Implementors