|
11 | 11 |
|
12 | 12 | use crate::Rng;
|
13 | 13 | use core::iter;
|
| 14 | +#[cfg(feature = "alloc")] |
| 15 | +use alloc::string::String; |
14 | 16 |
|
15 | 17 | /// Types (distributions) that can be used to create a random instance of `T`.
|
16 | 18 | ///
|
@@ -187,9 +189,27 @@ where
|
187 | 189 | }
|
188 | 190 | }
|
189 | 191 |
|
| 192 | +/// `String` sampler |
| 193 | +/// |
| 194 | +/// Sampling a `String` of random characters is not quite the same as collecting |
| 195 | +/// a sequence of chars. This trait contains some helpers. |
| 196 | +#[cfg(feature = "alloc")] |
| 197 | +pub trait DistString { |
| 198 | + /// Append `len` random chars to `string` |
| 199 | + fn append_string<R: Rng + ?Sized>(&self, rng: &mut R, string: &mut String, len: usize); |
| 200 | + |
| 201 | + /// Generate a `String` of `len` random chars |
| 202 | + #[inline] |
| 203 | + fn sample_string<R: Rng + ?Sized>(&self, rng: &mut R, len: usize) -> String { |
| 204 | + let mut s = String::new(); |
| 205 | + self.append_string(rng, &mut s, len); |
| 206 | + s |
| 207 | + } |
| 208 | +} |
| 209 | + |
190 | 210 | #[cfg(test)]
|
191 | 211 | mod tests {
|
192 |
| - use crate::distributions::{Distribution, Uniform}; |
| 212 | + use crate::distributions::{Alphanumeric, Distribution, Standard, Uniform}; |
193 | 213 | use crate::Rng;
|
194 | 214 |
|
195 | 215 | #[test]
|
@@ -233,4 +253,20 @@ mod tests {
|
233 | 253 | }
|
234 | 254 | assert_eq!(count, 10);
|
235 | 255 | }
|
| 256 | + |
| 257 | + #[test] |
| 258 | + #[cfg(feature = "alloc")] |
| 259 | + fn test_dist_string() { |
| 260 | + use core::str; |
| 261 | + use crate::distributions::DistString; |
| 262 | + let mut rng = crate::test::rng(213); |
| 263 | + |
| 264 | + let s1 = Alphanumeric.sample_string(&mut rng, 20); |
| 265 | + assert_eq!(s1.len(), 20); |
| 266 | + assert_eq!(str::from_utf8(s1.as_bytes()), Ok(s1.as_str())); |
| 267 | + |
| 268 | + let s2 = Standard.sample_string(&mut rng, 20); |
| 269 | + assert_eq!(s2.chars().count(), 20); |
| 270 | + assert_eq!(str::from_utf8(s2.as_bytes()), Ok(s2.as_str())); |
| 271 | + } |
236 | 272 | }
|
0 commit comments