generator-combinator 0.4.0

Composes combinators to generate patterns of increasing complexity
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
#![allow(non_camel_case_types)]
use crate::iter::StringIter;
use crate::transformfn::TransformFn;
use std::{
    fmt::Display,
    mem,
    ops::{Add, AddAssign, BitOr, BitOrAssign, Mul, MulAssign},
};

/// The building block of generator-combinators.
///
/// A `Generator` can be constructed from strings, chars, and slices:
///
/// ```
/// use generator_combinator::Generator;
/// let foo = Generator::from("foo"); // generates the string `foo`
/// let dot = Generator::from('.'); // generates the string `.`
/// let countries = Generator::from(&["US", "FR", "NZ", "CH"][..]); // generates strings `US`, `FR`, `NZ`, and `CH`.
/// ```
///
/// Individual `Generator`s can be combined as sequences with `+`, as variants with `|`, and with repetition with `* usize` and `* (usize, usize)`:
///
/// ```
/// use generator_combinator::Generator;
/// let foo = Generator::from("foo");
/// let bar = Generator::from("bar");
/// let foobar = foo.clone() + bar.clone(); // generates `foobar`
/// let foo_or_bar = foo.clone() | bar.clone(); // generates `foo`, `bar`
/// let foo_or_bar_x2 = foo_or_bar.clone() * 2; // generates `foofoo`, `foobar`, `barfoo`, `barbar`
/// let foo_x2_to_x4 = foo.clone() * (2, 4); // generates `foofoo`, `foofoofoo`, `foofoofoofoo`
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum Generator {
    // Some convenience 'constants':
    /// Lowercase ASCII letters (a-z)
    AlphaLower,

    /// Uppercase ASCII letters (A-Z)
    AlphaUpper,

    /// Base-10 digits (0-9)
    Digit,

    /// Lowercase ASCII letters and digits (a-z0-9)
    AlphaNumLower,

    /// Uppercase ASCII letters and digits (A-Z0-9)
    AlphaNumUpper,

    /// Uppercase hexadecimal values (0-9A-F)
    HexUpper,

    /// Lowercase hexadecimal values (0-9a-f)
    HexLower,

    /// Generates a [`char`] literal.
    Char(char),

    /// Generates a [`String`] literal.
    ///
    /// Note that this is not a character class.
    /// `Str("foo".into())` generates the exact string `"foo"`
    Str(String),

    /// A choice between two or more patterns
    ///
    /// As a regex, this would be, eg, `(a|b|c)?` (depending on `is_optional`)
    OneOf {
        v: Vec<Generator>,
        is_optional: bool,
    },

    /// A pattern repeated exactly _n_ times. This is the same as [`RepeatedMN`](Self::RepeatedMN)`(a, n, n)`
    ///
    /// As a regex, this would be `a{n}`
    RepeatedN(Box<Generator>, usize),

    /// A pattern repeated at least _m_ times, as many as _n_ times.
    ///
    /// As a regex, this would be `a{m,n}`
    RepeatedMN(Box<Generator>, usize, usize),

    /// Two or more sequential patterns.
    ///
    /// As a regex, this would be, eg, `abc`
    Sequence(Vec<Generator>),

    /// Wrap the current generator in a user-defined transformation.
    Transform {
        inner: Box<Generator>,
        transform_fn: TransformFn,
    },

    /// Doesn't generate anything
    Empty,
}

impl Generator {
    const ASCII_LOWER_A: u8 = 97;
    const ASCII_UPPER_A: u8 = 65;
    const ASCII_0: u8 = 48;

    /// Create a regular expression that represents the patterns generated.
    ///
    /// The result here is currently best-guess. It's not guaranteed valid, correct, idiomatic, etc.
    pub fn regex(&self) -> String {
        use Generator::*;

        match self {
            AlphaLower => "[a-z]".into(),
            AlphaUpper => "[A-Z]".into(),
            Digit => "\\d".into(),
            AlphaNumUpper => "[A-Z\\d]".into(),
            AlphaNumLower => "[a-z\\d]".into(),
            HexUpper => "[\\dA-F]".into(),
            HexLower => "[\\da-f]".into(),
            Char(c) => match c {
                &'.' => "\\.".into(),
                c => String::from(*c),
            },
            Str(s) => s.replace('.', "\\."),
            OneOf { v, is_optional } => {
                let regexes = v.iter().map(|a| a.regex()).collect::<Vec<_>>();
                let mut grp = format!("({})", regexes.join("|"));
                if *is_optional {
                    grp.push('?');
                }
                grp
            }
            RepeatedN(a, n) => a.regex() + "{" + &n.to_string() + "}",
            RepeatedMN(a, m, n) => a.regex() + "{" + &m.to_string() + "," + &n.to_string() + "}",
            Sequence(v) => {
                let regexes = v.iter().map(|a| a.regex()).collect::<Vec<_>>();
                regexes.join("")
            }
            Transform {
                inner,
                transform_fn: _,
            } => inner.regex(),
            Empty => String::new(),
        }
    }

