-
Notifications
You must be signed in to change notification settings - Fork 149
/
arbitrary.rs
1586 lines (1429 loc) · 46.3 KB
/
arbitrary.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::char;
use std::collections::{
BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
};
use std::env;
use std::ffi::{CString, OsString};
use std::hash::{BuildHasher, Hash};
use std::iter::{empty, once};
use std::net::{
IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6,
};
use std::num::Wrapping;
use std::num::{
NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
};
use std::ops::{
Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
RangeToInclusive,
};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use rand::seq::SliceRandom;
use rand::{self, Rng, SeedableRng};
/// Gen represents a PRNG.
///
/// It is the source of randomness from which QuickCheck will generate
/// values. An instance of `Gen` is passed to every invocation of
/// `Arbitrary::arbitrary`, which permits callers to use lower level RNG
/// routines to generate values.
///
/// It is unspecified whether this is a secure RNG or not. Therefore, callers
/// should assume it is insecure.
pub struct Gen {
rng: rand::rngs::SmallRng,
size: usize,
}
impl Gen {
/// Returns a `Gen` with the given size configuration.
///
/// The `size` parameter controls the size of random values generated.
/// For example, it specifies the maximum length of a randomly generated
/// vector, but is and should not be used to control the range of a
/// randomly generated number. (Unless that number is used to control the
/// size of a data structure.)
pub fn new(size: usize) -> Gen {
Gen { rng: rand::rngs::SmallRng::from_entropy(), size: size }
}
/// Returns the size configured with this generator.
pub fn size(&self) -> usize {
self.size
}
/// Choose among the possible alternatives in the slice given. If the slice
/// is empty, then `None` is returned. Otherwise, a non-`None` value is
/// guaranteed to be returned.
pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
slice.choose(&mut self.rng)
}
fn gen<T>(&mut self) -> T
where
rand::distributions::Standard: rand::distributions::Distribution<T>,
{
self.rng.gen()
}
fn gen_range<T, R>(&mut self, range: R) -> T
where
T: rand::distributions::uniform::SampleUniform,
R: rand::distributions::uniform::SampleRange<T>,
{
self.rng.gen_range(range)
}
}
/// Creates a shrinker with zero elements.
pub fn empty_shrinker<A: 'static>() -> Box<dyn Iterator<Item = A>> {
Box::new(empty())
}
/// Creates a shrinker with a single element.
pub fn single_shrinker<A: 'static>(value: A) -> Box<dyn Iterator<Item = A>> {
Box::new(once(value))
}
/// `Arbitrary` describes types whose values can be randomly generated and
/// shrunk.
///
/// Aside from shrinking, `Arbitrary` is different from typical RNGs in that
/// it respects `Gen::size()` for controlling how much memory a particular
/// value uses, for practical purposes. For example, `Vec::arbitrary()`
/// respects `Gen::size()` to decide the maximum `len()` of the vector.
/// This behavior is necessary due to practical speed and size limitations.
/// Conversely, `i32::arbitrary()` ignores `size()` since all `i32` values
/// require `O(1)` memory and operations between `i32`s require `O(1)` time
/// (with the exception of exponentiation).
///
/// Additionally, all types that implement `Arbitrary` must also implement
/// `Clone`.
pub trait Arbitrary: Clone + 'static {
/// Return an arbitrary value.
///
/// Implementations should respect `Gen::size()` when decisions about how
/// big a particular value should be. Implementations should generally
/// defer to other `Arbitrary` implementations to generate other random
/// values when necessary. The `Gen` type also offers a few RNG helper
/// routines.
fn arbitrary(g: &mut Gen) -> Self;
/// Return an iterator of values that are smaller than itself.
///
/// The way in which a value is "smaller" is implementation defined. In
/// some cases, the interpretation is obvious: shrinking an integer should
/// produce integers smaller than itself. Others are more complex, for
/// example, shrinking a `Vec` should both shrink its size and shrink its
/// component values.
///
/// The iterator returned should be bounded to some reasonable size.
///
/// It is always correct to return an empty iterator, and indeed, this
/// is the default implementation. The downside of this approach is that
/// witnesses to failures in properties will be more inscrutable.
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
empty_shrinker()
}
}
impl Arbitrary for () {
fn arbitrary(_: &mut Gen) -> () {
()
}
}
impl Arbitrary for bool {
fn arbitrary(g: &mut Gen) -> bool {
g.gen()
}
fn shrink(&self) -> Box<dyn Iterator<Item = bool>> {
if *self {
single_shrinker(false)
} else {
empty_shrinker()
}
}
}
impl<A: Arbitrary> Arbitrary for Option<A> {
fn arbitrary(g: &mut Gen) -> Option<A> {
if g.gen() {
None
} else {
Some(Arbitrary::arbitrary(g))
}
}
fn shrink(&self) -> Box<dyn Iterator<Item = Option<A>>> {
match *self {
None => empty_shrinker(),
Some(ref x) => {
let chain = single_shrinker(None).chain(x.shrink().map(Some));
Box::new(chain)
}
}
}
}
impl<A: Arbitrary, B: Arbitrary> Arbitrary for Result<A, B> {
fn arbitrary(g: &mut Gen) -> Result<A, B> {
if g.gen() {
Ok(Arbitrary::arbitrary(g))
} else {
Err(Arbitrary::arbitrary(g))
}
}
fn shrink(&self) -> Box<dyn Iterator<Item = Result<A, B>>> {
match *self {
Ok(ref x) => {
let xs = x.shrink();
let tagged = xs.map(Ok);
Box::new(tagged)
}
Err(ref x) => {
let xs = x.shrink();
let tagged = xs.map(Err);
Box::new(tagged)
}
}
}
}
macro_rules! impl_arb_for_single_tuple {
($(($type_param:ident, $tuple_index:tt),)*) => {
impl<$($type_param),*> Arbitrary for ($($type_param,)*)
where $($type_param: Arbitrary,)*
{
fn arbitrary(g: &mut Gen) -> ($($type_param,)*) {
(
$(
$type_param::arbitrary(g),
)*
)
}
fn shrink(&self) -> Box<dyn Iterator<Item=($($type_param,)*)>> {
let iter = ::std::iter::empty();
$(
let cloned = self.clone();
let iter = iter.chain(
self.$tuple_index.shrink().map(move |shr_value| {
let mut result = cloned.clone();
result.$tuple_index = shr_value;
result
})
);
)*
Box::new(iter)
}
}
};
}
macro_rules! impl_arb_for_tuples {
(@internal [$($acc:tt,)*]) => { };
(@internal [$($acc:tt,)*] ($type_param:ident, $tuple_index:tt), $($rest:tt,)*) => {
impl_arb_for_single_tuple!($($acc,)* ($type_param, $tuple_index),);
impl_arb_for_tuples!(@internal [$($acc,)* ($type_param, $tuple_index),] $($rest,)*);
};
($(($type_param:ident, $tuple_index:tt),)*) => {
impl_arb_for_tuples!(@internal [] $(($type_param, $tuple_index),)*);
};
}
impl_arb_for_tuples! {
(A, 0),
(B, 1),
(C, 2),
(D, 3),
(E, 4),
(F, 5),
(G, 6),
(H, 7),
}
impl<A: Arbitrary> Arbitrary for Vec<A> {
fn arbitrary(g: &mut Gen) -> Vec<A> {
let size = {
let s = g.size();
g.gen_range(0..s)
};
(0..size).map(|_| A::arbitrary(g)).collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = Vec<A>>> {
VecShrinker::new(self.clone())
}
}
///Iterator which returns successive attempts to shrink the vector `seed`
struct VecShrinker<A> {
seed: Vec<A>,
/// How much which is removed when trying with smaller vectors
size: usize,
/// The end of the removed elements
offset: usize,
/// The shrinker for the element at `offset` once shrinking of individual
/// elements are attempted
element_shrinker: Box<dyn Iterator<Item = A>>,
}
impl<A: Arbitrary> VecShrinker<A> {
fn new(seed: Vec<A>) -> Box<dyn Iterator<Item = Vec<A>>> {
let es = match seed.get(0) {
Some(e) => e.shrink(),
None => return empty_shrinker(),
};
let size = seed.len();
Box::new(VecShrinker {
seed: seed,
size: size,
offset: size,
element_shrinker: es,
})
}
/// Returns the next shrunk element if any, `offset` points to the index
/// after the returned element after the function returns
fn next_element(&mut self) -> Option<A> {
loop {
match self.element_shrinker.next() {
Some(e) => return Some(e),
None => match self.seed.get(self.offset) {
Some(e) => {
self.element_shrinker = e.shrink();
self.offset += 1;
}
None => return None,
},
}
}
}
}
impl<A> Iterator for VecShrinker<A>
where
A: Arbitrary,
{
type Item = Vec<A>;
fn next(&mut self) -> Option<Vec<A>> {
// Try with an empty vector first
if self.size == self.seed.len() {
self.size /= 2;
self.offset = self.size;
return Some(vec![]);
}
if self.size != 0 {
// Generate a smaller vector by removing the elements between
// (offset - size) and offset
let xs1 = self.seed[..(self.offset - self.size)]
.iter()
.chain(&self.seed[self.offset..])
.cloned()
.collect();
self.offset += self.size;
// Try to reduce the amount removed from the vector once all
// previous sizes tried
if self.offset > self.seed.len() {
self.size /= 2;
self.offset = self.size;
}
Some(xs1)
} else {
// A smaller vector did not work so try to shrink each element of
// the vector instead Reuse `offset` as the index determining which
// element to shrink
// The first element shrinker is already created so skip the first
// offset (self.offset == 0 only on first entry to this part of the
// iterator)
if self.offset == 0 {
self.offset = 1
}
match self.next_element() {
Some(e) => Some(
self.seed[..self.offset - 1]
.iter()
.cloned()
.chain(Some(e).into_iter())
.chain(self.seed[self.offset..].iter().cloned())
.collect(),
),
None => None,
}
}
}
}
impl<K: Arbitrary + Ord, V: Arbitrary> Arbitrary for BTreeMap<K, V> {
fn arbitrary(g: &mut Gen) -> BTreeMap<K, V> {
let vec: Vec<(K, V)> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = BTreeMap<K, V>>> {
let vec: Vec<(K, V)> = self.clone().into_iter().collect();
Box::new(
vec.shrink().map(|v| v.into_iter().collect::<BTreeMap<K, V>>()),
)
}
}
impl<
K: Arbitrary + Eq + Hash,
V: Arbitrary,
S: BuildHasher + Default + Clone + 'static,
> Arbitrary for HashMap<K, V, S>
{
fn arbitrary(g: &mut Gen) -> Self {
let vec: Vec<(K, V)> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let vec: Vec<(K, V)> = self.clone().into_iter().collect();
Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>()))
}
}
impl<T: Arbitrary + Ord> Arbitrary for BTreeSet<T> {
fn arbitrary(g: &mut Gen) -> BTreeSet<T> {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = BTreeSet<T>>> {
let vec: Vec<T> = self.clone().into_iter().collect();
Box::new(vec.shrink().map(|v| v.into_iter().collect::<BTreeSet<T>>()))
}
}
impl<T: Arbitrary + Ord> Arbitrary for BinaryHeap<T> {
fn arbitrary(g: &mut Gen) -> BinaryHeap<T> {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = BinaryHeap<T>>> {
let vec: Vec<T> = self.clone().into_iter().collect();
Box::new(
vec.shrink().map(|v| v.into_iter().collect::<BinaryHeap<T>>()),
)
}
}
impl<T: Arbitrary + Eq + Hash, S: BuildHasher + Default + Clone + 'static>
Arbitrary for HashSet<T, S>
{
fn arbitrary(g: &mut Gen) -> Self {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let vec: Vec<T> = self.clone().into_iter().collect();
Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>()))
}
}
impl<T: Arbitrary> Arbitrary for LinkedList<T> {
fn arbitrary(g: &mut Gen) -> LinkedList<T> {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = LinkedList<T>>> {
let vec: Vec<T> = self.clone().into_iter().collect();
Box::new(
vec.shrink().map(|v| v.into_iter().collect::<LinkedList<T>>()),
)
}
}
impl<T: Arbitrary> Arbitrary for VecDeque<T> {
fn arbitrary(g: &mut Gen) -> VecDeque<T> {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = VecDeque<T>>> {
let vec: Vec<T> = self.clone().into_iter().collect();
Box::new(vec.shrink().map(|v| v.into_iter().collect::<VecDeque<T>>()))
}
}
impl Arbitrary for IpAddr {
fn arbitrary(g: &mut Gen) -> IpAddr {
let ipv4: bool = g.gen();
if ipv4 {
IpAddr::V4(Arbitrary::arbitrary(g))
} else {
IpAddr::V6(Arbitrary::arbitrary(g))
}
}
}
impl Arbitrary for Ipv4Addr {
fn arbitrary(g: &mut Gen) -> Ipv4Addr {
Ipv4Addr::new(g.gen(), g.gen(), g.gen(), g.gen())
}
}
impl Arbitrary for Ipv6Addr {
fn arbitrary(g: &mut Gen) -> Ipv6Addr {
Ipv6Addr::new(
g.gen(),
g.gen(),
g.gen(),
g.gen(),
g.gen(),
g.gen(),
g.gen(),
g.gen(),
)
}
}
impl Arbitrary for SocketAddr {
fn arbitrary(g: &mut Gen) -> SocketAddr {
SocketAddr::new(Arbitrary::arbitrary(g), g.gen())
}
}
impl Arbitrary for SocketAddrV4 {
fn arbitrary(g: &mut Gen) -> SocketAddrV4 {
SocketAddrV4::new(Arbitrary::arbitrary(g), g.gen())
}
}
impl Arbitrary for SocketAddrV6 {
fn arbitrary(g: &mut Gen) -> SocketAddrV6 {
SocketAddrV6::new(Arbitrary::arbitrary(g), g.gen(), g.gen(), g.gen())
}
}
impl Arbitrary for PathBuf {
fn arbitrary(g: &mut Gen) -> PathBuf {
// use some real directories as guesses, so we may end up with
// actual working directories in case that is relevant.
let here =
env::current_dir().unwrap_or(PathBuf::from("/test/directory"));
let temp = env::temp_dir();
#[allow(deprecated)]
let home = env::home_dir().unwrap_or(PathBuf::from("/home/user"));
let mut p = g
.choose(&[
here,
temp,
home,
PathBuf::from("."),
PathBuf::from(".."),
PathBuf::from("../../.."),
PathBuf::new(),
])
.unwrap()
.to_owned();
p.extend(Vec::<OsString>::arbitrary(g).iter());
p
}
fn shrink(&self) -> Box<dyn Iterator<Item = PathBuf>> {
let mut shrunk = vec![];
let mut popped = self.clone();
if popped.pop() {
shrunk.push(popped);
}
// Iterating over a Path performs a small amount of normalization.
let normalized = self.iter().collect::<PathBuf>();
if normalized.as_os_str() != self.as_os_str() {
shrunk.push(normalized);
}
// Add the canonicalized variant only if canonicalizing the path
// actually does something, making it (hopefully) smaller. Also, ignore
// canonicalization if canonicalization errors.
if let Ok(canonicalized) = self.canonicalize() {
if canonicalized.as_os_str() != self.as_os_str() {
shrunk.push(canonicalized);
}
}
Box::new(shrunk.into_iter())
}
}
impl Arbitrary for OsString {
fn arbitrary(g: &mut Gen) -> OsString {
OsString::from(String::arbitrary(g))
}
fn shrink(&self) -> Box<dyn Iterator<Item = OsString>> {
let mystring: String = self.clone().into_string().unwrap();
Box::new(mystring.shrink().map(|s| OsString::from(s)))
}
}
impl Arbitrary for String {
fn arbitrary(g: &mut Gen) -> String {
let size = {
let s = g.size();
g.gen_range(0..s)
};
(0..size).map(|_| char::arbitrary(g)).collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = String>> {
// Shrink a string by shrinking a vector of its characters.
let chars: Vec<char> = self.chars().collect();
Box::new(chars.shrink().map(|x| x.into_iter().collect::<String>()))
}
}
impl Arbitrary for CString {
fn arbitrary(g: &mut Gen) -> Self {
let size = {
let s = g.size();
g.gen_range(0..s)
};
// Use either random bytes or random UTF-8 encoded codepoints.
let utf8: bool = g.gen();
if utf8 {
CString::new(
(0..)
.map(|_| char::arbitrary(g))
.filter(|&c| c != '\0')
.take(size)
.collect::<String>(),
)
} else {
CString::new(
(0..)
.map(|_| u8::arbitrary(g))
.filter(|&c| c != b'\0')
.take(size)
.collect::<Vec<u8>>(),
)
}
.expect("null characters should have been filtered out")
}
fn shrink(&self) -> Box<dyn Iterator<Item = CString>> {
// Use the implementation for a vec here, but make sure null characters
// are filtered out.
Box::new(VecShrinker::new(self.as_bytes().to_vec()).map(|bytes| {
CString::new(
bytes.into_iter().filter(|&c| c != 0).collect::<Vec<u8>>(),
)
.expect("null characters should have been filtered out")
}))
}
}
impl Arbitrary for char {
fn arbitrary(g: &mut Gen) -> char {
let mode = g.gen_range(0..100);
match mode {
0..=49 => {
// ASCII + some control characters
g.gen_range(0..0xB0) as u8 as char
}
50..=59 => {
// Unicode BMP characters
loop {
if let Some(x) = char::from_u32(g.gen_range(0..0x10000)) {
return x;
}
// ignore surrogate pairs
}
}
60..=84 => {
// Characters often used in programming languages
g.choose(&[
' ', ' ', ' ', '\t', '\n', '~', '`', '!', '@', '#', '$',
'%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '[',
']', '{', '}', ':', ';', '\'', '"', '\\', '|', ',', '<',
'>', '.', '/', '?', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9',
])
.unwrap()
.to_owned()
}
85..=89 => {
// Tricky Unicode, part 1
g.choose(&[
'\u{0149}', // a deprecated character
'\u{fff0}', // some of "Other, format" category:
'\u{fff1}',
'\u{fff2}',
'\u{fff3}',
'\u{fff4}',
'\u{fff5}',
'\u{fff6}',
'\u{fff7}',
'\u{fff8}',
'\u{fff9}',
'\u{fffA}',
'\u{fffB}',
'\u{fffC}',
'\u{fffD}',
'\u{fffE}',
'\u{fffF}',
'\u{0600}',
'\u{0601}',
'\u{0602}',
'\u{0603}',
'\u{0604}',
'\u{0605}',
'\u{061C}',
'\u{06DD}',
'\u{070F}',
'\u{180E}',
'\u{110BD}',
'\u{1D173}',
'\u{e0001}', // tag
'\u{e0020}', // tag space
'\u{e000}',
'\u{e001}',
'\u{ef8ff}', // private use
'\u{f0000}',
'\u{ffffd}',
'\u{ffffe}',
'\u{fffff}',
'\u{100000}',
'\u{10FFFD}',
'\u{10FFFE}',
'\u{10FFFF}',
// "Other, surrogate" characters are so that very special
// that they are not even allowed in safe Rust,
//so omitted here
'\u{3000}', // ideographic space
'\u{1680}',
// other space characters are already covered by two next
// branches
])
.unwrap()
.to_owned()
}
90..=94 => {
// Tricky unicode, part 2
char::from_u32(g.gen_range(0x2000..0x2070)).unwrap()
}
95..=99 => {
// Completely arbitrary characters
g.gen()
}
_ => unreachable!(),
}
}
fn shrink(&self) -> Box<dyn Iterator<Item = char>> {
Box::new((*self as u32).shrink().filter_map(char::from_u32))
}
}
macro_rules! unsigned_shrinker {
($ty:ty) => {
mod shrinker {
pub struct UnsignedShrinker {
x: $ty,
i: $ty,
}
impl UnsignedShrinker {
pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
if x == 0 {
super::empty_shrinker()
} else {
Box::new(
vec![0]
.into_iter()
.chain(UnsignedShrinker { x: x, i: x / 2 }),
)
}
}
}
impl Iterator for UnsignedShrinker {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
if self.x - self.i < self.x {
let result = Some(self.x - self.i);
self.i = self.i / 2;
result
} else {
None
}
}
}
}
};
}
macro_rules! unsigned_problem_values {
($t:ty) => {
&[<$t>::min_value(), 1, <$t>::max_value()]
};
}
macro_rules! unsigned_arbitrary {
($($ty:tt),*) => {
$(
impl Arbitrary for $ty {
fn arbitrary(g: &mut Gen) -> $ty {
match g.gen_range(0..10) {
0 => {
*g.choose(unsigned_problem_values!($ty)).unwrap()
},
_ => g.gen()
}
}
fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> {
unsigned_shrinker!($ty);
shrinker::UnsignedShrinker::new(*self)
}
}
)*
}
}
unsigned_arbitrary! {
usize, u8, u16, u32, u64, u128
}
macro_rules! signed_shrinker {
($ty:ty) => {
mod shrinker {
pub struct SignedShrinker {
x: $ty,
i: $ty,
}
impl SignedShrinker {
pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
if x == 0 {
super::empty_shrinker()
} else {
let shrinker = SignedShrinker { x: x, i: x / 2 };
let mut items = vec![0];
if shrinker.i < 0 && shrinker.x != <$ty>::MIN {
items.push(shrinker.x.abs());
}
Box::new(items.into_iter().chain(shrinker))
}
}
}
impl Iterator for SignedShrinker {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
if self.x == <$ty>::MIN
|| (self.x - self.i).abs() < self.x.abs()
{
let result = Some(self.x - self.i);
self.i = self.i / 2;
result
} else {
None
}
}
}
}
};
}
macro_rules! signed_problem_values {
($t:ty) => {
&[<$t>::min_value(), 0, <$t>::max_value()]
};
}
macro_rules! signed_arbitrary {
($($ty:tt),*) => {
$(
impl Arbitrary for $ty {
fn arbitrary(g: &mut Gen) -> $ty {
match g.gen_range(0..10) {
0 => {
*g.choose(signed_problem_values!($ty)).unwrap()
},
_ => g.gen()
}
}
fn shrink(&self) -> Box<dyn Iterator<Item=$ty>> {
signed_shrinker!($ty);
shrinker::SignedShrinker::new(*self)
}
}
)*
}
}
signed_arbitrary! {
isize, i8, i16, i32, i64, i128
}
macro_rules! float_problem_values {
($path:path) => {{
// hack. see: https://github.com/rust-lang/rust/issues/48067
use $path as p;
&[p::NAN, p::NEG_INFINITY, p::MIN, -0., 0., p::MAX, p::INFINITY]
}};
}
macro_rules! float_arbitrary {
($($t:ty, $path:path, $shrinkable:ty),+) => {$(
impl Arbitrary for $t {
fn arbitrary(g: &mut Gen) -> $t {
match g.gen_range(0..10) {
0 => *g.choose(float_problem_values!($path)).unwrap(),
_ => {
use $path as p;
let exp = g.gen_range((0.)..p::MAX_EXP as i16 as $t);
let mantissa = g.gen_range((1.)..2.);
let sign = *g.choose(&[-1., 1.]).unwrap();
sign * mantissa * exp.exp2()
}
}
}
fn shrink(&self) -> Box<dyn Iterator<Item = $t>> {
signed_shrinker!($shrinkable);
let it = shrinker::SignedShrinker::new(*self as $shrinkable);
Box::new(it.map(|x| x as $t))
}
}
)*};
}
float_arbitrary!(f32, std::f32, i32, f64, std::f64, i64);
macro_rules! unsigned_non_zero_shrinker {
($ty:tt) => {
mod shrinker {
pub struct UnsignedNonZeroShrinker {
x: $ty,
i: $ty,
}
impl UnsignedNonZeroShrinker {
pub fn new(x: $ty) -> Box<dyn Iterator<Item = $ty>> {
debug_assert!(x > 0);
if x == 1 {
super::empty_shrinker()
} else {
Box::new(
std::iter::once(1).chain(
UnsignedNonZeroShrinker { x: x, i: x / 2 },
),
)
}
}
}
impl Iterator for UnsignedNonZeroShrinker {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
if self.x - self.i < self.x {
let result = Some(self.x - self.i);
self.i = self.i / 2;
result
} else {
None
}
}
}
}
};
}
macro_rules! unsigned_non_zero_arbitrary {
($($ty:tt => $inner:tt),*) => {
$(
impl Arbitrary for $ty {
fn arbitrary(g: &mut Gen) -> $ty {
let mut v: $inner = g.gen();
if v == 0 {
v += 1;
}
$ty::new(v).expect("non-zero value contsturction failed")
}
fn shrink(&self) -> Box<dyn Iterator<Item = $ty>> {
unsigned_non_zero_shrinker!($inner);
Box::new(shrinker::UnsignedNonZeroShrinker::new(self.get())
.map($ty::new)
.map(Option::unwrap))
}
}
)*
}
}
unsigned_non_zero_arbitrary! {
NonZeroUsize => usize,
NonZeroU8 => u8,
NonZeroU16 => u16,
NonZeroU32 => u32,
NonZeroU64 => u64,
NonZeroU128 => u128
}
impl<T: Arbitrary> Arbitrary for Wrapping<T> {
fn arbitrary(g: &mut Gen) -> Wrapping<T> {
Wrapping(T::arbitrary(g))
}
fn shrink(&self) -> Box<dyn Iterator<Item = Wrapping<T>>> {
Box::new(self.0.shrink().map(|inner| Wrapping(inner)))
}
}
impl<T: Arbitrary> Arbitrary for Bound<T> {
fn arbitrary(g: &mut Gen) -> Bound<T> {
match g.gen_range(0..3) {
0 => Bound::Included(T::arbitrary(g)),
1 => Bound::Excluded(T::arbitrary(g)),
_ => Bound::Unbounded,
}
}
fn shrink(&self) -> Box<dyn Iterator<Item = Bound<T>>> {
match *self {
Bound::Included(ref x) => {
Box::new(x.shrink().map(Bound::Included))