#[cfg(feature = "std")]
use std::time::Duration;
use Rng;
use distributions::Distribution;
use distributions::float::IntoFloat;
#[derive(Clone, Copy, Debug)]
pub struct Uniform<X: SampleUniform> {
inner: X::Sampler,
}
impl<X: SampleUniform> Uniform<X> {
pub fn new(low: X, high: X) -> Uniform<X> {
Uniform { inner: X::Sampler::new(low, high) }
}
pub fn new_inclusive(low: X, high: X) -> Uniform<X> {
Uniform { inner: X::Sampler::new_inclusive(low, high) }
}
}
impl<X: SampleUniform> Distribution<X> for Uniform<X> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> X {
self.inner.sample(rng)
}
}
pub trait SampleUniform: Sized {
type Sampler: UniformSampler<X = Self>;
}
pub trait UniformSampler: Sized {
type X;
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
{
let uniform: Self = UniformSampler::new(low, high);
uniform.sample(rng)
}
}
impl<X: SampleUniform> From<::core::ops::Range<X>> for Uniform<X> {
fn from(r: ::core::ops::Range<X>) -> Uniform<X> {
Uniform::new(r.start, r.end)
}
}
#[derive(Clone, Copy, Debug)]
pub struct UniformInt<X> {
low: X,
range: X,
zone: X,
}
macro_rules! uniform_int_impl {
($ty:ty, $signed:ty, $unsigned:ident,
$i_large:ident, $u_large:ident) => {
impl SampleUniform for $ty {
type Sampler = UniformInt<$ty>;
}
impl UniformSampler for UniformInt<$ty> {
type X = $ty;
#[inline] fn new(low: Self::X, high: Self::X) -> Self {
assert!(low < high, "Uniform::new called with `low >= high`");
UniformSampler::new_inclusive(low, high - 1)
}
#[inline] fn new_inclusive(low: Self::X, high: Self::X) -> Self {
assert!(low <= high,
"Uniform::new_inclusive called with `low > high`");
let unsigned_max = ::core::$unsigned::MAX;
let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned;
let ints_to_reject =
if range > 0 {
(unsigned_max - range + 1) % range
} else {
0
};
let zone = unsigned_max - ints_to_reject;
UniformInt {
low: low,
range: range as $ty,
zone: zone as $ty
}
}
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
let range = self.range as $unsigned as $u_large;
if range > 0 {
let zone = self.zone as $signed as $i_large as $u_large;
loop {
let v: $u_large = rng.gen();
let (hi, lo) = v.wmul(range);
if lo <= zone {
return self.low.wrapping_add(hi as $ty);
}
}
} else {
rng.gen()
}
}
fn sample_single<R: Rng + ?Sized>(low: Self::X,
high: Self::X,
rng: &mut R) -> Self::X
{
assert!(low < high,
"Uniform::sample_single called with low >= high");
let range = high.wrapping_sub(low) as $unsigned as $u_large;
let zone =
if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned {
let unsigned_max: $u_large = ::core::$u_large::MAX;
let ints_to_reject = (unsigned_max - range + 1) % range;
unsigned_max - ints_to_reject
} else {
range << range.leading_zeros()
};
loop {
let v: $u_large = rng.gen();
let (hi, lo) = v.wmul(range);
if lo <= zone {
return low.wrapping_add(hi as $ty);
}
}
}
}
}
}
uniform_int_impl! { i8, i8, u8, i32, u32 }
uniform_int_impl! { i16, i16, u16, i32, u32 }
uniform_int_impl! { i32, i32, u32, i32, u32 }
uniform_int_impl! { i64, i64, u64, i64, u64 }
#[cfg(feature = "i128_support")]
uniform_int_impl! { i128, i128, u128, u128, u128 }
uniform_int_impl! { isize, isize, usize, isize, usize }
uniform_int_impl! { u8, i8, u8, i32, u32 }
uniform_int_impl! { u16, i16, u16, i32, u32 }
uniform_int_impl! { u32, i32, u32, i32, u32 }
uniform_int_impl! { u64, i64, u64, i64, u64 }
uniform_int_impl! { usize, isize, usize, isize, usize }
#[cfg(feature = "i128_support")]
uniform_int_impl! { u128, u128, u128, i128, u128 }
trait WideningMultiply<RHS = Self> {
type Output;
fn wmul(self, x: RHS) -> Self::Output;
}
macro_rules! wmul_impl {
($ty:ty, $wide:ty, $shift:expr) => {
impl WideningMultiply for $ty {
type Output = ($ty, $ty);
#[inline(always)]
fn wmul(self, x: $ty) -> Self::Output {
let tmp = (self as $wide) * (x as $wide);
((tmp >> $shift) as $ty, tmp as $ty)
}
}
}
}
wmul_impl! { u8, u16, 8 }
wmul_impl! { u16, u32, 16 }
wmul_impl! { u32, u64, 32 }
#[cfg(feature = "i128_support")]
wmul_impl! { u64, u128, 64 }
macro_rules! wmul_impl_large {
($ty:ty, $half:expr) => {
impl WideningMultiply for $ty {
type Output = ($ty, $ty);
#[inline(always)]
fn wmul(self, b: $ty) -> Self::Output {
const LOWER_MASK: $ty = !0 >> $half;
let mut low = (self & LOWER_MASK).wrapping_mul(b & LOWER_MASK);
let mut t = low >> $half;
low &= LOWER_MASK;
t += (self >> $half).wrapping_mul(b & LOWER_MASK);
low += (t & LOWER_MASK) << $half;
let mut high = t >> $half;
t = low >> $half;
low &= LOWER_MASK;
t += (b >> $half).wrapping_mul(self & LOWER_MASK);
low += (t & LOWER_MASK) << $half;
high += t >> $half;
high += (self >> $half).wrapping_mul(b >> $half);
(high, low)
}
}
}
}
#[cfg(not(feature = "i128_support"))]
wmul_impl_large! { u64, 32 }
#[cfg(feature = "i128_support")]
wmul_impl_large! { u128, 64 }
macro_rules! wmul_impl_usize {
($ty:ty) => {
impl WideningMultiply for usize {
type Output = (usize, usize);
#[inline(always)]
fn wmul(self, x: usize) -> Self::Output {
let (high, low) = (self as $ty).wmul(x as $ty);
(high as usize, low as usize)
}
}
}
}
#[cfg(target_pointer_width = "32")]
wmul_impl_usize! { u32 }
#[cfg(target_pointer_width = "64")]
wmul_impl_usize! { u64 }
#[derive(Clone, Copy, Debug)]
pub struct UniformFloat<X> {
scale: X,
offset: X,
}
macro_rules! uniform_float_impl {
($ty:ty, $bits_to_discard:expr, $next_u:ident) => {
impl SampleUniform for $ty {
type Sampler = UniformFloat<$ty>;
}
impl UniformSampler for UniformFloat<$ty> {
type X = $ty;
fn new(low: Self::X, high: Self::X) -> Self {
assert!(low < high, "Uniform::new called with `low >= high`");
let scale = high - low;
let offset = low - scale;
UniformFloat {
scale: scale,
offset: offset,
}
}
fn new_inclusive(low: Self::X, high: Self::X) -> Self {
assert!(low <= high,
"Uniform::new_inclusive called with `low > high`");
let scale = high - low;
let offset = low - scale;
UniformFloat {
scale: scale,
offset: offset,
}
}
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
let value1_2 = (rng.$next_u() >> $bits_to_discard)
.into_float_with_exponent(0);
value1_2 * self.scale + self.offset
}
fn sample_single<R: Rng + ?Sized>(low: Self::X,
high: Self::X,
rng: &mut R) -> Self::X {
assert!(low < high,
"Uniform::sample_single called with low >= high");
let scale = high - low;
let offset = low - scale;
let value1_2 = (rng.$next_u() >> $bits_to_discard)
.into_float_with_exponent(0);
value1_2 * scale + offset
}
}
}
}
uniform_float_impl! { f32, 32 - 23, next_u32 }
uniform_float_impl! { f64, 64 - 52, next_u64 }
#[cfg(feature = "std")]
#[derive(Clone, Copy, Debug)]
pub struct UniformDuration {
offset: Duration,
mode: UniformDurationMode,
}
#[cfg(feature = "std")]
#[derive(Debug, Copy, Clone)]
enum UniformDurationMode {
Small {
nanos: Uniform<u64>,
},
Large {
size: Duration,
secs: Uniform<u64>,
}
}
#[cfg(feature = "std")]
impl SampleUniform for Duration {
type Sampler = UniformDuration;
}
#[cfg(feature = "std")]
impl UniformSampler for UniformDuration {
type X = Duration;
#[inline]
fn new(low: Duration, high: Duration) -> UniformDuration {
assert!(low < high, "Uniform::new called with `low >= high`");
UniformDuration::new_inclusive(low, high - Duration::new(0, 1))
}
#[inline]
fn new_inclusive(low: Duration, high: Duration) -> UniformDuration {
assert!(low <= high, "Uniform::new_inclusive called with `low > high`");
let size = high - low;
let nanos = size
.as_secs()
.checked_mul(1_000_000_000)
.and_then(|n| n.checked_add(size.subsec_nanos() as u64));
let mode = match nanos {
Some(nanos) => {
UniformDurationMode::Small {
nanos: Uniform::new_inclusive(0, nanos),
}
}
None => {
UniformDurationMode::Large {
size: size,
secs: Uniform::new_inclusive(0, size.as_secs()),
}
}
};
UniformDuration {
mode,
offset: low,
}
}
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration {
let d = match self.mode {
UniformDurationMode::Small { nanos } => {
let nanos = nanos.sample(rng);
Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32)
}
UniformDurationMode::Large { size, secs } => {
let nano_range = Uniform::new(0, 1_000_000_000);
loop {
let d = Duration::new(secs.sample(rng), nano_range.sample(rng));
if d <= size {
break d;
}
}
}
};
self.offset + d
}
}
#[cfg(test)]
mod tests {
use Rng;
use distributions::uniform::{Uniform, UniformSampler, UniformFloat, SampleUniform};
#[should_panic]
#[test]
fn test_uniform_bad_limits_equal_int() {
Uniform::new(10, 10);
}
#[should_panic]
#[test]
fn test_uniform_bad_limits_equal_float() {
Uniform::new(10., 10.);
}
#[test]
fn test_uniform_good_limits_equal_int() {
let mut rng = ::test::rng(804);
let dist = Uniform::new_inclusive(10, 10);
for _ in 0..20 {
assert_eq!(rng.sample(dist), 10);
}
}
#[test]
fn test_uniform_good_limits_equal_float() {
let mut rng = ::test::rng(805);
let dist = Uniform::new_inclusive(10., 10.);
for _ in 0..20 {
assert_eq!(rng.sample(dist), 10.);
}
}
#[should_panic]
#[test]
fn test_uniform_bad_limits_flipped_int() {
Uniform::new(10, 5);
}
#[should_panic]
#[test]
fn test_uniform_bad_limits_flipped_float() {
Uniform::new(10., 5.);
}
#[test]
fn test_integers() {
let mut rng = ::test::rng(251);
macro_rules! t {
($($ty:ident),*) => {{
$(
let v: &[($ty, $ty)] = &[(0, 10),
(10, 127),
(::core::$ty::MIN, ::core::$ty::MAX)];
for &(low, high) in v.iter() {
let my_uniform = Uniform::new(low, high);
for _ in 0..1000 {
let v: $ty = rng.sample(my_uniform);
assert!(low <= v && v < high);
}
let my_uniform = Uniform::new_inclusive(low, high);
for _ in 0..1000 {
let v: $ty = rng.sample(my_uniform);
assert!(low <= v && v <= high);
}
for _ in 0..1000 {
let v: $ty = rng.gen_range(low, high);
assert!(low <= v && v < high);
}
}
)*
}}
}
t!(i8, i16, i32, i64, isize,
u8, u16, u32, u64, usize);
#[cfg(feature = "i128_support")]
t!(i128, u128)
}
#[test]
fn test_floats() {
let mut rng = ::test::rng(252);
macro_rules! t {
($($ty:ty),*) => {{
$(
let v: &[($ty, $ty)] = &[(0.0, 100.0),
(-1e35, -1e25),
(1e-35, 1e-25),
(-1e35, 1e35)];
for &(low, high) in v.iter() {
let my_uniform = Uniform::new(low, high);
for _ in 0..1000 {
let v: $ty = rng.sample(my_uniform);
assert!(low <= v && v < high);
}
}
)*
}}
}
t!(f32, f64)
}
#[test]
#[cfg(feature = "std")]
fn test_durations() {
use std::time::Duration;
let mut rng = ::test::rng(253);
let v = &[(Duration::new(10, 50000), Duration::new(100, 1234)),
(Duration::new(0, 100), Duration::new(1, 50)),
(Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999))];
for &(low, high) in v.iter() {
let my_uniform = Uniform::new(low, high);
for _ in 0..1000 {
let v = rng.sample(my_uniform);
assert!(low <= v && v < high);
}
}
}
#[test]
fn test_custom_uniform() {
#[derive(Clone, Copy, PartialEq, PartialOrd)]
struct MyF32 {
x: f32,
}
#[derive(Clone, Copy, Debug)]
struct UniformMyF32 {
inner: UniformFloat<f32>,
}
impl UniformSampler for UniformMyF32 {
type X = MyF32;
fn new(low: Self::X, high: Self::X) -> Self {
UniformMyF32 {
inner: UniformFloat::<f32>::new(low.x, high.x),
}
}
fn new_inclusive(low: Self::X, high: Self::X) -> Self {
UniformSampler::new(low, high)
}
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
MyF32 { x: self.inner.sample(rng) }
}
}
impl SampleUniform for MyF32 {
type Sampler = UniformMyF32;
}
let (low, high) = (MyF32{ x: 17.0f32 }, MyF32{ x: 22.0f32 });
let uniform = Uniform::new(low, high);
let mut rng = ::test::rng(804);
for _ in 0..100 {
let x: MyF32 = rng.sample(uniform);
assert!(low <= x && x < high);
}
}
#[test]
fn test_uniform_from_std_range() {
let r = Uniform::from(2u32..7);
assert_eq!(r.inner.low, 2);
assert_eq!(r.inner.range, 5);
let r = Uniform::from(2.0f64..7.0);
assert_eq!(r.inner.offset, -3.0);
assert_eq!(r.inner.scale, 5.0);
}
}