Skip to content

Commit b1c3585

Browse files
authored
Merge pull request #436 from pitdicker/wrapping_impls
Implement `Standard` for `Wrapping<T>`
2 parents f0f1efe + 3e62ff4 commit b1c3585

File tree

3 files changed

+58
-38
lines changed

3 files changed

+58
-38
lines changed

src/distributions/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,8 @@ impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T>
389389
/// * `bool`: Generates `false` or `true`, each with probability 0.5.
390390
/// * Floating point types (`f32` and `f64`): Uniformly distributed in the
391391
/// half-open range `[0, 1)`. See notes below.
392+
/// * Wrapping integers (`Wrapping<T>`), besides the type identical to their
393+
/// normal integer variants.
392394
///
393395
/// The following aggregate types also implement the distribution `Standard` as
394396
/// long as their component types implement it:

src/distributions/other.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
//! The implementations of the `Standard` distribution for other built-in types.
1212
1313
use core::char;
14+
use core::num::Wrapping;
1415

1516
use {Rng};
1617
use distributions::{Distribution, Standard, Uniform};
@@ -161,6 +162,13 @@ impl<T> Distribution<Option<T>> for Standard where Standard: Distribution<T> {
161162
}
162163
}
163164

165+
impl<T> Distribution<Wrapping<T>> for Standard where Standard: Distribution<T> {
166+
#[inline]
167+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Wrapping<T> {
168+
Wrapping(rng.gen())
169+
}
170+
}
171+
164172