    /// The number of possible patterns represented.
    pub fn len(&self) -> u128 {
        use Generator::*;
        match self {
            AlphaLower | AlphaUpper => 26,
            Digit => 10,
            AlphaNumUpper | AlphaNumLower => 36,
            HexUpper | HexLower => 16,

            Char(_) | Str(_) => 1,

            OneOf { v, is_optional } => {
                // Optionals add one value (empty/null)
                v.iter().map(|a| a.len()).sum::<u128>() + if *is_optional { 1 } else { 0 }
            }

            // Repeated variants are like base-x numbers of length n, where x is the number of combinations for a.
            // RepeatedN is easy:
            RepeatedN(a, n) => a.len().pow(*n as u32),
            // RepeatedMN has to remove the lower 'bits'/'digits'
            RepeatedMN(a, m, n) => {
                let base = a.len();
                (*m..=*n).map(|i| base.pow(i as u32)).sum()
            }

            Sequence(v) => v.iter().map(|a| a.len()).product(),
            Transform {
                inner,
                transform_fn: _,
            } => inner.len(),
            Empty => 1,
        }
    }

    /// Recursively generates the pattern encoded in `num`, appending values to the `result`.
    fn generate_on_top_of(&self, num: &mut u128, result: &mut String) {
        use Generator::*;

        match self {
            AlphaLower => {
                let i = (*num % 26) as u8;
                *num /= 26;
                let c: char = (Self::ASCII_LOWER_A + i).into();
                result.push(c);
            }
            AlphaUpper => {
                let i = (*num % 26) as u8;
                *num /= 26;
                let c: char = (Self::ASCII_UPPER_A + i).into();
                result.push(c);
            }
            Digit => {
                let i = (*num % 10) as u8;
                *num /= 10;
                let c: char = (Self::ASCII_0 + i).into();
                result.push(c);
            }
            AlphaNumUpper => {
                let i = (*num % 36) as u8;
                *num /= 36;
                let c: char = if i < 26 {
                    Self::ASCII_UPPER_A + i
                } else {
                    Self::ASCII_0 + i - 26
                }
                .into();
                result.push(c);
            }
            AlphaNumLower => {
                let i = (*num % 36) as u8;
                *num /= 36;
                let c: char = if i < 26 {
                    Self::ASCII_LOWER_A + i
                } else {
                    Self::ASCII_0 + i - 26
                }
                .into();
                result.push(c);
            }
            HexUpper => {
                let i = (*num % 16) as u8;
                *num /= 16;
                let c: char = if i < 10 {
                    Self::ASCII_0 + i
                } else {
                    Self::ASCII_UPPER_A + i - 10
                }
                .into();
                result.push(c);
            }
            HexLower => {
                let i = (*num % 16) as u8;
                *num /= 16;
                let c: char = if i < 10 {
                    Self::ASCII_0 + i
                } else {
                    Self::ASCII_LOWER_A + i - 10
                }
                .into();
                result.push(c);
            }
            Char(c) => {
                result.push(*c);
            }
            Str(s) => {
                result.push_str(s);
            }
            OneOf { v, is_optional } => {
                let v_len = self.len();

                // Divide out the impact of this OneOf; the remainder can be
                // used internally and we'll update num for parent recursions.
                let new_num = *num / v_len;
                *num %= v_len;

                if *is_optional && *num == 0 {
                    // use the optional - don't recurse and don't update result
                } else {
                    if *is_optional {
                        *num -= 1;
                    }
                    for a in v {
                        let a_len = a.len() as u128;
                        if *num < a_len {
                            a.generate_on_top_of(num, result);
                            break;
                        } else {
                            // subtract out the impact of this OneOf branch
                            *num -= a_len;
                        }
                    }
                }

                *num = new_num;
            }
            RepeatedN(a, n) => {
                // Repeat this one exactly n times
                let mut parts = Vec::with_capacity(*n);
                for _ in 0..*n {
                    let mut r = String::new();
                    a.generate_on_top_of(num, &mut r);
                    parts.push(r);
                }
                parts.reverse();
                result.push_str(&parts.join(""));
            }
            RepeatedMN(a, m, n) => {
                let mut parts = Vec::with_capacity(n - m + 1);
                for _ in *m..=*n {
                    let mut r = String::new();
                    a.generate_on_top_of(num, &mut r);
                    parts.push(r);
                }
                parts.reverse();
                result.push_str(&parts.join(""));
            }
            Sequence(v) => {
                for a in v {
                    a.generate_on_top_of(num, result);
                }
            }
            Transform {
                inner,
                transform_fn,
            } => {
                let mut r = String::new();
                inner.generate_on_top_of(num, &mut r);
                let r = (transform_fn.0)(r);
                result.push_str(&r);
            }
            Empty => {}
        }
    }

