1 use std::char;
2 use std::collections::{
3 BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
4 };
5 use std::env;
6 use std::ffi::{CString, OsString};
7 use std::hash::{BuildHasher, Hash};
8 use std::iter::{empty, once};
9 use std::net::{
10 IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6,
11 };
12 use std::num::Wrapping;
13 use std::num::{
14 NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
15 };
16 use std::ops::{
17 Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
18 RangeToInclusive,
19 };
20 use std::path::PathBuf;
21 use std::sync::Arc;
22 use std::time::{Duration, SystemTime, UNIX_EPOCH};
23
24 use rand::seq::SliceRandom;
25 use rand::{self, Rng, SeedableRng};
26
27 /// Gen represents a PRNG.
28 ///
29 /// It is the source of randomness from which QuickCheck will generate
30 /// values. An instance of `Gen` is passed to every invocation of
31 /// `Arbitrary::arbitrary`, which permits callers to use lower level RNG
32 /// routines to generate values.
33 ///
34 /// It is unspecified whether this is a secure RNG or not. Therefore, callers
35 /// should assume it is insecure.
36 pub struct Gen {
37 rng: rand::rngs::SmallRng,
38 size: usize,
39 }
40
41 impl Gen {
42 /// Returns a `Gen` with the given size configuration.
43 ///
44 /// The `size` parameter controls the size of random values generated.
45 /// For example, it specifies the maximum length of a randomly generated
46 /// vector, but is and should not be used to control the range of a
47 /// randomly generated number. (Unless that number is used to control the
48 /// size of a data structure.)
new(size: usize) -> Gen49 pub fn new(size: usize) -> Gen {
50 Gen { rng: rand::rngs::SmallRng::from_entropy(), size: size }
51 }
52
53 /// Returns the size configured with this generator.
size(&self) -> usize54 pub fn size(&self) -> usize {
55 self.size
56 }
57
58 /// Choose among the possible alternatives in the slice given. If the slice
59 /// is empty, then `None` is returned. Otherwise, a non-`None` value is
60 /// guaranteed to be returned.
choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T>61 pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
62 slice.choose(&mut self.rng)
63 }
64
gen<T>(&mut self) -> T where rand::distributions::Standard: rand::distributions::Distribution<T>,65 fn gen<T>(&mut self) -> T
66 where
67 rand::distributions::Standard: rand::distributions::Distribution<T>,
68 {
69 self.rng.gen()
70 }
71
gen_range<T, R>(&mut self, range: R) -> T where T: rand::distributions::uniform::SampleUniform, R: rand::distributions::uniform::SampleRange<T>,72 fn gen_range<T, R>(&mut self, range: R) -> T
73 where
74 T: rand::distributions::uniform::SampleUniform,
75 R: rand::distributions::uniform::SampleRange<T>,
76 {
77 self.rng.gen_range(range)
78 }
79 }
80
81 /// Creates a shrinker with zero elements.
empty_shrinker<A: 'static>() -> Box<dyn Iterator<Item = A>>82 pub fn empty_shrinker<A: 'static>() -> Box<dyn Iterator<Item = A>> {
83 Box::new(empty())
84 }
85
86 /// Creates a shrinker with a single element.
single_shrinker<A: 'static>(value: A) -> Box<dyn Iterator<Item = A>>87 pub fn single_shrinker<A: 'static>(value: A) -> Box<dyn Iterator<Item = A>> {
88 Box::new(once(value))
89 }
90
91 /// `Arbitrary` describes types whose values can be randomly generated and
92 /// shrunk.
93 ///
94 /// Aside from shrinking, `Arbitrary` is different from typical RNGs in that
95 /// it respects `Gen::size()` for controlling how much memory a particular
96 /// value uses, for practical purposes. For example, `Vec::arbitrary()`
97 /// respects `Gen::size()` to decide the maximum `len()` of the vector.
98 /// This behavior is necessary due to practical speed and size limitations.
99 /// Conversely, `i32::arbitrary()` ignores `size()` since all `i32` values
100 /// require `O(1)` memory and operations between `i32`s require `O(1)` time
101 /// (with the exception of exponentiation).
102 ///
103 /// Additionally, all types that implement `Arbitrary` must also implement
104 /// `Clone`.
105 pub trait Arbitrary: Clone + 'static {
106 /// Return an arbitrary value.
107 ///
108 /// Implementations should respect `Gen::size()` when decisions about how
109 /// big a particular value should be. Implementations should generally
110 /// defer to other `Arbitrary` implementations to generate other random
111 /// values when necessary. The `Gen` type also offers a few RNG helper
112 /// routines.
arbitrary(g: &mut Gen) -> Self113 fn arbitrary(g: &mut Gen) -> Self;
114
115 /// Return an iterator of values that are smaller than itself.
116 ///
117 /// The way in which a value is "smaller" is implementation defined. In
118 /// some cases, the interpretation is obvious: shrinking an integer should
119 /// produce integers smaller than itself. Others are more complex, for
120 /// example, shrinking a `Vec` should both shrink its size and shrink its
121 /// component values.
122 ///
123 /// The iterator returned should be bounded to some reasonable size.
124 ///
125 /// It is always correct to return an empty iterator, and indeed, this
126 /// is the default implementation. The downside of this approach is that
127 /// witnesses to failures in properties will be more inscrutable.
shrink(&self) -> Box<dyn Iterator<Item = Self>>128 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
129 empty_shrinker()
130 }
131 }
132
133 impl Arbitrary for () {
arbitrary(_: &mut Gen) -> ()134 fn arbitrary(_: &mut Gen) -> () {
135 ()
136 }
137 }
138
139 impl Arbitrary for bool {
arbitrary(g: &mut Gen) -> bool140 fn arbitrary(g: &mut Gen) -> bool {
141 g.gen()
142 }
143
shrink(&self) -> Box<dyn Iterator<Item = bool>>144 fn shrink(&self) -> Box<dyn Iterator<Item = bool>> {
145 if *self {
146 single_shrinker(false)
147 } else {
148 empty_shrinker()
149 }
150 }
151 }
152
153 impl<A: Arbitrary> Arbitrary for Option<A> {
arbitrary(g: &mut Gen) -> Option<A>154 fn arbitrary(g: &mut Gen) -> Option<A> {
155 if g.gen() {
156 None
157 } else {
158 Some(Arbitrary::arbitrary(g))
159 }
160 }
161
shrink(&self) -> Box<dyn Iterator<Item = Option<A>>>162 fn shrink(&self) -> Box<dyn Iterator<Item = Option<A>>> {
163 match *self {
164 None => empty_shrinker(),
165 Some(ref x) => {
166 let chain = single_shrinker(None).chain(x.shrink().map(Some));
167 Box::new(chain)
168 }
169 }
170 }
171 }
172
173 impl<A: Arbitrary, B: Arbitrary> Arbitrary for Result<A, B> {
arbitrary(g: &mut Gen) -> Result<A, B>174 fn arbitrary(g: &mut Gen) -> Result<A, B> {
175 if g.gen() {
176 Ok(Arbitrary::arbitrary(g))
177 } else {
178 Err(Arbitrary::arbitrary(g))
179 }
180 }
181
shrink(&self) -> Box<dyn Iterator<Item = Result<A, B>>>182 fn shrink(&self) -> Box<dyn Iterator<Item = Result<A, B>>> {
183 match *self {
184 Ok(ref x) => {
185 let xs = x.shrink();
186 let tagged = xs.map(Ok);
187 Box::new(tagged)
188 }
189 Err(ref x) => {
190 let xs = x.shrink();
191 let tagged = xs.map(Err);
192 Box::new(tagged)
193 }
194 }
195 }
196 }
197
198 macro_rules! impl_arb_for_single_tuple {
199 ($(($type_param:ident, $tuple_index:tt),)*) => {
200 impl<$($type_param),*> Arbitrary for ($($type_param,)*)
201 where $($type_param: Arbitrary,)*
202 {
203 fn arbitrary(g: &mut Gen) -> ($($type_param,)*) {
204 (
205 $(
206 $type_param::arbitrary(g),
207 )*
208 )
209 }
210
211 fn shrink(&self) -> Box<dyn Iterator<Item=($($type_param,)*)>> {
212 let iter = ::std::iter::empty();
213 $(
214 let cloned = self.clone();
215 let iter = iter.chain(
216 self.$tuple_index.shrink().map(move |shr_value| {
217 let mut result = cloned.clone();
218 result.$tuple_index = shr_value;
219 result
220 })
221 );
222 )*
223 Box::new(iter)
224 }
225 }
226 };
227 }
228
229 macro_rules! impl_arb_for_tuples {
230 (@internal [$($acc:tt,)*]) => { };
231 (@internal [$($acc:tt,)*] ($type_param:ident, $tuple_index:tt), $($rest:tt,)*) => {
232 impl_arb_for_single_tuple!($($acc,)* ($type_param, $tuple_index),);
233 impl_arb_for_tuples!(@internal [$($acc,)* ($type_param, $tuple_index),] $($rest,)*);
234 };
235 ($(($type_param:ident, $tuple_index:tt),)*) => {
236 impl_arb_for_tuples!(@internal [] $(($type_param, $tuple_index),)*);
237 };
238 }
239
240 impl_arb_for_tuples! {
241 (A, 0),
242 (B, 1),
243 (C, 2),
244 (D, 3),
245 (E, 4),
246 (F, 5),
247 (G, 6),
248 (H, 7),
249 }
250
251 impl<A: Arbitrary> Arbitrary for Vec<A> {
arbitrary(g: &mut Gen) -> Vec<A>252 fn arbitrary(g: &mut Gen) -> Vec<A> {
253 let size = {
254 let s = g.size();
255 g.gen_range(0..s)
256 };
257 (0..size).map(|_| A::arbitrary(g)).collect()
258 }
259
shrink(&self) -> Box<dyn Iterator<Item = Vec<A>>>260 fn shrink(&self) -> Box<dyn Iterator<Item = Vec<A>>> {
261 VecShrinker::new(self.clone())
262 }
263 }
264
265 ///Iterator which returns successive attempts to shrink the vector `seed`
266 struct VecShrinker<A> {
267 seed: Vec<A>,
268 /// How much which is removed when trying with smaller vectors
269 size: usize,
270 /// The end of the removed elements
271 offset: usize,
272 /// The shrinker for the element at `offset` once shrinking of individual
273 /// elements are attempted
274 element_shrinker: Box<dyn Iterator<Item = A>>,
275 }
276
277 impl<A: Arbitrary> VecShrinker<A> {
new(seed: Vec<A>) -> Box<dyn Iterator<Item = Vec<A>>>278 fn new(seed: Vec<A>) -> Box<dyn Iterator<Item = Vec<A>>> {
279 let es = match seed.get(0) {
280 Some(e) => e.shrink(),
281 None => return empty_shrinker(),
282 };
283 let size = seed.len();
284 Box::new(VecShrinker {
285 seed: seed,
286 size: size,
287 offset: size,
288 element_shrinker: es,
289 })
290 }
291
292 /// Returns the next shrunk element if any, `offset` points to the index
293 /// after the returned element after the function returns
next_element(&mut self) -> Option<A>294 fn next_element(&mut self) -> Option<A> {
295 loop {
296 match self.element_shrinker.next() {
297 Some(e) => return Some(e),
298 None => match self.seed.get(self.offset) {
299 Some(e) => {
300 self.element_shrinker = e.shrink();
301 self.offset += 1;
302 }
303 None => return None,
304 },
305 }
306 }
307 }
308 }
309
310 impl<A> Iterator for VecShrinker<A>
311 where
312 A: Arbitrary,
313 {
314 type Item = Vec<A>;
next(&mut self) -> Option<Vec<A>>315 fn next(&mut self) -> Option<Vec<A>> {
316 // Try with an empty vector first
317 if self.size == self.seed.len() {
318 self.size /= 2;
319 self.offset = self.size;
320 return Some(vec![]);
321 }
322 if self.size != 0 {
323 // Generate a smaller vector by removing the elements between
324 // (offset - size) and offset
325 let xs1 = self.seed[..(self.offset - self.size)]
326 .iter()
327 .chain(&self.seed[self.offset..])
328 .cloned()
329 .collect();
330 self.offset += self.size;
331 // Try to reduce the amount removed from the vector once all
332 // previous sizes tried
333 if self.offset > self.seed.len() {
334 self.size /= 2;
335 self.offset = self.size;
336 }
337 Some(xs1)
338 } else {
339 // A smaller vector did not work so try to shrink each element of
340 // the vector instead Reuse `offset` as the index determining which
341 // element to shrink
342
343 // The first element shrinker is already created so skip the first
344 // offset (self.offset == 0 only on first entry to this part of the
345 // iterator)
346 if self.offset == 0 {
347 self.offset = 1
348 }
349
350 match self.next_element() {
351 Some(e) => Some(
352 self.seed[..self.offset - 1]
353 .iter()
354 .cloned()
355 .chain(Some(e).into_iter())
356 .chain(self.seed[self.offset..].iter().cloned())
357 .collect(),
358 ),
359 None => None,
360 }
361 }
362 }
363 }
364
365 impl<K: Arbitrary + Ord, V: Arbitrary> Arbitrary for BTreeMap<K, V> {
arbitrary(g: &mut Gen) -> BTreeMap<K, V>366 fn arbitrary(g: &mut Gen) -> BTreeMap<K, V> {
367 let vec: Vec<(K, V)> = Arbitrary::arbitrary(g);
368 vec.into_iter().collect()
369 }
370
shrink(&self) -> Box<dyn Iterator<Item = BTreeMap<K, V>>>371 fn shrink(&self) -> Box<dyn Iterator<Item = BTreeMap<K, V>>> {
372 let vec: Vec<(K, V)> = self.clone().into_iter().collect();
373 Box::new(
374 vec.shrink().map(|v| v.into_iter().collect::<BTreeMap<K, V>>()),
375 )
376 }
377 }
378
379 impl<
380 K: Arbitrary + Eq + Hash,
381 V: Arbitrary,
382 S: BuildHasher + Default + Clone + 'static,
383 > Arbitrary for HashMap<K, V, S>
384 {
arbitrary(g: &mut Gen) -> Self385 fn arbitrary(g: &mut Gen) -> Self {
386 let vec: Vec<(K, V)> = Arbitrary::arbitrary(g);
387 vec.into_iter().collect()
388 }
389
shrink(&self) -> Box<dyn Iterator<Item = Self>>390 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
391 let vec: Vec<(K, V)> = self.clone().into_iter().collect();
392 Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>()))
393 }
394 }
395
396 impl<T: Arbitrary + Ord> Arbitrary for BTreeSet<T> {
arbitrary(g: &mut Gen) -> BTreeSet<T>397 fn arbitrary(g: &mut Gen) -> BTreeSet<T> {
398 let vec: Vec<T> = Arbitrary::arbitrary(g);
399 vec.into_iter().collect()
400 }
401
shrink(&self) -> Box<dyn Iterator<Item = BTreeSet<T>>>402 fn shrink(&self) -> Box<dyn Iterator<Item = BTreeSet<T>>> {
403 let vec: Vec<T> = self.clone().into_iter().collect();
404 Box::new(vec.shrink().map(|v| v.into_iter().collect::<BTreeSet<T>>()))
405 }
406 }
407
408 impl<T: Arbitrary + Ord> Arbitrary for BinaryHeap<T> {
arbitrary(g: &mut Gen) -> BinaryHeap<T>409 fn arbitrary(g: &mut Gen) -> BinaryHeap<T> {
410 let vec: Vec<T> = Arbitrary::arbitrary(g);
411 vec.into_iter().collect()
412 }
413
shrink(&self) -> Box<dyn Iterator<Item = BinaryHeap<T>>>414 fn shrink(&self) -> Box<dyn Iterator<Item = BinaryHeap<T>>> {
415 let vec: Vec<T> = self.clone().into_iter().collect();
416 Box::new(
417 vec.shrink().map(|v| v.into_iter().collect::<BinaryHeap<T>>()),
418 )
419 }
420 }
421
422 impl<T: Arbitrary + Eq + Hash, S: BuildHasher + Default + Clone + 'static>
423 Arbitrary for HashSet<T, S>
424 {
arbitrary(g: &mut Gen) -> Self425 fn arbitrary(g: &mut Gen) -> Self {
426 let vec: Vec<T> = Arbitrary::arbitrary(g);
427 vec.into_iter().collect()
428 }
429
shrink(&self) -> Box<dyn Iterator<Item = Self>>430 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
431 let vec: Vec<T> = self.clone().into_iter().collect();
432 Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>()))
433 }
434 }
435
436 impl<T: Arbitrary> Arbitrary for LinkedList<T> {
arbitrary(g: &mut Gen) -> LinkedList<T>437 fn arbitrary(g: &mut Gen) -> LinkedList<T> {
438 let vec: Vec<T> = Arbitrary::arbitrary(g);
439 vec.into_iter().collect()
440 }
441
shrink(&self) -> Box<dyn Iterator<Item = LinkedList<T>>>442 fn shrink(&self) -> Box<dyn Iterator<Item = LinkedList<T>>> {
443 let vec: Vec<T> = self.clone().into_iter().collect();
444 Box::new(
445 vec.shrink().map(|v| v.into_iter().collect::<LinkedList<T>>()),
446 )
447 }
448 }
449
450 impl<T: Arbitrary> Arbitrary for VecDeque<T> {
arbitrary(g: &mut Gen) -> VecDeque<T>451 fn arbitrary(g: &mut Gen) -> VecDeque<T> {
452 let vec: Vec<T> = Arbitrary::arbitrary(g);
453 vec.into_iter().collect()
454 }
455
shrink(&self) -> Box<dyn Iterator<Item = VecDeque<T>>>456 fn shrink(&self) -> Box<dyn Iterator<Item = VecDeque<T>>> {
457 let vec: Vec<T> = self.clone().into_iter().collect();
458 Box::new(vec.shrink().map(|v| v.into_iter().collect::<VecDeque<T>>()))
459 }
460 }
461
462 impl Arbitrary for IpAddr {
arbitrary(g: &mut Gen) -> IpAddr463 fn arbitrary(g: &mut Gen) -> IpAddr {
464 let ipv4: bool = g.gen();
465 if ipv4 {
466 IpAddr::V4(Arbitrary::arbitrary(g))
467 } else {
468 IpAddr::V6(Arbitrary::arbitrary(g))
469 }
470 }
471 }
472
473 impl Arbitrary for Ipv4Addr {
arbitrary(g: &mut Gen) -> Ipv4Addr474 fn arbitrary(g: &mut Gen) -> Ipv4Addr {
475 Ipv4Addr::new(g.gen(), g.gen(), g.gen(), g.gen())
476 }
477 }
478
479 impl Arbitrary for Ipv6Addr {
arbitrary(g: &mut Gen) -> Ipv6Addr480 fn arbitrary(g: &mut Gen) -> Ipv6Addr {
481 Ipv6Addr::new(
482 g.gen(),
483 g.gen(),
484 g.gen(),
485 g.gen(),
486 g.gen(),
487 g.gen(),
488 g.gen(),
489 g.gen(),
490 )
491 }
492 }
493
494 impl Arbitrary for SocketAddr {
arbitrary(g: &mut Gen) -> SocketAddr495 fn arbitrary(g: &mut Gen) -> SocketAddr {
496 SocketAddr::new(Arbitrary::arbitrary(g), g.gen())
497 }
498 }
499
500 impl Arbitrary for SocketAddrV4 {
arbitrary(g: &mut Gen) -> SocketAddrV4501 fn arbitrary(g: &mut Gen) -> SocketAddrV4 {
502 SocketAddrV4::new(Arbitrary::arbitrary(g), g.gen())
503 }
504 }
505
506 impl Arbitrary for SocketAddrV6 {
arbitrary(g: &mut Gen) -> SocketAddrV6507 fn arbitrary(g: &mut Gen) -> SocketAddrV6 {
508 SocketAddrV6::new(Arbitrary::arbitrary(g), g.gen(), g.gen(), g.gen())
509 }
510 }
511
512 impl Arbitrary for PathBuf {
arbitrary(g: &mut Gen) -> PathBuf513 fn arbitrary(g: &mut Gen) -> PathBuf {
514 // use some real directories as guesses, so we may end up with
515 // actual working directories in case that is relevant.
516 let here =
517 env::current_dir().unwrap_or(PathBuf::from("/test/directory"));
518 let temp = env::temp_dir();
519 #[allow(deprecated)]
520 let home = env::home_dir().unwrap_or(PathBuf::from("/home/user"));
521 let mut p = g
522 .choose(&[
523 here,
524 temp,
525 home,
526 PathBuf::from("."),
527 PathBuf::from(".."),
528 PathBuf::from("../../.."),
529 PathBuf::new(),
530 ])
531 .unwrap()
532 .to_owned();
533 p.extend(Vec::<OsString>::arbitrary(g).iter());
534 p
535 }
536
shrink(&self) -> Box<dyn Iterator<Item = PathBuf>>537 fn shrink(&self) -> Box<dyn Iterator<Item = PathBuf>> {
538 let mut shrunk = vec![];
539 let mut popped = self.clone();
540 if popped.pop() {
541 shrunk.push(popped);
542 }
543
544 // Iterating over a Path performs a small amount of normalization.
545 let normalized = self.iter().collect::<PathBuf>();
546 if normalized.as_os_str() != self.as_os_str() {
547 shrunk.push(normalized);
548 }
549
550 // Add the canonicalized variant only if canonicalizing the path
551 // actually does something, making it (hopefully) smaller. Also, ignore
552 // canonicalization if canonicalization errors.
553 if let Ok(canonicalized) = self.canonicalize() {
554 if canonicalized.as_os_str() != self.as_os_str() {
555 shrunk.push(canonicalized);
556 }
557 }
558
559 Box::new(shrunk.into_iter())
560 }
561 }
562
563 impl Arbitrary for OsString {
arbitrary(g: &mut Gen) -> OsString564 fn arbitrary(g: &mut Gen) -> OsString {
565 OsString::from(String::arbitrary(g))
566 }
567
shrink(&self) -> Box<dyn Iterator<Item = OsString>>568 fn shrink(&self) -> Box<dyn Iterator<Item = OsString>> {
569 let mystring: String = self.clone().into_string().unwrap();
570 Box::new(mystring.shrink().map(|s| OsString::from(s)))
571 }
572 }
573
574 impl Arbitrary for String {
arbitrary(g: &mut Gen) -> String575 fn arbitrary(g: &mut Gen) -> String {
576 let size = {
577 let s = g.size();
578 g.gen_range(0..s)
579 };
580 (0..size).map(|_| char::arbitrary(g)).collect()
581 }
582
shrink(&self) -> Box<dyn Iterator<Item = String>>583 fn shrink(&self) -> Box<dyn Iterator<Item = String>> {
584 // Shrink a string by shrinking a vector of its characters.
585 let chars: Vec<char> = self.chars().collect();
586 Box::new(chars.shrink().map(|x| x.into_iter().collect::<String>()))
587 }
588 }
589
590 impl Arbitrary for CString {
arbitrary(g: &mut Gen) -> Self591 fn arbitrary(g: &mut Gen) -> Self {
592 let size = {
593 let s = g.size();
594 g.gen_range(0..s)
595 };
596 // Use either random bytes or random UTF-8 encoded codepoints.
597 let utf8: bool = g.gen();
598 if utf8 {
599 CString::new(
600 (0..)
601 .map(|_| char::arbitrary(g))
602 .filter(|&c| c != '\0')
603 .take(size)
604 .collect::<String>(),
605 )
606 } else {
607 CString::new(
608 (0..)
609 .map(|_| u8::arbitrary(g))
610 .filter(|&c| c != b'\0')
611 .take(size)
612 .collect::<Vec<u8>>(),
613 )
614 }
615 .expect("null characters should have been filtered out")
616 }
617
shrink(&self) -> Box<dyn Iterator<Item = CString>>618 fn shrink(&self) -> Box<dyn Iterator<Item = CString>> {
619 // Use the implementation for a vec here, but make sure null characters
620 // are filtered out.
621 Box::new(VecShrinker::new(self.as_bytes().to_vec()).map(|bytes| {
622 CString::new(
623 bytes.into_iter().filter(|&c| c != 0).collect::<Vec<u8>>(),
624 )
625 .expect("null characters should have been filtered out")
626 }))
627 }
628 }
629
630 impl Arbitrary for char {
arbitrary(g: &mut Gen) -> char631 fn arbitrary(g: &mut Gen) -> char {
632 let mode = g.gen_range(0..100);
633 match mode {
634 0..=49 => {
635 // ASCII + some control characters
636 g.gen_range(0..0xB0) as u8 as char
637 }
638 50..=59 => {
639 // Unicode BMP characters
640 loop {
641 if let Some(x) = char::from_u32(g.gen_range(0..0x10000)) {
642 return x;
643 }
644 // ignore surrogate pairs
645 }
646 }
647 60..=84 => {
648 // Characters often used in programming languages
649 g.choose(&[
650 ' ', ' ', ' ', '\t', '\n', '~', '`', '!', '@', '#', '$',
651 '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '[',
652 ']', '{', '}', ':', ';', '\'', '"', '\\', '|', ',', '<',
653 '>', '.', '/', '?', '0', '1', '2', '3', '4', '5', '6',
654 '7', '8', '9',
655 ])
656 .unwrap()
657 .to_owned()
658 }
659 85..=89 => {
660 // Tricky Unicode, part 1
661 g.choose(&[
662 '\u{0149}', // a deprecated character
663 '\u{fff0}', // some of "Other, format" category:
664 '\u{fff1}',
665 '\u{fff2}',
666 '\u{fff3}',
667 '\u{fff4}',
668 '\u{fff5}',
669 '\u{fff6}',
670 '\u{fff7}',
671 '\u{fff8}',
672 '\u{fff9}',
673 '\u{fffA}',
674 '\u{fffB}',
675 '\u{fffC}',
676 '\u{fffD}',
677 '\u{fffE}',
678 '\u{fffF}',
679 '\u{0600}',
680 '\u{0601}',
681 '\u{0602}',
682 '\u{0603}',
683 '\u{0604}',
684 '\u{0605}',
685 '\u{061C}',
686 '\u{06DD}',
687 '\u{070F}',
688 '\u{180E}',
689 '\u{110BD}',
690 '\u{1D173}',
691 '\u{e0001}', // tag
692 '\u{e0020}', // tag space
693 '\u{e000}',
694 '\u{e001}',
695 '\u{ef8ff}', // private use
696 '\u{f0000}',
697 '\u{ffffd}',
698 '\u{ffffe}',
699 '\u{fffff}',
700 '\u{100000}',
701 '\u{10FFFD}',
702 '\u{10FFFE}',
703 '\u{10FFFF}',
704 // "Other, surrogate" characters are so that very special
705 // that they are not even allowed in safe Rust,
706 //so omitted here
707 '\u{3000}', // ideographic space
708 '\u{1680}',
709 // other space characters are already covered by two next
710 // branches
711 ])
712 .unwrap()
713 .to_owned()
714 }
715 90..=94 => {
716 // Tricky unicode, part 2
717 char::from_u32(g.gen_range(0x2000..0x2070)).unwrap()
718 }
719 95..=99 => {
720 // Completely arbitrary characters
721 g.gen()
722 }
723 _ => unreachable!(),
724 }
725 }
726
shrink(&self) -> Box<dyn Iterator<Item = char>>727 fn shrink(&self) -> Box<dyn Iterator<Item = char>> {
728 Box::new((*self as u32).shrink().filter_map(char::from_u32))
729 }
730 }
731
732 macro_rules! unsigned_shrinker {
733 ($ty:ty) => {
734 mod shrinker {
735 pub struct UnsignedShrinker {
736 x: $ty,
737 i: $ty,
738 }
739
740 impl UnsignedShrinker {
741 pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
742 if x == 0 {
743 super::empty_shrinker()
744 } else {
745 Box::new(
746 vec![0]
747 .into_iter()
748 .chain(UnsignedShrinker { x: x, i: x / 2 }),
749 )
750 }
751 }
752 }
753
754 impl Iterator for UnsignedShrinker {
755 type Item = $ty;
756 fn next(&mut self) -> Option<$ty> {
757 if self.x - self.i < self.x {
758 let result = Some(self.x - self.i);
759 self.i = self.i / 2;
760 result
761 } else {
762 None
763 }
764 }
765 }
766 }
767 };
768 }
769
770 macro_rules! unsigned_problem_values {
771 ($t:ty) => {
772 &[<$t>::min_value(), 1, <$t>::max_value()]
773 };
774 }
775
776 macro_rules! unsigned_arbitrary {
777 ($($ty:tt),*) => {
778 $(
779 impl Arbitrary for $ty {
780 fn arbitrary(g: &mut Gen) -> $ty {
781 match g.gen_range(0..10) {
782 0 => {
783 *g.choose(unsigned_problem_values!($ty)).unwrap()
784 },
785 _ => g.gen()
786 }
787 }
788 fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> {
789 unsigned_shrinker!($ty);
790 shrinker::UnsignedShrinker::new(*self)
791 }
792 }
793 )*
794 }
795 }
796
797 unsigned_arbitrary! {
798 usize, u8, u16, u32, u64, u128
799 }
800
801 macro_rules! signed_shrinker {
802 ($ty:ty) => {
803 mod shrinker {
804 pub struct SignedShrinker {
805 x: $ty,
806 i: $ty,
807 }
808
809 impl SignedShrinker {
810 pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
811 if x == 0 {
812 super::empty_shrinker()
813 } else {
814 let shrinker = SignedShrinker { x: x, i: x / 2 };
815 let mut items = vec![0];
816 if shrinker.i < 0 && shrinker.x != <$ty>::MIN {
817 items.push(shrinker.x.abs());
818 }
819 Box::new(items.into_iter().chain(shrinker))
820 }
821 }
822 }
823
824 impl Iterator for SignedShrinker {
825 type Item = $ty;
826 fn next(&mut self) -> Option<$ty> {
827 if self.x == <$ty>::MIN
828 || (self.x - self.i).abs() < self.x.abs()
829 {
830 let result = Some(self.x - self.i);
831 self.i = self.i / 2;
832 result
833 } else {
834 None
835 }
836 }
837 }
838 }
839 };
840 }
841
842 macro_rules! signed_problem_values {
843 ($t:ty) => {
844 &[<$t>::min_value(), 0, <$t>::max_value()]
845 };
846 }
847
848 macro_rules! signed_arbitrary {
849 ($($ty:tt),*) => {
850 $(
851 impl Arbitrary for $ty {
852 fn arbitrary(g: &mut Gen) -> $ty {
853 match g.gen_range(0..10) {
854 0 => {
855 *g.choose(signed_problem_values!($ty)).unwrap()
856 },
857 _ => g.gen()
858 }
859 }
860 fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> {
861 signed_shrinker!($ty);
862 shrinker::SignedShrinker::new(*self)
863 }
864 }
865 )*
866 }
867 }
868
869 signed_arbitrary! {
870 isize, i8, i16, i32, i64, i128
871 }
872
873 macro_rules! float_problem_values {
874 ($path:path) => {{
875 // hack. see: https://github.com/rust-lang/rust/issues/48067
876 use $path as p;
877 &[p::NAN, p::NEG_INFINITY, p::MIN, -0., 0., p::MAX, p::INFINITY]
878 }};
879 }
880
881 macro_rules! float_arbitrary {
882 ($($t:ty, $path:path, $shrinkable:ty),+) => {$(
883 impl Arbitrary for $t {
884 fn arbitrary(g: &mut Gen) -> $t {
885 match g.gen_range(0..10) {
886 0 => *g.choose(float_problem_values!($path)).unwrap(),
887 _ => {
888 use $path as p;
889 let exp = g.gen_range((0.)..p::MAX_EXP as i16 as $t);
890 let mantissa = g.gen_range((1.)..2.);
891 let sign = *g.choose(&[-1., 1.]).unwrap();
892 sign * mantissa * exp.exp2()
893 }
894 }
895 }
896 fn shrink(&self) -> Box<dyn Iterator<Item = $t>> {
897 signed_shrinker!($shrinkable);
898 let it = shrinker::SignedShrinker::new(*self as $shrinkable);
899 Box::new(it.map(|x| x as $t))
900 }
901 }
902 )*};
903 }
904
905 float_arbitrary!(f32, std::f32, i32, f64, std::f64, i64);
906
907 macro_rules! unsigned_non_zero_shrinker {
908 ($ty:tt) => {
909 mod shrinker {
910 pub struct UnsignedNonZeroShrinker {
911 x: $ty,
912 i: $ty,
913 }
914
915 impl UnsignedNonZeroShrinker {
916 pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
917 debug_assert!(x > 0);
918
919 if x == 1 {
920 super::empty_shrinker()
921 } else {
922 Box::new(
923 std::iter::once(1).chain(
924 UnsignedNonZeroShrinker { x: x, i: x / 2 },
925 ),
926 )
927 }
928 }
929 }
930
931 impl Iterator for UnsignedNonZeroShrinker {
932 type Item = $ty;
933
934 fn next(&mut self) -> Option<$ty> {
935 if self.x - self.i < self.x {
936 let result = Some(self.x - self.i);
937 self.i = self.i / 2;
938 result
939 } else {
940 None
941 }
942 }
943 }
944 }
945 };
946 }
947
948 macro_rules! unsigned_non_zero_arbitrary {
949 ($($ty:tt => $inner:tt),*) => {
950 $(
951 impl Arbitrary for $ty {
952 fn arbitrary(g: &mut Gen) -> $ty {
953 let mut v: $inner = g.gen();
954 if v == 0 {
955 v += 1;
956 }
957 $ty::new(v).expect("non-zero value contsturction failed")
958 }
959
960 fn shrink(&self) -> Box<dyn Iterator<Item = $ty>> {
961 unsigned_non_zero_shrinker!($inner);
962 Box::new(shrinker::UnsignedNonZeroShrinker::new(self.get())
963 .map($ty::new)
964 .map(Option::unwrap))
965 }
966 }
967 )*
968 }
969 }
970
971 unsigned_non_zero_arbitrary! {
972 NonZeroUsize => usize,
973 NonZeroU8 => u8,
974 NonZeroU16 => u16,
975 NonZeroU32 => u32,
976 NonZeroU64 => u64,
977 NonZeroU128 => u128
978 }
979
980 impl<T: Arbitrary> Arbitrary for Wrapping<T> {
arbitrary(g: &mut Gen) -> Wrapping<T>981 fn arbitrary(g: &mut Gen) -> Wrapping<T> {
982 Wrapping(T::arbitrary(g))
983 }
shrink(&self) -> Box<dyn Iterator<Item = Wrapping<T>>>984 fn shrink(&self) -> Box<dyn Iterator<Item = Wrapping<T>>> {
985 Box::new(self.0.shrink().map(|inner| Wrapping(inner)))
986 }
987 }
988
989 impl<T: Arbitrary> Arbitrary for Bound<T> {
arbitrary(g: &mut Gen) -> Bound<T>990 fn arbitrary(g: &mut Gen) -> Bound<T> {
991 match g.gen_range(0..3) {
992 0 => Bound::Included(T::arbitrary(g)),
993 1 => Bound::Excluded(T::arbitrary(g)),
994 _ => Bound::Unbounded,
995 }
996 }
shrink(&self) -> Box<dyn Iterator<Item = Bound<T>>>997 fn shrink(&self) -> Box<dyn Iterator<Item = Bound<T>>> {
998 match *self {
999 Bound::Included(ref x) => {
1000 Box::new(x.shrink().map(Bound::Included))
1001 }
1002 Bound::Excluded(ref x) => {
1003 Box::new(x.shrink().map(Bound::Excluded))
1004 }
1005 Bound::Unbounded => empty_shrinker(),
1006 }
1007 }
1008 }
1009
1010 impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for Range<T> {
arbitrary(g: &mut Gen) -> Range<T>1011 fn arbitrary(g: &mut Gen) -> Range<T> {
1012 Arbitrary::arbitrary(g)..Arbitrary::arbitrary(g)
1013 }
shrink(&self) -> Box<dyn Iterator<Item = Range<T>>>1014 fn shrink(&self) -> Box<dyn Iterator<Item = Range<T>>> {
1015 Box::new(
1016 (self.start.clone(), self.end.clone()).shrink().map(|(s, e)| s..e),
1017 )
1018 }
1019 }
1020
1021 impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeInclusive<T> {
arbitrary(g: &mut Gen) -> RangeInclusive<T>1022 fn arbitrary(g: &mut Gen) -> RangeInclusive<T> {
1023 Arbitrary::arbitrary(g)..=Arbitrary::arbitrary(g)
1024 }
shrink(&self) -> Box<dyn Iterator<Item = RangeInclusive<T>>>1025 fn shrink(&self) -> Box<dyn Iterator<Item = RangeInclusive<T>>> {
1026 Box::new(
1027 (self.start().clone(), self.end().clone())
1028 .shrink()
1029 .map(|(s, e)| s..=e),
1030 )
1031 }
1032 }
1033
1034 impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeFrom<T> {
arbitrary(g: &mut Gen) -> RangeFrom<T>1035 fn arbitrary(g: &mut Gen) -> RangeFrom<T> {
1036 Arbitrary::arbitrary(g)..
1037 }
shrink(&self) -> Box<dyn Iterator<Item = RangeFrom<T>>>1038 fn shrink(&self) -> Box<dyn Iterator<Item = RangeFrom<T>>> {
1039 Box::new(self.start.clone().shrink().map(|start| start..))
1040 }
1041 }
1042
1043 impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeTo<T> {
arbitrary(g: &mut Gen) -> RangeTo<T>1044 fn arbitrary(g: &mut Gen) -> RangeTo<T> {
1045 ..Arbitrary::arbitrary(g)
1046 }
shrink(&self) -> Box<dyn Iterator<Item = RangeTo<T>>>1047 fn shrink(&self) -> Box<dyn Iterator<Item = RangeTo<T>>> {
1048 Box::new(self.end.clone().shrink().map(|end| ..end))
1049 }
1050 }
1051
1052 impl<T: Arbitrary + Clone + PartialOrd> Arbitrary for RangeToInclusive<T> {
arbitrary(g: &mut Gen) -> RangeToInclusive<T>1053 fn arbitrary(g: &mut Gen) -> RangeToInclusive<T> {
1054 ..=Arbitrary::arbitrary(g)
1055 }
shrink(&self) -> Box<dyn Iterator<Item = RangeToInclusive<T>>>1056 fn shrink(&self) -> Box<dyn Iterator<Item = RangeToInclusive<T>>> {
1057 Box::new(self.end.clone().shrink().map(|end| ..=end))
1058 }
1059 }
1060
1061 impl Arbitrary for RangeFull {
arbitrary(_: &mut Gen) -> RangeFull1062 fn arbitrary(_: &mut Gen) -> RangeFull {
1063 ..
1064 }
1065 }
1066
1067 impl Arbitrary for Duration {
arbitrary(gen: &mut Gen) -> Self1068 fn arbitrary(gen: &mut Gen) -> Self {
1069 let seconds = gen.gen_range(0..gen.size() as u64);
1070 let nanoseconds = gen.gen_range(0..1_000_000);
1071 Duration::new(seconds, nanoseconds)
1072 }
1073
shrink(&self) -> Box<dyn Iterator<Item = Self>>1074 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
1075 Box::new(
1076 (self.as_secs(), self.subsec_nanos())
1077 .shrink()
1078 .map(|(secs, nanos)| Duration::new(secs, nanos % 1_000_000)),
1079 )
1080 }
1081 }
1082
1083 impl<A: Arbitrary> Arbitrary for Box<A> {
arbitrary(g: &mut Gen) -> Box<A>1084 fn arbitrary(g: &mut Gen) -> Box<A> {
1085 Box::new(A::arbitrary(g))
1086 }
1087
shrink(&self) -> Box<dyn Iterator<Item = Box<A>>>1088 fn shrink(&self) -> Box<dyn Iterator<Item = Box<A>>> {
1089 Box::new((**self).shrink().map(Box::new))
1090 }
1091 }
1092
1093 impl<A: Arbitrary + Sync> Arbitrary for Arc<A> {
arbitrary(g: &mut Gen) -> Arc<A>1094 fn arbitrary(g: &mut Gen) -> Arc<A> {
1095 Arc::new(A::arbitrary(g))
1096 }
1097
shrink(&self) -> Box<dyn Iterator<Item = Arc<A>>>1098 fn shrink(&self) -> Box<dyn Iterator<Item = Arc<A>>> {
1099 Box::new((**self).shrink().map(Arc::new))
1100 }
1101 }
1102
1103 impl Arbitrary for SystemTime {
arbitrary(gen: &mut Gen) -> Self1104 fn arbitrary(gen: &mut Gen) -> Self {
1105 let after_epoch = bool::arbitrary(gen);
1106 let duration = Duration::arbitrary(gen);
1107 if after_epoch {
1108 UNIX_EPOCH + duration
1109 } else {
1110 UNIX_EPOCH - duration
1111 }
1112 }
1113
shrink(&self) -> Box<dyn Iterator<Item = Self>>1114 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
1115 let duration = match self.duration_since(UNIX_EPOCH) {
1116 Ok(duration) => duration,
1117 Err(e) => e.duration(),
1118 };
1119 Box::new(
1120 duration
1121 .shrink()
1122 .flat_map(|d| vec![UNIX_EPOCH + d, UNIX_EPOCH - d]),
1123 )
1124 }
1125 }
1126
1127 #[cfg(test)]
1128 mod test {
1129 use std::collections::{
1130 BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
1131 };
1132 use std::fmt::Debug;
1133 use std::hash::Hash;
1134 use std::num::Wrapping;
1135 use std::path::PathBuf;
1136
1137 use super::{Arbitrary, Gen};
1138
1139 #[test]
arby_unit()1140 fn arby_unit() {
1141 assert_eq!(arby::<()>(), ());
1142 }
1143
1144 macro_rules! arby_int {
1145 ( $signed:expr, $($t:ty),+) => {$(
1146 let mut arbys = (0..1_000_000).map(|_| arby::<$t>());
1147 let mut problems = if $signed {
1148 signed_problem_values!($t).iter()
1149 } else {
1150 unsigned_problem_values!($t).iter()
1151 };
1152 assert!(problems.all(|p| arbys.any(|arby| arby == *p)),
1153 "Arbitrary does not generate all problematic values");
1154 let max = <$t>::max_value();
1155 let mid = (max + <$t>::min_value()) / 2;
1156 // split full range of $t into chunks
1157 // Arbitrary must return some value in each chunk
1158 let double_chunks: $t = 9;
1159 let chunks = double_chunks * 2; // chunks must be even
1160 let lim: Box<dyn Iterator<Item=$t>> = if $signed {
1161 Box::new((0..=chunks)
1162 .map(|idx| idx - chunks / 2)
1163 .map(|x| mid + max / (chunks / 2) * x))
1164 } else {
1165 Box::new((0..=chunks).map(|idx| max / chunks * idx))
1166 };
1167 let mut lim = lim.peekable();
1168 while let (Some(low), Some(&high)) = (lim.next(), lim.peek()) {
1169 assert!(arbys.any(|arby| low <= arby && arby <= high),
1170 "Arbitrary doesn't generate numbers in {}..={}", low, high)
1171 }
1172 )*};
1173 }
1174
1175 #[test]
arby_int()1176 fn arby_int() {
1177 arby_int!(true, i8, i16, i32, i64, isize, i128);
1178 }
1179
1180 #[test]
arby_uint()1181 fn arby_uint() {
1182 arby_int!(false, u8, u16, u32, u64, usize, u128);
1183 }
1184
1185 macro_rules! arby_float {
1186 ($($t:ty, $path:path),+) => {$({
1187 use $path as p;
1188 let mut arbys = (0..1_000_000).map(|_| arby::<$t>());
1189 //NaN != NaN
1190 assert!(arbys.any(|f| f.is_nan()),
1191 "Arbitrary does not generate the problematic value NaN"
1192 );
1193 for p in float_problem_values!($path).iter().filter(|f| !f.is_nan()) {
1194 assert!(arbys.any(|arby| arby == *p),
1195 "Arbitrary does not generate the problematic value {}",
1196 p
1197 );
1198 }
1199 // split full range of $t into chunks
1200 // Arbitrary must return some value in each chunk
1201 let double_chunks: i8 = 9;
1202 let chunks = double_chunks * 2; // chunks must be even
1203 let lim = (-double_chunks..=double_chunks)
1204 .map(|idx| <$t>::from(idx))
1205 .map(|idx| p::MAX/(<$t>::from(chunks/2)) * idx);
1206 let mut lim = lim.peekable();
1207 while let (Some(low), Some(&high)) = (lim.next(), lim.peek()) {
1208 assert!(
1209 arbys.any(|arby| low <= arby && arby <= high),
1210 "Arbitrary doesn't generate numbers in {:e}..={:e}",
1211 low,
1212 high,
1213 )
1214 }
1215 })*};
1216 }
1217
1218 #[test]
arby_float()1219 fn arby_float() {
1220 arby_float!(f32, std::f32, f64, std::f64);
1221 }
1222
arby<A: Arbitrary>() -> A1223 fn arby<A: Arbitrary>() -> A {
1224 Arbitrary::arbitrary(&mut Gen::new(5))
1225 }
1226
1227 // Shrink testing.
1228 #[test]
unit()1229 fn unit() {
1230 eq((), vec![]);
1231 }
1232
1233 #[test]
bools()1234 fn bools() {
1235 eq(false, vec![]);
1236 eq(true, vec![false]);
1237 }
1238
1239 #[test]
options()1240 fn options() {
1241 eq(None::<()>, vec![]);
1242 eq(Some(false), vec![None]);
1243 eq(Some(true), vec![None, Some(false)]);
1244 }
1245
1246 #[test]
results()1247 fn results() {
1248 // Result<A, B> doesn't implement the Hash trait, so these tests
1249 // depends on the order of shrunk results. Ug.
1250 // TODO: Fix this.
1251 ordered_eq(Ok::<bool, ()>(true), vec![Ok(false)]);
1252 ordered_eq(Err::<(), bool>(true), vec![Err(false)]);
1253 }
1254
1255 #[test]
tuples()1256 fn tuples() {
1257 eq((false, false), vec![]);
1258 eq((true, false), vec![(false, false)]);
1259 eq((true, true), vec![(false, true), (true, false)]);
1260 }
1261
1262 #[test]
triples()1263 fn triples() {
1264 eq((false, false, false), vec![]);
1265 eq((true, false, false), vec![(false, false, false)]);
1266 eq(
1267 (true, true, false),
1268 vec![(false, true, false), (true, false, false)],
1269 );
1270 }
1271
1272 #[test]
quads()1273 fn quads() {
1274 eq((false, false, false, false), vec![]);
1275 eq((true, false, false, false), vec![(false, false, false, false)]);
1276 eq(
1277 (true, true, false, false),
1278 vec![(false, true, false, false), (true, false, false, false)],
1279 );
1280 }
1281
1282 #[test]
ints()1283 fn ints() {
1284 // TODO: Test overflow?
1285 eq(5isize, vec![0, 3, 4]);
1286 eq(-5isize, vec![5, 0, -3, -4]);
1287 eq(0isize, vec![]);
1288 }
1289
1290 #[test]
ints8()1291 fn ints8() {
1292 eq(5i8, vec![0, 3, 4]);
1293 eq(-5i8, vec![5, 0, -3, -4]);
1294 eq(0i8, vec![]);
1295 }
1296
1297 #[test]
ints16()1298 fn ints16() {
1299 eq(5i16, vec![0, 3, 4]);
1300 eq(-5i16, vec![5, 0, -3, -4]);
1301 eq(0i16, vec![]);
1302 }
1303
1304 #[test]
ints32()1305 fn ints32() {
1306 eq(5i32, vec![0, 3, 4]);
1307 eq(-5i32, vec![5, 0, -3, -4]);
1308 eq(0i32, vec![]);
1309 }
1310
1311 #[test]
ints64()1312 fn ints64() {
1313 eq(5i64, vec![0, 3, 4]);
1314 eq(-5i64, vec![5, 0, -3, -4]);
1315 eq(0i64, vec![]);
1316 }
1317
1318 #[test]
ints128()1319 fn ints128() {
1320 eq(5i128, vec![0, 3, 4]);
1321 eq(-5i128, vec![5, 0, -3, -4]);
1322 eq(0i128, vec![]);
1323 }
1324
1325 #[test]
uints()1326 fn uints() {
1327 eq(5usize, vec![0, 3, 4]);
1328 eq(0usize, vec![]);
1329 }
1330
1331 #[test]
uints8()1332 fn uints8() {
1333 eq(5u8, vec![0, 3, 4]);
1334 eq(0u8, vec![]);
1335 }
1336
1337 #[test]
uints16()1338 fn uints16() {
1339 eq(5u16, vec![0, 3, 4]);
1340 eq(0u16, vec![]);
1341 }
1342
1343 #[test]
uints32()1344 fn uints32() {
1345 eq(5u32, vec![0, 3, 4]);
1346 eq(0u32, vec![]);
1347 }
1348
1349 #[test]
uints64()1350 fn uints64() {
1351 eq(5u64, vec![0, 3, 4]);
1352 eq(0u64, vec![]);
1353 }
1354
1355 #[test]
uints128()1356 fn uints128() {
1357 eq(5u128, vec![0, 3, 4]);
1358 eq(0u128, vec![]);
1359 }
1360
1361 macro_rules! define_float_eq {
1362 ($ty:ty) => {
1363 fn eq(s: $ty, v: Vec<$ty>) {
1364 let shrunk: Vec<$ty> = s.shrink().collect();
1365 for n in v {
1366 let found = shrunk.iter().any(|&i| i == n);
1367 if !found {
1368 panic!(format!(
1369 "Element {:?} was not found \
1370 in shrink results {:?}",
1371 n, shrunk
1372 ));
1373 }
1374 }
1375 }
1376 };
1377 }
1378
1379 #[test]
floats32()1380 fn floats32() {
1381 define_float_eq!(f32);
1382
1383 eq(0.0, vec![]);
1384 eq(-0.0, vec![]);
1385 eq(1.0, vec![0.0]);
1386 eq(2.0, vec![0.0, 1.0]);
1387 eq(-2.0, vec![0.0, 2.0, -1.0]);
1388 eq(1.5, vec![0.0]);
1389 }
1390
1391 #[test]
floats64()1392 fn floats64() {
1393 define_float_eq!(f64);
1394
1395 eq(0.0, vec![]);
1396 eq(-0.0, vec![]);
1397 eq(1.0, vec![0.0]);
1398 eq(2.0, vec![0.0, 1.0]);
1399 eq(-2.0, vec![0.0, 2.0, -1.0]);
1400 eq(1.5, vec![0.0]);
1401 }
1402
1403 #[test]
wrapping_ints32()1404 fn wrapping_ints32() {
1405 eq(Wrapping(5i32), vec![Wrapping(0), Wrapping(3), Wrapping(4)]);
1406 eq(
1407 Wrapping(-5i32),
1408 vec![Wrapping(5), Wrapping(0), Wrapping(-3), Wrapping(-4)],
1409 );
1410 eq(Wrapping(0i32), vec![]);
1411 }
1412
1413 #[test]
vecs()1414 fn vecs() {
1415 eq(
1416 {
1417 let it: Vec<isize> = vec![];
1418 it
1419 },
1420 vec![],
1421 );
1422 eq(
1423 {
1424 let it: Vec<Vec<isize>> = vec![vec![]];
1425 it
1426 },
1427 vec![vec![]],
1428 );
1429 eq(vec![1isize], vec![vec![], vec![0]]);
1430 eq(vec![11isize], vec![vec![], vec![0], vec![6], vec![9], vec![10]]);
1431 eq(
1432 vec![3isize, 5],
1433 vec![
1434 vec![],
1435 vec![5],
1436 vec![3],
1437 vec![0, 5],
1438 vec![2, 5],
1439 vec![3, 0],
1440 vec![3, 3],
1441 vec![3, 4],
1442 ],
1443 );
1444 }
1445
1446 macro_rules! map_tests {
1447 ($name:ident, $ctor:expr) => {
1448 #[test]
1449 fn $name() {
1450 ordered_eq($ctor, vec![]);
1451
1452 {
1453 let mut map = $ctor;
1454 map.insert(1usize, 1isize);
1455
1456 let shrinks = vec![
1457 $ctor,
1458 {
1459 let mut m = $ctor;
1460 m.insert(0, 1);
1461 m
1462 },
1463 {
1464 let mut m = $ctor;
1465 m.insert(1, 0);
1466 m
1467 },
1468 ];
1469
1470 ordered_eq(map, shrinks);
1471 }
1472 }
1473 };
1474 }
1475
1476 map_tests!(btreemap, BTreeMap::<usize, isize>::new());
1477 map_tests!(hashmap, HashMap::<usize, isize>::new());
1478
1479 macro_rules! list_tests {
1480 ($name:ident, $ctor:expr, $push:ident) => {
1481 #[test]
1482 fn $name() {
1483 ordered_eq($ctor, vec![]);
1484
1485 {
1486 let mut list = $ctor;
1487 list.$push(2usize);
1488
1489 let shrinks = vec![
1490 $ctor,
1491 {
1492 let mut m = $ctor;
1493 m.$push(0);
1494 m
1495 },
1496 {
1497 let mut m = $ctor;
1498 m.$push(1);
1499 m
1500 },
1501 ];
1502
1503 ordered_eq(list, shrinks);
1504 }
1505 }
1506 };
1507 }
1508
1509 list_tests!(btreesets, BTreeSet::<usize>::new(), insert);
1510 list_tests!(hashsets, HashSet::<usize>::new(), insert);
1511 list_tests!(linkedlists, LinkedList::<usize>::new(), push_back);
1512 list_tests!(vecdeques, VecDeque::<usize>::new(), push_back);
1513
1514 #[test]
binaryheaps()1515 fn binaryheaps() {
1516 ordered_eq(
1517 BinaryHeap::<usize>::new().into_iter().collect::<Vec<_>>(),
1518 vec![],
1519 );
1520
1521 {
1522 let mut heap = BinaryHeap::<usize>::new();
1523 heap.push(2usize);
1524
1525 let shrinks = vec![vec![], vec![0], vec![1]];
1526
1527 ordered_eq(heap.into_iter().collect::<Vec<_>>(), shrinks);
1528 }
1529 }
1530
1531 #[test]
chars()1532 fn chars() {
1533 eq('\x00', vec![]);
1534 }
1535
1536 // All this jazz is for testing set equality on the results of a shrinker.
eq<A: Arbitrary + Eq + Debug + Hash>(s: A, v: Vec<A>)1537 fn eq<A: Arbitrary + Eq + Debug + Hash>(s: A, v: Vec<A>) {
1538 let (left, right) = (shrunk(s), set(v));
1539 assert_eq!(left, right);
1540 }
shrunk<A: Arbitrary + Eq + Hash>(s: A) -> HashSet<A>1541 fn shrunk<A: Arbitrary + Eq + Hash>(s: A) -> HashSet<A> {
1542 set(s.shrink())
1543 }
set<A: Hash + Eq, I: IntoIterator<Item = A>>(xs: I) -> HashSet<A>1544 fn set<A: Hash + Eq, I: IntoIterator<Item = A>>(xs: I) -> HashSet<A> {
1545 xs.into_iter().collect()
1546 }
1547
ordered_eq<A: Arbitrary + Eq + Debug>(s: A, v: Vec<A>)1548 fn ordered_eq<A: Arbitrary + Eq + Debug>(s: A, v: Vec<A>) {
1549 let (left, right) = (s.shrink().collect::<Vec<A>>(), v);
1550 assert_eq!(left, right);
1551 }
1552
1553 #[test]
bounds()1554 fn bounds() {
1555 use std::ops::Bound::*;
1556 for i in -5..=5 {
1557 ordered_eq(Included(i), i.shrink().map(Included).collect());
1558 ordered_eq(Excluded(i), i.shrink().map(Excluded).collect());
1559 }
1560 eq(Unbounded::<i32>, vec![]);
1561 }
1562
1563 #[test]
ranges()1564 fn ranges() {
1565 ordered_eq(0..0, vec![]);
1566 ordered_eq(1..1, vec![0..1, 1..0]);
1567 ordered_eq(3..5, vec![0..5, 2..5, 3..0, 3..3, 3..4]);
1568 ordered_eq(5..3, vec![0..3, 3..3, 4..3, 5..0, 5..2]);
1569 ordered_eq(3.., vec![0.., 2..]);
1570 ordered_eq(..3, vec![..0, ..2]);
1571 ordered_eq(.., vec![]);
1572 ordered_eq(3..=5, vec![0..=5, 2..=5, 3..=0, 3..=3, 3..=4]);
1573 ordered_eq(..=3, vec![..=0, ..=2]);
1574 }
1575
1576 #[test]
pathbuf()1577 fn pathbuf() {
1578 ordered_eq(
1579 PathBuf::from("/home/foo//.././bar"),
1580 vec![
1581 PathBuf::from("/home/foo//.."),
1582 PathBuf::from("/home/foo/../bar"),
1583 ],
1584 );
1585 }
1586 }
1587