165173
#[cfg(test)]
166174
mod tests {

src/distributions/uniform.rs

Lines changed: 48 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,21 @@
5050
//!
5151
//! At a minimum, the back-end needs to store any parameters needed for sampling
5252
//! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`.
53-
//! The example below merely wraps another back-end.
53+
//! Those methods should include an assert to check the range is valid (i.e.
54+
//! `low < high`). The example below merely wraps another back-end.
5455
//!
5556
//! ```
5657
//! use rand::prelude::*;
5758
//! use rand::distributions::uniform::{Uniform, SampleUniform,
5859
//! UniformSampler, UniformFloat};
5960
//!
60-
//! #[derive(Clone, Copy, PartialEq, PartialOrd)]
6161
//! struct MyF32(f32);
6262
//!
6363
//! #[derive(Clone, Copy, Debug)]
6464
//! struct UniformMyF32 {
6565
//! inner: UniformFloat<f32>,
6666
//! }
67+
//!
6768
//! impl UniformSampler for UniformMyF32 {
6869
//! type X = MyF32;
6970
//! fn new(low: Self::X, high: Self::X) -> Self {
@@ -162,21 +163,18 @@ impl<X: SampleUniform> Uniform<X> {
162163
/// Create a new `Uniform` instance which samples uniformly from the half
163164
/// open range `[low, high)` (excluding `high`). Panics if `low >= high`.
164165
pub fn new(low: X, high: X) -> Uniform<X> {
165-
assert!(low < high, "Uniform::new called with `low >= high`");
166166
Uniform { inner: X::Sampler::new(low, high) }
167167
}
168168

169169
/// Create a new `Uniform` instance which samples uniformly from the closed
170170
/// range `[low, high]` (inclusive). Panics if `low > high`.
171171
pub fn new_inclusive(low: X, high: X) -> Uniform<X> {
172-
assert!(low <= high, "Uniform::new_inclusive called with `low > high`");
173172
Uniform { inner: X::Sampler::new_inclusive(low, high) }
174173
}
175174

176175
/// Sample a single value uniformly from `[low, high)`.
177176
/// Panics if `low >= high`.
178177
pub fn sample_single<R: Rng + ?Sized>(low: X, high: X, rng: &mut R) -> X {
179-
assert!(low < high, "Uniform::sample_single called with low >= high");
180178
X::Sampler::sample_single(low, high, rng)
181179
}
182180
}
@@ -196,7 +194,7 @@ impl<X: SampleUniform> Distribution<X> for Uniform<X> {
196194
/// [`UniformSampler`]: trait.UniformSampler.html
197195
/// [module documentation]: index.html
198196
/// [`Uniform`]: struct.Uniform.html
199-
pub trait SampleUniform: PartialOrd+Sized {
197+
pub trait SampleUniform: Sized {
200198
/// The `UniformSampler` implementation supporting type `X`.
201199
type Sampler: UniformSampler<X = Self>;
202200
}
@@ -214,7 +212,7 @@ pub trait SampleUniform: PartialOrd+Sized {
214212
/// [`sample_single`]: trait.UniformSampler.html#method.sample_single
215213
pub trait UniformSampler: Sized {
216214
/// The type sampled by this implementation.
217-
type X: PartialOrd;
215+
type X;
218216

219217
/// Construct self, with inclusive lower bound and exclusive upper bound
220218
/// `[low, high)`.
@@ -252,6 +250,17 @@ pub trait UniformSampler: Sized {
252250
}
253251
}
254252

253+
impl<X: SampleUniform> From<::core::ops::Range<X>> for Uniform<X> {
254+
fn from(r: ::core::ops::Range<X>) -> Uniform<X> {
255+
Uniform::new(r.start, r.end)
256+
}
257+
}
258+
259+
////////////////////////////////////////////////////////////////////////////////
260+
261+
// What follows are all back-ends.
262+
263+
255264
/// The back-end implementing [`UniformSampler`] for integer types.
256265
///
257266
/// Unless you are implementing [`UniformSampler`] for your own type, this type
@@ -278,17 +287,12 @@ pub trait UniformSampler: Sized {
278287
/// `ints_to_reject = (unsigned_max - range + 1) % range;`
279288
///
280289
/// The smallest integer PRNGs generate is `u32`. That is why for small integer
281-
/// sizes (`i8`/`u8` and `i16`/`u16`) there is an optimisation: don't pick the
290+
/// sizes (`i8`/`u8` and `i16`/`u16`) there is an optimization: don't pick the
282291
/// largest zone that can fit in the small type, but pick the largest zone that
283-
/// can fit in an `u32`. This improves the chance to get a random integer that
284-
/// fits in the zone to 998 in 1000 in the worst case.
285-
///
286-
/// There is a problem however: we can't store the acceptable `zone` of such a
287-
/// larger type in `UniformInt`, which only holds values with the size of the
288-
/// type. `ints_to_reject` is always less than half the size of the small
289-
/// integer. For an `u8` it only ever uses 7 bits. This means that all but the
290-
/// last 7 bits of `zone` are always 1's (or 15 in the case of `u16`). So
291-
/// nothing is lost by trucating `zone`.
292+
/// can fit in an `u32`. `ints_to_reject` is always less than half the size of
293+
/// the small integer. This means the first bit of `zone` is always 1, and so
294+
/// are all the other preceding bits of a larger integer. The easiest way to
295+
/// grow the `zone` for the larger type is to simply sign extend it.
292296
///
293297
/// An alternative to using a modulus is widening multiply: After a widening
294298
/// multiply by `range`, the result is in the high word. Then comparing the low
@@ -321,17 +325,18 @@ macro_rules! uniform_int_impl {
321325
#[inline] // if the range is constant, this helps LLVM to do the
322326
// calculations at compile-time.
323327
fn new(low: Self::X, high: Self::X) -> Self {
328+
assert!(low < high, "Uniform::new called with `low >= high`");
324329
UniformSampler::new_inclusive(low, high - 1)
325330
}
326331

327332
#[inline] // if the range is constant, this helps LLVM to do the
328333
// calculations at compile-time.
329334
fn new_inclusive(low: Self::X, high: Self::X) -> Self {
330-
let unsigned_max: $u_large = ::core::$u_large::MAX;
335+
assert!(low <= high,
336+
"Uniform::new_inclusive called with `low > high`");
337+
let unsigned_max = ::core::$unsigned::MAX;
331338

332-
let range = (high as $u_large)
333-
.wrapping_sub(low as $u_large)
334-
.wrapping_add(1);
339+
let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned;
335340
let ints_to_reject =
336341
if range > 0 {
337342
(unsigned_max - range + 1) % range
@@ -351,9 +356,9 @@ macro_rules! uniform_int_impl {
351356
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
352357
let range = self.range as $unsigned as $u_large;
353358
if range > 0 {
354-
// Some casting to recover the trucated bits of `zone`:
355-
// First bit-cast to a signed int. Next sign-extend to the
356-
// larger type. Then bit-cast to unsigned.
359+
// Grow `zone` to fit a type of at least 32 bits, by
360+
// sign-extending it (the first bit is always 1, so are all
361+
// the preceding bits of the larger type).
357362
// For types that already have the right size, all the
358363
// casting is a no-op.
359364
let zone = self.zone as $signed as $i_large as $u_large;
@@ -374,8 +379,9 @@ macro_rules! uniform_int_impl {
374379
high: Self::X,
375380
rng: &mut R) -> Self::X
376381
{
377-
let range = (high as $u_large)
378-
.wrapping_sub(low as $u_large);
382+
assert!(low < high,
383+
"Uniform::sample_single called with low >= high");
384+
let range = high.wrapping_sub(low) as $unsigned as $u_large;
379385
let zone =
380386
if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned {
381387
// Using a modulus is faster than the approximation for
@@ -401,12 +407,6 @@ macro_rules! uniform_int_impl {
401407
}
402408
}
403409

404-
impl<X: SampleUniform> From<::core::ops::Range<X>> for Uniform<X> {
405-
fn from(r: ::core::ops::Range<X>) -> Uniform<X> {
406-
Uniform::new(r.start, r.end)
407-
}
408-
}
409-
410410
uniform_int_impl! { i8, i8, u8, i32, u32 }
411411
uniform_int_impl! { i16, i16, u16, i32, u32 }
412412
uniform_int_impl! { i32, i32, u32, i32, u32 }
@@ -442,7 +442,6 @@ macro_rules! wmul_impl {
442442
}
443443
}
444444
}
445-
446445
wmul_impl! { u8, u16, 8 }
447446
wmul_impl! { u16, u32, 16 }
448447
wmul_impl! { u32, u64, 32 }
@@ -481,13 +480,11 @@ macro_rules! wmul_impl_large {
481480
}
482481
}
483482
}
484-
485483
#[cfg(not(feature = "i128_support"))]
486484
wmul_impl_large! { u64, 32 }
487485
#[cfg(feature = "i128_support")]
488486
wmul_impl_large! { u128, 64 }
489487

490-
491488
macro_rules! wmul_impl_usize {
492489
($ty:ty) => {
493490
impl WideningMultiply for usize {
@@ -501,7 +498,6 @@ macro_rules! wmul_impl_usize {
501498
}
502499
}
503500
}
504-
505501
#[cfg(target_pointer_width = "32")]
506502
wmul_impl_usize! { u32 }
507503
#[cfg(target_pointer_width = "64")]
@@ -550,6 +546,7 @@ macro_rules! uniform_float_impl {
550546
type X = $ty;
551547

552548
fn new(low: Self::X, high: Self::X) -> Self {
549+
assert!(low < high, "Uniform::new called with `low >= high`");
553550
let scale = high - low;
554551
let offset = low - scale;
555552
UniformFloat {
@@ -559,7 +556,14 @@ macro_rules! uniform_float_impl {
559556
}
560557

561558
fn new_inclusive(low: Self::X, high: Self::X) -> Self {
562-
UniformSampler::new(low, high)
559+
assert!(low <= high,
560+
"Uniform::new_inclusive called with `low > high`");
561+
let scale = high - low;
562+
let offset = low - scale;
563+
UniformFloat {
564+
scale: scale,
565+
offset: offset,
566+
}
563567
}
564568

565569
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
@@ -577,6 +581,8 @@ macro_rules! uniform_float_impl {
577581
fn sample_single<R: Rng + ?Sized>(low: Self::X,
578582
high: Self::X,
579583
rng: &mut R) -> Self::X {
584+
assert!(low < high,
585+
"Uniform::sample_single called with low >= high");
580586
let scale = high - low;
581587
let offset = low - scale;
582588
// Generate a value in the range [1, 2)
@@ -593,7 +599,9 @@ macro_rules! uniform_float_impl {
593599
uniform_float_impl! { f32, 32 - 23, next_u32 }
594600
uniform_float_impl! { f64, 64 - 52, next_u64 }
595601

596-
/// Implementation of [`UniformSampler`] for `Duration`.
602+
603+
604+
/// The back-end implementing [`UniformSampler`] for `Duration`.
597605
///
598606
/// Unless you are implementing [`UniformSampler`] for your own types, this type
599607
/// should not be used directly, use [`Uniform`] instead.
@@ -630,11 +638,13 @@ impl UniformSampler for UniformDuration {
630638

631639
#[inline]
632640
fn new(low: Duration, high: Duration) -> UniformDuration {
641+
assert!(low < high, "Uniform::new called with `low >= high`");
633642
UniformDuration::new_inclusive(low, high - Duration::new(0, 1))
634643
}
635644

636645
#[inline]
637646
fn new_inclusive(low: Duration, high: Duration) -> UniformDuration {
647+
assert!(low <= high, "Uniform::new_inclusive called with `low > high`");
638648
let size = high - low;
639649
let nanos = size
640650
.as_secs()

0 commit comments

Comments
 (0)