Skip to content

Commit a70e32e

Browse files
committed
Reorder Rng methods in order of importance (for documentation)
1 parent 9dab45b commit a70e32e

File tree

1 file changed

+147
-146
lines changed

1 file changed

+147
-146
lines changed

src/lib.rs

+147-146
Original file line numberDiff line numberDiff line change
@@ -314,79 +314,61 @@ pub trait Rand : Sized {
314314
///
315315
/// [`RngCore`]: trait.RngCore.html
316316
pub trait Rng: RngCore {
317-
/// Fill `dest` entirely with random bytes (uniform value distribution),
318-
/// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
319-
/// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
320-
///
321-
/// On big-endian platforms this performs byte-swapping to ensure
322-
/// portability of results from reproducible generators.
323-
///
324-
/// This uses [`fill_bytes`] internally which may handle some RNG errors
325-
/// implicitly (e.g. waiting if the OS generator is not ready), but panics
326-
/// on other errors. See also [`try_fill`] which returns errors.
327-
///
317+
/// Return a random value supporting the [`Uniform`] distribution.
318+
///
319+
/// [`Uniform`]: distributions/struct.Uniform.html
320+
///
328321
/// # Example
329-
///
322+
///
330323
/// ```rust
331324
/// use rand::{thread_rng, Rng};
332-
///
333-
/// let mut arr = [0i8; 20];
334-
/// thread_rng().fill(&mut arr[..]);
325+
///
326+
/// let mut rng = thread_rng();
327+
/// let x: u32 = rng.gen();
328+
/// println!("{}", x);
329+
/// println!("{:?}", rng.gen::<(f64, bool)>());
335330
/// ```
336-
///
337-
/// [`fill_bytes`]: trait.RngCore.html#method.fill_bytes
338-
/// [`try_fill`]: trait.Rng.html#method.try_fill
339-
/// [`AsByteSliceMut`]: trait.AsByteSliceMut.html
340-
fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) {
341-
self.fill_bytes(dest.as_byte_slice_mut());
342-
dest.to_le();
331+
#[inline(always)]
332+
fn gen<T>(&mut self) -> T where Uniform: Distribution<T> {
333+
Uniform.sample(self)
343334
}
344-
345-
/// Fill `dest` entirely with random bytes (uniform value distribution),
346-
/// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
347-
/// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
348-
///
349-
/// On big-endian platforms this performs byte-swapping to ensure
350-
/// portability of results from reproducible generators.
351-
///
352-
/// This uses [`try_fill_bytes`] internally and forwards all RNG errors. In
353-
/// some cases errors may be resolvable; see [`ErrorKind`] and
354-
/// documentation for the RNG in use. If you do not plan to handle these
355-
/// errors you may prefer to use [`fill`].
356-
///
335+
336+
/// Generate a random value in the range [`low`, `high`), i.e. inclusive of
337+
/// `low` and exclusive of `high`.
338+
///
339+
/// This is a convenience wrapper around
340+
/// `distributions::Range`. If this function will be called
341+
/// repeatedly with the same arguments, one should use `Range`, as
342+
/// that will amortize the computations that allow for perfect
343+
/// uniformity, as they only happen when constructing the `Range`.
344+
///
345+
/// # Panics
346+
///
347+
/// Panics if `low >= high`.
348+
///
357349
/// # Example
358-
///
350+
///
359351
/// ```rust
360-
/// # use rand::Error;
361352
/// use rand::{thread_rng, Rng};
362-
///
363-
/// # fn try_inner() -> Result<(), Error> {
364-
/// let mut arr = [0u64; 4];
365-
/// thread_rng().try_fill(&mut arr[..])?;
366-
/// # Ok(())
367-
/// # }
368-
///
369-
/// # try_inner().unwrap()
353+
///
354+
/// let mut rng = thread_rng();
355+
/// let n: u32 = rng.gen_range(0, 10);
356+
/// println!("{}", n);
357+
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
358+
/// println!("{}", m);
370359
/// ```
371-
///
372-
/// [`ErrorKind`]: enum.ErrorKind.html
373-
/// [`try_fill_bytes`]: trait.RngCore.html#method.try_fill_bytes
374-
/// [`fill`]: trait.Rng.html#method.fill
375-
/// [`AsByteSliceMut`]: trait.AsByteSliceMut.html
376-
fn try_fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> {
377-
self.try_fill_bytes(dest.as_byte_slice_mut())?;
378-
dest.to_le();
379-
Ok(())
360+
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
361+
Range::sample_single(low, high, self)
380362
}
381-
363+
382364
/// Sample a new value, using the given distribution.
383-
///
365+
///
384366
/// ### Example
385-
///
367+
///
386368
/// ```rust
387369
/// use rand::{thread_rng, Rng};
388370
/// use rand::distributions::Range;
389-
///
371+
///
390372
/// let mut rng = thread_rng();
391373
/// let x: i32 = rng.sample(Range::new(10, 15));
392374
/// ```
@@ -426,96 +408,70 @@ pub trait Rng: RngCore {
426408
{
427409
distr.sample_iter(self)
428410
}
429-
430-
/// Return a random value supporting the [`Uniform`] distribution.
431-
///
432-
/// [`Uniform`]: distributions/struct.Uniform.html
433-
///
434-
/// # Example
411+
412+
/// Fill `dest` entirely with random bytes (uniform value distribution),
413+
/// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
414+
/// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
435415
///
436-
/// ```rust
437-
/// use rand::{thread_rng, Rng};
416+
/// On big-endian platforms this performs byte-swapping to ensure
417+
/// portability of results from reproducible generators.
438418
///
439-
/// let mut rng = thread_rng();
440-
/// let x: u32 = rng.gen();
441-
/// println!("{}", x);
442-
/// println!("{:?}", rng.gen::<(f64, bool)>());
443-
/// ```
444-
#[inline(always)]
445-
fn gen<T>(&mut self) -> T where Uniform: Distribution<T> {
446-
Uniform.sample(self)
447-
}
448-
449-
/// Return an iterator that will yield an infinite number of randomly
450-
/// generated items.
419+
/// This uses [`fill_bytes`] internally which may handle some RNG errors
420+
/// implicitly (e.g. waiting if the OS generator is not ready), but panics
421+
/// on other errors. See also [`try_fill`] which returns errors.
451422
///
452423
/// # Example
453424
///
454-
/// ```
455-
/// # #![allow(deprecated)]
425+
/// ```rust
456426
/// use rand::{thread_rng, Rng};
457427
///
458-
/// let mut rng = thread_rng();
459-
/// let x = rng.gen_iter::<u32>().take(10).collect::<Vec<u32>>();
460-
/// println!("{:?}", x);
461-
/// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
462-
/// .collect::<Vec<(f64, bool)>>());
428+
/// let mut arr = [0i8; 20];
429+
/// thread_rng().fill(&mut arr[..]);
463430
/// ```
464-
#[allow(deprecated)]
465-
#[deprecated(since="0.5.0", note="use Rng::sample_iter(&Uniform) instead")]
466-
fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where Uniform: Distribution<T> {
467-
Generator { rng: self, _marker: marker::PhantomData }
431+
///
432+
/// [`fill_bytes`]: trait.RngCore.html#method.fill_bytes
433+
/// [`try_fill`]: trait.Rng.html#method.try_fill
434+
/// [`AsByteSliceMut`]: trait.AsByteSliceMut.html
435+
fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) {
436+
self.fill_bytes(dest.as_byte_slice_mut());
437+
dest.to_le();
468438
}
469439

470-
/// Generate a random value in the range [`low`, `high`), i.e. inclusive of
471-
/// `low` and exclusive of `high`.
472-
///
473-
/// This is a convenience wrapper around
474-
/// `distributions::Range`. If this function will be called
475-
/// repeatedly with the same arguments, one should use `Range`, as
476-
/// that will amortize the computations that allow for perfect
477-
/// uniformity, as they only happen when constructing the `Range`.
440+
/// Fill `dest` entirely with random bytes (uniform value distribution),
441+
/// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
442+
/// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
478443
///
479-
/// # Panics
444+
/// On big-endian platforms this performs byte-swapping to ensure
445+
/// portability of results from reproducible generators.
480446
///
481-
/// Panics if `low >= high`.
447+
/// This uses [`try_fill_bytes`] internally and forwards all RNG errors. In
448+
/// some cases errors may be resolvable; see [`ErrorKind`] and
449+
/// documentation for the RNG in use. If you do not plan to handle these
450+
/// errors you may prefer to use [`fill`].
482451
///
483452
/// # Example
484453
///
485454
/// ```rust
455+
/// # use rand::Error;
486456
/// use rand::{thread_rng, Rng};
487457
///
488-
/// let mut rng = thread_rng();
489-
/// let n: u32 = rng.gen_range(0, 10);
490-
/// println!("{}", n);
491-
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
492-
/// println!("{}", m);
493-
/// ```
494-
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
495-
Range::sample_single(low, high, self)
496-
}
497-
498-
/// Return a bool with a 1 in n chance of true
499-
///
500-
/// # Example
501-
///
502-
/// ```rust
503-
/// # #![allow(deprecated)]
504-
/// use rand::{thread_rng, Rng};
458+
/// # fn try_inner() -> Result<(), Error> {
459+
/// let mut arr = [0u64; 4];
460+
/// thread_rng().try_fill(&mut arr[..])?;
461+
/// # Ok(())
462+
/// # }
505463
///
506-
/// let mut rng = thread_rng();
507-
/// assert_eq!(rng.gen_weighted_bool(0), true);
508-
/// assert_eq!(rng.gen_weighted_bool(1), true);
509-
/// // Just like `rng.gen::<bool>()` a 50-50% chance, but using a slower
510-
/// // method with different results.
511-
/// println!("{}", rng.gen_weighted_bool(2));
512-
/// // First meaningful use of `gen_weighted_bool`.
513-
/// println!("{}", rng.gen_weighted_bool(3));
464+
/// # try_inner().unwrap()
514465
/// ```
515-
#[deprecated(since="0.5.0", note="use gen_bool instead")]
516-
fn gen_weighted_bool(&mut self, n: u32) -> bool {
517-
// Short-circuit after `n <= 1` to avoid panic in `gen_range`
518-
n <= 1 || self.gen_range(0, n) == 0
466+
///
467+
/// [`ErrorKind`]: enum.ErrorKind.html
468+
/// [`try_fill_bytes`]: trait.RngCore.html#method.try_fill_bytes
469+
/// [`fill`]: trait.Rng.html#method.fill
470+
/// [`AsByteSliceMut`]: trait.AsByteSliceMut.html
471+
fn try_fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> {
472+
self.try_fill_bytes(dest.as_byte_slice_mut())?;
473+
dest.to_le();
474+
Ok(())
519475
}
520476

521477
/// Return a bool with a probability `p` of being true.
@@ -545,23 +501,6 @@ pub trait Rng: RngCore {
545501
self.gen::<u32>() <= p_int
546502
}
547503

548-
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
549-
///
550-
/// # Example
551-
///
552-
/// ```rust
553-
/// # #![allow(deprecated)]
554-
/// use rand::{thread_rng, Rng};
555-
///
556-
/// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
557-
/// println!("{}", s);
558-
/// ```
559-
#[allow(deprecated)]
560-
#[deprecated(since="0.5.0", note="use sample_iter(&Alphanumeric) instead")]
561-
fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self> {
562-
AsciiGenerator { rng: self }
563-
}
564-
565504
/// Return a random element from `values`.
566505
///
567506
/// Return `None` if `values` is empty.
@@ -598,7 +537,8 @@ pub trait Rng: RngCore {
598537

599538
/// Shuffle a mutable slice in place.
600539
///
601-
/// This applies Durstenfeld's algorithm for the [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm)
540+
/// This applies Durstenfeld's algorithm for the [Fisher–Yates shuffle](
541+
/// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm)
602542
/// which produces an unbiased permutation.
603543
///
604544
/// # Example
@@ -622,6 +562,67 @@ pub trait Rng: RngCore {
622562
values.swap(i, self.gen_range(0, i + 1));
623563
}
624564
}
565+
566+
/// Return an iterator that will yield an infinite number of randomly
567+
/// generated items.
568+
///
569+
/// # Example
570+
///
571+
/// ```
572+
/// # #![allow(deprecated)]
573+
/// use rand::{thread_rng, Rng};
574+
///
575+
/// let mut rng = thread_rng();
576+
/// let x = rng.gen_iter::<u32>().take(10).collect::<Vec<u32>>();
577+
/// println!("{:?}", x);
578+
/// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
579+
/// .collect::<Vec<(f64, bool)>>());
580+
/// ```
581+
#[allow(deprecated)]
582+
#[deprecated(since="0.5.0", note="use Rng::sample_iter(&Uniform) instead")]
583+
fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where Uniform: Distribution<T> {
584+
Generator { rng: self, _marker: marker::PhantomData }
585+
}
586+
587+
/// Return a bool with a 1 in n chance of true
588+
///
589+
/// # Example
590+
///
591+
/// ```rust
592+
/// # #![allow(deprecated)]
593+
/// use rand::{thread_rng, Rng};
594+
///
595+
/// let mut rng = thread_rng();
596+
/// assert_eq!(rng.gen_weighted_bool(0), true);
597+
/// assert_eq!(rng.gen_weighted_bool(1), true);
598+
/// // Just like `rng.gen::<bool>()` a 50-50% chance, but using a slower
599+
/// // method with different results.
600+
/// println!("{}", rng.gen_weighted_bool(2));
601+
/// // First meaningful use of `gen_weighted_bool`.
602+
/// println!("{}", rng.gen_weighted_bool(3));
603+
/// ```
604+
#[deprecated(since="0.5.0", note="use gen_bool instead")]
605+
fn gen_weighted_bool(&mut self, n: u32) -> bool {
606+
// Short-circuit after `n <= 1` to avoid panic in `gen_range`
607+
n <= 1 || self.gen_range(0, n) == 0
608+
}
609+
610+
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
611+
///
612+
/// # Example
613+
///
614+
/// ```rust
615+
/// # #![allow(deprecated)]
616+
/// use rand::{thread_rng, Rng};
617+
///
618+
/// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
619+
/// println!("{}", s);
620+
/// ```
621+
#[allow(deprecated)]
622+
#[deprecated(since="0.5.0", note="use sample_iter(&Alphanumeric) instead")]
623+
fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self> {
624+
AsciiGenerator { rng: self }
625+
}
625626
}
626627

627628
impl<R: RngCore + ?Sized> Rng for R {}

0 commit comments

Comments
 (0)