Skip to content

Commit 6478cfc

Browse files
committed
impl Distribution<Result<String, FromUtf8Error>> for Regex.
1 parent 5322834 commit 6478cfc

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
Changelog
22
=========
33

4+
v0.14.1 (2020 Jan 27)
5+
---------------------
6+
7+
Added an additional `impl Distribution<Result<String, FromUtf8Error>> for Regex`.
8+
49
v0.14.0 (2020 Jan 25)
510
---------------------
611

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "rand_regex"
3-
version = "0.14.0"
3+
version = "0.14.1"
44
authors = ["kennytm <[email protected]>"]
55
description = "Generates random strings and byte strings matching a regex"
66
repository = "https://github.com/kennytm/rand_regex"

src/lib.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ use std::char;
4646
use std::error;
4747
use std::fmt::{self, Debug};
4848
use std::mem;
49+
use std::string::FromUtf8Error;
4950

5051
const SHORT_UNICODE_CLASS_COUNT: usize = 64;
5152

@@ -148,14 +149,24 @@ impl Distribution<String> for Regex {
148149
///
149150
/// If the regex produced some non-UTF-8 byte sequence, this method will
150151
/// panic. You may want to check [`is_utf8()`](Regex::is_utf8) to ensure the
151-
/// regex will only generate valid Unicode strings, or sample a `Vec<u8>`
152-
/// and manually check for UTF-8 validity.
152+
/// regex will only generate valid Unicode strings, or sample a
153+
/// `Result<String, FromUtf8Error>` and manually handle the error.
153154
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> String {
155+
<Self as Distribution<Result<_, _>>>::sample(self, rng).unwrap()
156+
}
157+
}
158+
159+
impl Distribution<Result<String, FromUtf8Error>> for Regex {
160+
/// Samples a random string satisfying the regex.
161+
///
162+
/// The the sampled bytes sequence is not valid UTF-8, the sampling result
163+
/// is an Err value.
164+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<String, FromUtf8Error> {
154165
let bytes = <Self as Distribution<Vec<u8>>>::sample(self, rng);
155166
if self.is_utf8 {
156-
unsafe { String::from_utf8_unchecked(bytes) }
167+
unsafe { Ok(String::from_utf8_unchecked(bytes)) }
157168
} else {
158-
String::from_utf8(bytes).unwrap()
169+
String::from_utf8(bytes)
159170
}
160171
}
161172
}

0 commit comments

Comments
 (0)