    /// Generates the [`String`] encoded by the specified `num`.
    ///
    /// Panics if `num` exceeds the length given by [Generator::len]
    pub fn generate_one(&self, num: u128) -> String {
        let range = self.len();
        assert!(num < range);

        let mut num = num;

        // build up a single string
        let mut result = String::new();
        self.generate_on_top_of(&mut num, &mut result);
        result
    }

    /// Makes this `Generator` optional.
    ///
    /// As a regex, this is the `?` operator.
    pub fn optional(self) -> Self {
        use Generator::OneOf;
        match self {
            OneOf {
                v,
                is_optional: true,
            } => OneOf {
                v,
                is_optional: true,
            },
            OneOf {
                v,
                is_optional: false,
            } => OneOf {
                v,
                is_optional: true,
            },
            _ => OneOf {
                v: vec![self],
                is_optional: true,
            },
        }
    }

    /// Provides an iterator across all possible values for this `Generator`.
    pub fn generate_all(&self) -> StringIter {
        self.into()
    }

    /// Includes a user-defined transformation when generating values.
    pub fn transform(self, f: fn(String) -> String) -> Self {
        let transform_fn = TransformFn(Box::new(f));

        Self::Transform {
            inner: Box::new(self),
            transform_fn,
        }
    }

    /// For a value specified by `num`, applies the callback `cb` for each of the component values
    /// for this Generator.
    ///
    /// This may be preferable to [`generate_one`] if you want to see the individual components
    /// comprising the final string and/or if you want to avoid the memory allocation and freeing
    /// by creating the values.
    pub fn visit_one<F>(&self, mut num: u128, mut cb: F)
    where
        F: FnMut(String),
    {
        let range = self.len();
        assert!(num < range);

        self.visit_exact_inner(&mut num, &mut cb);
    }

