Skip to content

Commit 4eb0831

Browse files
committed
Also add sample_iter to Rng
1 parent efb8a26 commit 4eb0831

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/lib.rs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,39 @@ pub trait Rng: RngCore {
380380
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
381381
distr.sample(self)
382382
}
383+
384+
/// Create an iterator that generates values using the given distribution.
385+
///
386+
/// # Example
387+
///
388+
/// ```rust
389+
/// use rand::{thread_rng, Rng};
390+
/// use rand::distributions::{Alphanumeric, Range, Uniform};
391+
///
392+
/// let mut rng = thread_rng();
393+
///
394+
/// // Vec of 16 x f32:
395+
/// let v: Vec<f32> = thread_rng().sample_iter(&Uniform).take(16).collect();
396+
///
397+
/// // String:
398+
/// let s: String = rng.sample_iter(&Alphanumeric).take(7).collect();
399+
///
400+
/// // Combined values
401+
/// println!("{:?}", thread_rng().sample_iter(&Uniform).take(5)
402+
/// .collect::<Vec<(f64, bool)>>());
403+
///
404+
/// // Dice-rolling:
405+
/// let die_range = Range::new_inclusive(1, 6);
406+
/// let mut roll_die = rng.sample_iter(&die_range);
407+
/// while roll_die.next().unwrap() != 6 {
408+
/// println!("Not a 6; rolling again!");
409+
/// }
410+
/// ```
411+
fn sample_iter<'a, T, D: Distribution<T>>(&'a mut self, distr: &'a D)
412+
-> distributions::DistIter<'a, D, Self, T> where Self: Sized
413+
{
414+
distr.sample_iter(self)
415+
}
383416

384417
/// Return a random value supporting the [`Uniform`] distribution.
385418
///
@@ -415,7 +448,7 @@ pub trait Rng: RngCore {
415448
/// .collect::<Vec<(f64, bool)>>());
416449
/// ```
417450
#[allow(deprecated)]
418-
#[deprecated(since="0.5.0", note="use Distribution::sample_iter instead")]
451+
#[deprecated(since="0.5.0", note="use Rng::sample_iter(&Uniform) instead")]
419452
fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where Uniform: Distribution<T> {
420453
Generator { rng: self, _marker: marker::PhantomData }
421454
}
@@ -500,7 +533,7 @@ pub trait Rng: RngCore {
500533
/// println!("{}", s);
501534
/// ```
502535
#[allow(deprecated)]
503-
#[deprecated(since="0.5.0", note="use distributions::Alphanumeric instead")]
536+
#[deprecated(since="0.5.0", note="use sample_iter(&Alphanumeric) instead")]
504537
fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self> {
505538
AsciiGenerator { rng: self }
506539
}
@@ -651,7 +684,7 @@ impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
651684
/// [`Rng`]: trait.Rng.html
652685
#[derive(Debug)]
653686
#[allow(deprecated)]
654-
#[deprecated(since="0.5.0", note="use Distribution::sample_iter instead")]
687+
#[deprecated(since="0.5.0", note="use Rng::sample_iter instead")]
655688
pub struct Generator<T, R: RngCore> {
656689
rng: R,
657690
_marker: marker::PhantomData<fn() -> T>,

0 commit comments

Comments
 (0)