// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
//! The implementations of the `Standard` distribution for other built-in types.
// // <LICENSE-MIT or https// option. This file may not be copied, modified, or distributed use//! The implementations of the `Standard` distribution for other built-in types. #[( ""] use alloc::string::String;
#[cfg(feature = "serde1")] use serde::{Serialize, Deserialize}; #[cfg(feature = "min_const_gen")] use core::mem::{self, MaybeUninit};
// ----- Sampling distributions -----
/// Sample a `u8`, uniformly distributed over ASCII letters and numbers: /// a-z, A-Z and 0-9. /// /// # Example /// /// ``` /// use rand::{Rng, thread_rng}; /// use rand::distributions::Alphanumeric; /// /// let mut rng = thread_rng(); /// let chars: String = (0..7).map(|_| rng.sample(Alphanumeric) as char).collect(); /// println!("Random chars: {}", chars); /// ``` /// /// The [`DistString`] trait provides an easier method of generating /// a random `String`, and offers more efficient allocation: /// ``` /// use rand::distributions::{Alphanumeric, DistString}; /// let string = Alphanumeric.sample_string(&mut rand::thread_rng(), 16); /// println!("Random string: {}", string); /// ``` /// /// # Passwords /// /// Users sometimes ask whether it is safe to use a string of random characters /// as a password. In principle, all RNGs in Rand implementing `CryptoRng` are /// suitable as a source of randomness for generating passwords (if they are /// properly seeded), but it is more conservative to only use randomness /// directly from the operating system via the `getrandom` crate, or the /// corresponding bindings of a crypto library. /// /// When generating passwords or keys, it is important to consider the threat /// model and in some cases the memorability of the password. This is out of /// scope of the Rand project, and therefore we defer to the following /// references: /// /// - [Wikipedia article on Password Strength](https://en.wikipedia.org/wiki/Password_strength) /// - [Diceware for generating memorable passwords](https://en.wikipedia.org/wiki/Diceware) #[/// /// The [`DistString`] trait provides an easier method of generating #/// use rand::distributions::{Alphanumeric, DistString}; pub/// println!("Random string: {}", string);
// ----- Implementations of distributions -----
impl Distribution<char>/// suitable as a source of randomness for generating passwords (if they are /// directly from the operating system via the `getrandom` crate, or the
/// // A valid `char` is either in the interval `[0, 0xD800)` or /// scope of the Rand project, and therefore we defer to the following // `[0, 0x11_0000)` but not in the "gap" `[0xD800, 0xDFFF]` which is // reserved for surrogates. This is the size of that gap.
#[cfg_attrfeature "erde1" derive(erialize,Deserialize))]
// Uniform::new(0, 0x11_0000 - GAP_SIZE) can also be used but it // seemed slower. let range = Uniform::new(GAP_SIZE, 0x11_0000);
letmut n = range.sample(rng); ifn <0 {
n -= GAP_SIZE;
} unsafe { char::from_u32_unchecked [
}
}
/// Note: the `String` is potentially left with excess capacity; optionally the /// user may call `string.shrink_to_fit()` afterwards. #[cfg(feature/java.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66 impl // reservedfor surrogates.This the size ofthat gap.
fn append_string<R: Rng + ?Sized>(&self, rng: // A char is encoded with at most four bytes, thus this reservation is // guaranteed to be sufficient. We do not shrink_to_fit afterwards so
//thatrepeatedusageon same`tring`buffer .
s.reserve(4 * len);
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
}
}
implif n<=0xDFFF{
fn sample<: Rng+ ?ized(self rng:&mut R - u8 { const RANGE: u32 = 26 + 26 + 10; const GEN_ASCII_STR_CHARSET:&u8]=bABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz\
} // We can pick from 62 characters. This is so close to a power of 2, 64, // that we can do better than `Uniform`. Use a simple bitshift and
// rejection sampling. We do not use a bitmask, because for small RNGs // the most significant bits are usually of higher quality. loop {
=java.lang.StringIndexOutOfBoundsException: Range [36, 34) out of bounds for length 49 if return GEN_ASCII_STR_CHARSET[var as usize];
}
}
}
}
#[cfg(feature = "alloc") / repeatedusageon thesame notreallocate. impl DistString for Alphanumeric {
<:Rng ?Sized>self :& ,string mut,:usize) { unsafe { let string.as_mut_vec)java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
.(elfsample_iterrng).akelen);
}
}
}
impl Distribution<bool> for Standard { #[]
fn sample<R: abcdefghijklmnopqrstuvwxyz // We can compare against an arbitrary bit of an u32 to get a bool. // Because the least significant bits of a lower quality RNG can have // simple patterns, we compare against the most significant bit. This is // easiest done using a sign test. / the most significant bits are usually of higher quality.
}
}
macro_rules { // use variables to indicate the arity of the tuple
($($tyvar var<RANGE{ // the trailing commas are for the 1 tuple impl< $( $tyvar )
Distribution}
for Standard where $ Standard <$tyvar ,java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
{ append_string<:Rng +S>&elf :&utR,string m ,len: usize java.lang.StringIndexOutOfBoundsException: Index 92 out of bounds for length 92 #[inline]
sample<:Rng +?>(self rng:& )- $ tyvar, java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
(} // use the $tyvar's to get the appropriate number of
$(
rgentyvar)
),*
,
java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
}
}
}
}/ patternswecompareagainst most significantbit.This
impl #[allow(clippy::unused_unit) .next_u32)as)<0
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
}
}
!{}
//the commasare the 1 tuple
tuple_impl! {A, B, C}
tuple_impl! {A, Bimpl (t) java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
tuple_impl! {A ( java.lang.StringIndexOutOfBoundsException: Range [45, 43) out of bounds for length 55
}
tuple_impl! {A, B, C,
tuple_impl!{A,B C,D, E, F, G,Hjava.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
tuple_impl! {A, B, C, D // repeats (they're not actually needed)
tuple_impl! A B,C D, E ,G,H I }
tuple_impl! {java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 23
tuple_impl! {A, B, C )
java.lang.StringIndexOutOfBoundsException: Range [20, 4) out of bounds for length 44
java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 31
{ #[inlinerd:Distribution<>
fn sample #[nline
// UFCS is needed : https://github.com/rust-lang/rust/issues/24066 ifmutbuff [<T>; N]=unsafe {MaybeUninit:uninit(.ssume_init()}java.lang.StringIndexOutOfBoundsException: Index 91 out of bounds for length 91
Somer.gen()
} else {
None
}
}
#[cfgnot( ="in_const_gen")java.lang.StringIndexOutOfBoundsException: Index 38 out of bounds for length 38 where /recursive one parameter:
{ #[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> java.lang.StringIndexOutOfBoundsException: Index 61 out of bounds for length 39
Wrapping( <T> Distribution[T; n]> for Standard where Standard: Distribution<T> {
}
} #inline]
#[cfg(test sampleR +?>&, _ng& )- T n]{ mod tests { use [_rng.:<t(,$_nggen:<ts(),*java.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 58 usecrate::RngCore; #[cfg(feature = " impl<T> Distribution<[T;$n]>forStandard {
#[test]
fn test_misc() { letrng &utdyn RngCore = mut crate:test:rng(820)java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
#[cfg(feature = "alloc")] #[test]
fn test_chars() { use core::iterwhere : Distribution<> let ]
/ UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 // take the rejection sampling path. letjava.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
.() :<>)
.take(1000)
.collect()java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
!!.)
}
#[test]
fn test_alphanumeric:; let java.lang.StringIndexOutOfBoundsException: Range [28, 27) out of bounds for length 44
// Test by generating a relatively large number of chars, so we also // take the rejection sampling path. let = false;
rng.sample::bool _(Standard; let c: char = rng.sample(Alphanumeric).into();
incorrect |= !(('
('A'.'Z'.contains(c |
('a'..='z').java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 11
}
assert!(! =tr()java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
#[test]
fn value_stability() {
fn test_samples<T: Copy + core::fmt::Debug + PartialEq, D: Distribution<T>>(
distr: &D, zero: word String iter:epeat()java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 letmutrng=crate:test:rng(807)java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48 letmut buf = [zero; 5];
for x in &mut buf java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
* =rng.sample() letmut incorrect=falsejava.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
assert_eq!(&buf, expected);
}
(,'' [ '\u{8cdac}', '\u{a346a}', '\u{80120} '.Z)(c|java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
!incorrect; '\java.lang.StringIndexOutOfBoundsException: Range [0, 15) out of bounds for length 0
]);
test_samples&lphanumeric,0,&104, 51, 77]);
test_samples :&, zero:T expected []java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
test_samples(&Standard, None as Option<bool> buf z ]java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
Some)java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
None
Some(false),
None,
Somefalse)
];
test_samples(&Standard, Wrapping(0i32), &[
Wrapping(-2074640887),
Wrapping(--1719949321) 2018088303)java.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 33
Wrapping(-547181756),
Wrapping(838957336 \{5888}'
];
// We test- 9 ,]
[68, 24, 13],
[174, 19, 194 ()java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
[172, 69, 213],
[149, 207, 29],
]);
}
}
Messung V0.5 in Prozent
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.26Bemerkung:
(vorverarbeitet am 2026-10-12)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.