    /// Internal function to recursively visit each of the components of this Generator.
    fn visit_exact_inner<F>(&self, num: &mut u128, cb: &mut F)
    where
        F: FnMut(String),
    {
        use Generator::*;

        match self {
            AlphaLower => {
                let i = (*num % 26) as u8;
                *num /= 26;
                let c: char = (Self::ASCII_LOWER_A + i).into();
                cb(String::from(c));
            }
            AlphaUpper => {
                let i = (*num % 26) as u8;
                *num /= 26;
                let c: char = (Self::ASCII_UPPER_A + i).into();
                cb(String::from(c));
            }
            Digit => {
                let i = (*num % 10) as u8;
                *num /= 10;
                let c: char = (Self::ASCII_0 + i).into();
                cb(String::from(c));
            }
            AlphaNumUpper => {
                let i = (*num % 36) as u8;
                *num /= 36;
                let c: char = if i < 26 {
                    Self::ASCII_UPPER_A + i
                } else {
                    Self::ASCII_0 + i - 26
                }
                .into();
                cb(String::from(c));
            }
            AlphaNumLower => {
                let i = (*num % 36) as u8;
                *num /= 36;
                let c: char = if i < 26 {
                    Self::ASCII_LOWER_A + i
                } else {
                    Self::ASCII_0 + i - 26
                }
                .into();
                cb(String::from(c));
            }
            HexUpper => {
                let i = (*num % 16) as u8;
                *num /= 16;
                let c: char = if i < 10 {
                    Self::ASCII_0 + i
                } else {
                    Self::ASCII_UPPER_A + i - 10
                }
                .into();
                cb(String::from(c));
            }
            HexLower => {
                let i = (*num % 16) as u8;
                *num /= 16;
                let c: char = if i < 10 {
                    Self::ASCII_0 + i
                } else {
                    Self::ASCII_LOWER_A + i - 10
                }
                .into();
                cb(String::from(c));
            }
            Char(c) => cb(String::from(*c)),
            Str(s) => cb(s.to_string()),
            OneOf { v, is_optional } => {
                let v_len = self.len();

                // Divide out the impact of this OneOf; the remainder can be
                // used internally and we'll update num for parent recursions.
                let new_num = *num / v_len;
                *num %= v_len;

                if *is_optional && *num == 0 {
                    // use the optional - don't recurse and don't update result
                } else {
                    if *is_optional {
                        *num -= 1;
                    }
                    for a in v {
                        let a_len = a.len();
                        if *num < a_len {
                            a.visit_exact_inner(num, cb);
                            break;
                        } else {
                            // subtract out the impact of this OneOf branch
                            *num -= a_len;
                        }
                    }
                }

                *num = new_num;
            }
            RepeatedN(a, n) => {
                // Repeat this one exactly n times
                let mut parts = Vec::with_capacity(*n);
                for _ in 0..*n {
                    let mut r = String::new();
                    a.generate_on_top_of(num, &mut r);
                    parts.push(r);
                }

                parts.into_iter().rev().for_each(cb);
            }
            RepeatedMN(a, m, n) => {
                let mut parts = Vec::with_capacity(n - m + 1);
                for _ in *m..=*n {
                    let mut r = String::new();
                    a.generate_on_top_of(num, &mut r);
                    parts.push(r);
                }
                parts.into_iter().rev().for_each(cb);
            }
            Sequence(v) => v.iter().for_each(|a| a.visit_exact_inner(num, cb)),
            Transform {
                inner,
                transform_fn,
            } => {
                let mut r = String::new();
                inner.generate_on_top_of(num, &mut r);
                let r = (transform_fn.0)(r);
                cb(r);
            }
            // Empty won't invoke the callback
            Empty => {}
        }
    }
}

impl Default for Generator {
    fn default() -> Self {
        Generator::Empty
    }
}

impl From<char> for Generator {
    fn from(c: char) -> Self {
        Generator::Char(c)
    }
}

impl From<&str> for Generator {
    fn from(s: &str) -> Self {
        Generator::Str(s.to_string())
    }
}

impl From<String> for Generator {
    fn from(s: String) -> Self {
        Generator::Str(s)
    }
}

impl<T> From<&[T]> for Generator
where
    T: AsRef<str> + Display,
{
    fn from(values: &[T]) -> Self {
        // todo: check for & remove empty strings and set is_optional to true
        let is_optional = false;
        let v = values
            .iter()
            .map(|value| Generator::Str(value.to_string()))
            .collect();
        Generator::OneOf { v, is_optional }
    }
}

impl BitOr for Generator {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        use Generator::*;
        match (self, rhs) {
            (
                OneOf {
                    v: mut v1,
                    is_optional: opt1,
                },
                OneOf {
                    v: v2,
                    is_optional: opt2,
                },
            ) => {
                v1.extend(v2);

                let is_optional = opt1 || opt2;
                OneOf { v: v1, is_optional }
            }
            (OneOf { mut v, is_optional }, rhs) => {
                v.push(rhs);
                OneOf { v, is_optional }
            }
            (lhs, OneOf { mut v, is_optional }) => {
                v.insert(0, lhs);
                OneOf { v, is_optional }
            }

            (lhs, rhs) => {
                let v = vec![lhs, rhs];
                OneOf {
                    v,
                    is_optional: false,
                }
            }
        }
    }
}

/// Mul operator for exact repetitions.
///
/// The following expressions are equivalent:
/// ```
/// use generator_combinator::Generator;
/// let foostr = Generator::from("foofoo");
/// let foomul = Generator::from("foo") * 2;
/// let fooadd = Generator::from("foo") + Generator::from("foo");
/// ```
impl Mul<usize> for Generator {
    type Output = Self;

    fn mul(self, rhs: usize) -> Self::Output {
        if rhs == 0 {
            // Multiplying a generator by 0 transforms it to Empty
            Generator::Empty
        } else {
            let lhs = Box::new(self);
            Generator::RepeatedN(lhs, rhs)
        }
    }
}

