@@ -46,6 +46,7 @@ use std::char;
4646use std:: error;
4747use std:: fmt:: { self , Debug } ;
4848use std:: mem;
49+ use std:: string:: FromUtf8Error ;
4950
5051const 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