Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/distr/uniform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,23 @@ where

/// Range that supports generating a single sample efficiently.
///
/// Any type implementing this trait can be used to specify the sampled range
/// for `Rng::random_range`.
/// See [`RngExt::random_range`] for examples; the method provides a convenient
/// interface over this type.
///
/// # Examples
///
/// ```
/// use rand::distr::uniform::SampleRange;
/// let mut rng = rand::rng();
///
/// // Range and InclusiveRange are supported for many types:
/// assert_eq!((9..10).sample_single(&mut rng), Ok(9));
/// assert_eq!(('a'..='a').sample_single(&mut rng), Ok('a'));
///
/// // RangeTo and RangeToInclusive are supported for unsigned integers:
/// assert_eq!((..1u8).sample_single(&mut rng), Ok(0));
/// assert!((..=10u32).sample_single(&mut rng).unwrap() <= 10);
/// ```
pub trait SampleRange<T> {
/// Generate a sample from the given range.
fn sample_single<R: Rng + ?Sized>(self, rng: &mut R) -> Result<T, Error>;
Expand Down
20 changes: 12 additions & 8 deletions src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ pub trait RngExt: Rng {
/// made from the given range. See also the [`Uniform`] distribution
/// type which may be faster if sampling from the same range repeatedly.
///
/// All types support `low..high_exclusive` and `low..=high` range syntax.
/// Unsigned integer types also support `..high_exclusive` and `..=high` syntax.
/// All supported types may be sampled with `low..high_exclusive`
/// ([`Range`]) and `low..=high` ([`RangeInclusive`]) syntax. Unsigned
/// integer types also support `..high_exclusive` ([`RangeTo`]) and
/// `..=high` ([`RangeToInclusive`]) syntax.
///
/// # Panics
///
Expand All @@ -144,17 +146,19 @@ pub trait RngExt: Rng {
/// let mut rng = rand::rng();
///
/// // Exclusive range
/// let n: u32 = rng.random_range(..10);
/// println!("{}", n);
/// let m: f64 = rng.random_range(-40.0..1.3e5);
/// println!("{}", m);
/// println!("{}", rng.random_range::<u32, _>(..10));
/// println!("{}", rng.random_range(-40.0..1.3e5));
///
/// // Inclusive range
/// let n: u32 = rng.random_range(..=10);
/// println!("{}", n);
/// println!("{}", rng.random_range(-10..=10));
/// println!("{}", rng.random_range('a'..='z'));
/// ```
///
/// [`Uniform`]: distr::uniform::Uniform
/// [`Range`]: std::ops::Range
/// [`RangeInclusive`]: std::ops::RangeInclusive
/// [`RangeTo`]: std::ops::RangeTo
/// [`RangeToInclusive`]: std::ops::RangeToInclusive
#[track_caller]
fn random_range<T, R>(&mut self, range: R) -> T
where
Expand Down
Loading