impl MulAssign<usize> for Generator {
    fn mul_assign(&mut self, rhs: usize) {
        if rhs == 0 {
            // Multiplying a generator by 0 transforms it to Empty
            *self = Generator::Empty;
        } else {
            let repeat = self.clone() * rhs;
            *self = repeat;
        }
    }
}

/// Mul operator for repetitions between `m` and `n` (inclusive)
/// ```
/// use generator_combinator::Generator;
/// let foo_two_to_five_times = Generator::from("foo") * (2,5);
/// ```
impl Mul<(usize, usize)> for Generator {
    type Output = Self;

    fn mul(self, rhs: (usize, usize)) -> Self::Output {
        let (m, n) = rhs;
        assert!(m <= n);

        let lhs = Box::new(self);
        if m == 0 {
            // if the lower bound is zero, then this is an optional pattern
            Generator::RepeatedMN(lhs, 1, n).optional()
        } else {
            Generator::RepeatedMN(lhs, m, n)
        }
    }
}

impl MulAssign<(usize, usize)> for Generator {
    fn mul_assign(&mut self, rhs: (usize, usize)) {
        let (m, n) = rhs;
        assert!(m <= n);

        let lhs = mem::take(self);

        *self = if m == 0 {
            Generator::RepeatedMN(Box::new(lhs), 1, n).optional()
        } else {
            Generator::RepeatedMN(Box::new(lhs), m, n)
        };
    }
}

/// Add operator for exact repetitions.
///
/// The following expressions are equivalent:
/// ```
/// use generator_combinator::Generator;
/// let foostr = Generator::from("foofoo");
/// let foomul = Generator::from("foo") * 2;
/// let fooadd = Generator::from("foo") + Generator::from("foo");
/// ```
impl Add for Generator {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        use Generator::*;
        match (self, rhs) {
            // + Empty is a no-op
            (s, Generator::Empty) => s,
            (Sequence(mut v1), Sequence(v2)) => {
                v1.extend(v2);
                Sequence(v1)
            }
            (Sequence(mut v1), rhs) => {
                v1.push(rhs);
                Sequence(v1)
            }
            (lhs, Sequence(v2)) => {
                let mut v = Vec::with_capacity(1 + v2.len());
                v.push(lhs);
                v.extend(v2);
                Sequence(v)
            }

            (lhs, rhs) => {
                let v = vec![lhs, rhs];
                Sequence(v)
            }
        }
    }
}

impl AddAssign for Generator {
    fn add_assign(&mut self, rhs: Self) {
        use Generator::*;
        match (self, rhs) {
            // Adding empty doesn't do anything
            (_, Generator::Empty) => {}
            (Sequence(v1), Sequence(v2)) => {
                v1.extend(v2);
            }
            (Sequence(v1), rhs) => {
                v1.push(rhs);
            }
            (lhs, Sequence(v2)) => {
                let mut v = Vec::with_capacity(1 + v2.len());
                v.push(mem::take(lhs));
                v.extend(v2);
                *lhs = Sequence(v);
            }

            (lhs, rhs) => {
                let left = mem::take(lhs);
                let v = vec![left, rhs];
                *lhs = Sequence(v)
            }
        }
    }
}

impl BitOrAssign for Generator {
    fn bitor_assign(&mut self, rhs: Self) {
        use Generator::*;
        match (self, rhs) {
            (
                OneOf {
                    v: v1,
                    is_optional: opt1,
                },
                OneOf {
                    v: v2,
                    is_optional: opt2,
                },
            ) => {
                v1.extend(v2);
                if opt2 {
                    *opt1 = true;
                }
            }
            (OneOf { v, is_optional: _ }, rhs) => {
                v.push(rhs);
            }
            (lhs, OneOf { mut v, is_optional }) => {
                let left = mem::take(lhs);
                v.insert(0, left);
                *lhs = OneOf { v, is_optional };
            }

            (lhs, rhs) => {
                let left = mem::take(lhs);
                let v = vec![left, rhs];
                *lhs = OneOf {
                    v,
                    is_optional: false,
                };
            }
        }
    }
}

macro_rules! impl_add_or {
    ($t: ty) => {
        impl Add<$t> for Generator {
            type Output = Generator;

            fn add(self, rhs: $t) -> Self::Output {
                let rhs: Generator = rhs.into();
                self + rhs
            }
        }

        impl AddAssign<$t> for Generator {
            fn add_assign(&mut self, rhs: $t) {
                *self = std::mem::take(self) + rhs;
            }
        }

        impl BitOr<$t> for Generator {
            type Output = Generator;

            fn bitor(self, rhs: $t) -> Self::Output {
                let rhs: Generator = rhs.into();
                self | rhs
            }
        }

        impl BitOrAssign<$t> for Generator {
            fn bitor_assign(&mut self, rhs: $t) {
                *self = std::mem::take(self) | rhs;
            }
        }
    };
}

impl_add_or!(String);
impl_add_or!(&str);
impl_add_or!(char);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{gen, oneof};
    #[test]
    fn combinations_consts() {
        let eight_alphas = Generator::AlphaLower * 8;
        assert_eq!(26u128.pow(8), eight_alphas.len());

        // This is the same as above
        let eight_alphas = Generator::AlphaLower * (8, 8);
        assert_eq!(26u128.pow(8), eight_alphas.len());

        // This is all combinations of exactly seven or exactly eight alphas:
        // aaaaaaa, aaaaaab, ..., zzzzzzz, aaaaaaaa, ..., zzzzzzzz
        let expected = 26u128.pow(7) + 26u128.pow(8);
        let seven_or_eight_alphas = Generator::AlphaLower * (7, 8);
        assert_eq!(expected, seven_or_eight_alphas.len());
    }

    #[test]
    fn combinations_mn() {
        /*
        Given the regex [ab]{2,3}, we can enumerate this easily:
        aa, ab, ba, bb,
        aaa, aab, aba, abb, baa, bab, bba, bbb
        Total combinations is therefore 12
        */

        let ab23 = (Generator::from("a") | Generator::from("b")) * (2, 3);
        assert_eq!(12, ab23.len());
    }

    #[test]
    fn combinations_str() {
        let foo = Generator::from("foo");
        assert_eq!(1, foo.len());
    }

    #[test]
    fn combinations_oneof() {
        let foo = Generator::from("foo");
        let bar = Generator::from("bar");
        assert_eq!(1, foo.len());
        assert_eq!(1, bar.len());

        let foo_bar = foo | bar;
        assert_eq!(2, foo_bar.len());

        let baz = Generator::from("baz");
        assert_eq!(1, baz.len());
        let foo_bar_baz = foo_bar | baz;
        assert_eq!(3, foo_bar_baz.len());
    }

    #[test]
    fn combinations_optional() {
        let foo = Generator::from("foo");
        let bar = Generator::from("bar");

        let opt_foo = Generator::OneOf {
            v: vec![foo.clone()],
            is_optional: true,
        };
        assert_eq!(2, opt_foo.len());

        let opt_foo_bar = Generator::OneOf {
            v: vec![foo.clone(), bar.clone()],
            is_optional: true,
        };
        assert_eq!(3, opt_foo_bar.len());

        let mut v = opt_foo_bar.generate_all();
        assert_eq!(Some("".into()), v.next());
        assert_eq!(Some("foo".into()), v.next());
        assert_eq!(Some("bar".into()), v.next());
        assert_eq!(None, v.next());
    }

    #[test]
    fn combinations_email() {
        use Generator::Char;
        let username = Generator::AlphaLower * (6, 8);
        let user_combos = 26u128.pow(6) + 26u128.pow(7) + 26u128.pow(8);
        assert_eq!(username.len(), user_combos);

        let tld = Generator::from("com")
            | Generator::from("net")
            | Generator::from("org")
            | Generator::from("edu")
            | Generator::from("gov");
        let tld_combos = 5;
        assert_eq!(tld.len(), tld_combos);

        let domain = Generator::AlphaLower * (1, 8) + Char('.') + tld;
        let domain_combos = (1..=8).map(|i| 26u128.pow(i)).sum::<u128>() * tld_combos;
        assert_eq!(domain.len(), domain_combos);

        let email = username + Char('@') + domain;
        assert_eq!(email.len(), domain_combos * user_combos);
    }

    #[test]
    fn generate_alpha1() {
        let alphas2 = Generator::AlphaLower * 2;
        let aa = alphas2.generate_one(0);
        assert_eq!(aa, "aa");

        let onetwothree = (Generator::Digit * 10).generate_one(123);
        assert_eq!(onetwothree, "0000000123");

        // Same thing but with postprocessing
        let onetwothree = (Generator::Digit * 10)
            .transform(|s| s.trim_start_matches('0').to_string())
            .generate_one(123);
        assert_eq!(onetwothree, "123");
    }

    #[test]
    fn generate_hex() {
        let hex = Generator::from("0x") + Generator::HexUpper * 8;

        assert_eq!(4_294_967_296, hex.len());

        assert_eq!(hex.generate_one(3_735_928_559), "0xDEADBEEF");
        assert_eq!(hex.generate_one(464_375_821), "0x1BADD00D");
    }

    #[test]
    fn simplify() {
        let foo_opt1 = gen!("foo").optional();
        let foo_opt1 = foo_opt1.optional(); // making an optional optional shouldn't change it

        let foo_opt2 = gen!("foo").optional();
        assert_eq!(foo_opt1, foo_opt2);
    }

    #[test]
    fn equality() {
        // test the macros
        let foo1 = Generator::from("foo");
        let foo2 = gen!("foo");
        assert_eq!(foo1, foo2);

        let foo2 = oneof!("foo");
        assert_eq!(foo1, foo2);

        // test BitOrAssign
        let foobar1 = oneof!("foo", "bar");
        let mut foobar2 = gen!("foo");
        foobar2 |= gen!("bar");
        assert_eq!(foobar1, foobar2);

        // test AddAssign
        let foobar1 = gen!("foo") + gen!("bar");
        let mut foobar2 = gen!("foo");
        foobar2 += gen!("bar");
        assert_eq!(foobar1, foobar2);

        // test MulAssign<usize>
        let foo1 = gen!("foo") * 2;
        let mut foo2 = gen!("foo");
        foo2 *= 2;
        assert_eq!(foo1, foo2);

        // test MulAssign<(usize,usize)>
        let foo1 = gen!("foo") * (2, 3);
        let mut foo2 = gen!("foo");
        foo2 *= (2, 3);
        assert_eq!(foo1, foo2);
    }

    #[test]
    fn test_reduce_optionals() {
        // A naive implementation might treat this as:
        // ("foo" | "") | ("bar" | "") | ("baz" | ""), which could incorrectly generate two unnecessary empty strings
        let foo = gen!("foo").optional();
        let bar = gen!("bar").optional();
        let baz = gen!("baz").optional();
        let foobarbaz1 = foo | bar | baz;

        // The ideal approach is to know that with each of foo, bar, and baz being optional, it's the same as:
        let foobarbaz2 = gen!("foo").optional() | oneof!("bar", "baz");

        // Which they are, taken care of by BitOr
        assert_eq!(foobarbaz1, foobarbaz2);

        // And it will generate the four values as expected
        let values: Vec<_> = foobarbaz1.generate_all().collect();
        assert_eq!(vec!["", "foo", "bar", "baz"], values);

        // Note that the optional value is boosted to the front of the line and foo|bar|baz are commoned up
        let foobarbaz3 = gen!("foo") | gen!("bar").optional() | gen!("baz");
        assert_eq!(foobarbaz1, foobarbaz3);
        assert!(
            matches!(foobarbaz3, Generator::OneOf { v, is_optional } if v.len() == 3 && is_optional)
        );
    }

    #[test]
    fn test_transform() {
        let foobarbaz = oneof!("foo", "bar", "baz");

        // Trim any leading 'b' from (foo|bar|baz)
        let fooaraz = foobarbaz.clone().transform(|s| {
            if s.starts_with("b") {
                s.trim_start_matches('b').to_string()
            } else {
                s
            }
        });

        assert_eq!(3, fooaraz.len());
        assert_eq!("foo", fooaraz.generate_one(0));
        assert_eq!("ar", fooaraz.generate_one(1));
        assert_eq!("az", fooaraz.generate_one(2));

        // Uppercase (foo|bar|baz)
        let foobarbaz_upper = foobarbaz.clone().transform(|s| s.to_uppercase());
        assert_eq!(3, foobarbaz_upper.len());
        assert_eq!("FOO", foobarbaz_upper.generate_one(0));
        assert_eq!("BAR", foobarbaz_upper.generate_one(1));
        assert_eq!("BAZ", foobarbaz_upper.generate_one(2));

        let ten_digits = Generator::Digit * 10;
        let onetwothree = ten_digits.generate_one(123);
        assert_eq!(onetwothree, "0000000123");
        let onetwothree = ten_digits
            .transform(|s| s.trim_start_matches('0').to_string())
            .generate_one(123);
        assert_eq!(onetwothree, "123");
    }

    #[test]
    fn test_visit() {
        let foobarbaz = oneof!("foo", "bar", "baz");
        let fbb_nnnn = foobarbaz + Generator::Digit * 4;

        let bar1234 = fbb_nnnn.generate_one(3703);
        assert_eq!("bar1234", bar1234);

        let mut s = String::with_capacity(7);
        fbb_nnnn.visit_one(3703, |part| s.push_str(&part));
        assert_eq!("bar1234", s);
    }

    #[test]
    fn regex() {
        let foobarbaz = oneof!("foo", "bar", "baz");
        let fbb_nnnn = foobarbaz + Generator::Digit * 4;
        assert_eq!("(foo|bar|baz)\\d{4}", fbb_nnnn.regex());

        let hi45 = Generator::from("hi") * (4, 5);
        assert_eq!("hi{4,5}", hi45.regex());

        let sea = Generator::from("Seattle") + gen!(", WA").optional();
        assert_eq!("Seattle(, WA)?", sea.regex());
    }

    quickcheck! {
        /// Check that `generate_one` will produce the same string as would be visited.
        fn street_addresses(n: u128) -> bool {
            const RANGE : u128 = 809_190_000;

            let space = Generator::from(' ');
            let number = (Generator::Digit * (3, 5)).transform(|s| s.trim_start_matches('0').to_string());

            let directional = space.clone() + oneof!("N", "E", "S", "W", "NE", "SE", "SW", "NW");
            let street_names = space.clone() + oneof!("Boren", "Olive", "Spring", "Cherry", "Seneca", "Yesler", "Madison", "James", "Union", "Mercer");
            let street_suffixes = space.clone() + oneof!("Rd", "St", "Ave", "Blvd", "Ln", "Dr", "Way", "Ct", "Pl");

            let address = number
                + directional.clone().optional()
                + street_names
                + street_suffixes
                + directional.clone().optional();

            assert_eq!(address.len(), RANGE);
            let n = n % RANGE;

            let generated = address.generate_one(n);

            let mut visited  = String::with_capacity(generated.len());
            address.visit_one(n, |part| visited.push_str(&part));
            assert_eq!(visited, generated);

            true
        }
    }

    #[test]
    #[should_panic]
    fn exceeds_u128() {
        // The range for any generator is store id a `u128`.
        // 2**128 == 340282366920938463463374607431768211456, which is 39 digits long.
        // Trying to generate a 39 digit string, therefore, exceeds the capacity.
        // We can build the generator successfully:
        let g = Generator::Digit * 39;

        // But when calculating the range, we'll get an overflow:
        let _n = g.len();
    }

    #[test]
    fn lower_limit_0() {
        // Both should be: empty, a, aa
        let g1 = Generator::Char('a') * (0, 2);
        let g2 = (Generator::Char('a') * (1, 2)).optional();
        assert_eq!(g1.len(), g2.len());
        assert_eq!(g1, g2);

        let g1 = (Generator::Char('a') * (1, 2)) * 0;
        let g2 = Generator::Empty;
        assert_eq!(g1.len(), g2.len());
        assert_eq!(g1, g2);
    }

    #[test]
    fn oneof_bitorassign_oneof() {
        let mut g = oneof!('a', 'b');
        g |= oneof!('x', 'y');
        assert_eq!(g.len(), 4);
    }

    #[test]
    fn test_add_addassign() {
        let g = Generator::from("hello");
        let g = g + ',' + ' ' + "world!".to_string();
        assert_eq!(g.len(), 1);

        let mut g = Generator::from("hello");
        g += ',';
        g += " world!";

        assert_eq!(g.len(), 1);
    }

    #[test]
    fn test_bitor_bitorassign() {
        let mut g = Generator::from("hello") | "hi" | "salut".to_string();
        g += ", ";
        g += Generator::from("world") | "tout le monde" | "everyone";
        g += '!';

        assert_eq!(g.len(), 9);
    }

    #[test]
    fn test_or_and() {
        let mut g = Generator::from("hello");
        g |= "salut";
        g += ',';
        g += " ";
        g += Generator::from("world") | "tout le monde" | "🌎";
        g += String::from("!");

        assert_eq!(g.len(), 6);
    }
}