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
#![allow(non_camel_case_types)]
use crate::Iter;
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, Eq)]
pub enum Generator {
    // Some convenience 'constants':
    /// Lowercase letters (a-z)
    AlphaLower,

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

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

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

    /// Uppercase 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)`
    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>),
}

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("")
            }
        }
    }

    /// 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()).fold(1, |acc, n| acc * n),
        }
    }

    /// 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);
                }
            }
        }
    }

    pub fn generate_exact(&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 values(&self) -> Iter {
        Iter {
            c: self,
            n: self.len(),
            i: 0,
        }
    }

    // Removes redundant [`Self::Optional`] values from [`Self::OneOf`].
    //
    // When `OneOf` contains multiple `Optional` values, the generator would incorrectly
    // produce two logically identical results. This function detects this scenario,
    // keeping the first `Optional` value and unboxing the remaining values, if any.
    /*
    fn reduce_optionals(v: &mut Vec<Generator>) {
        use Generator::*;
        let mut found_opt = false;

        for a in v.iter_mut() {
            if let Optional(inner) = a {
                if found_opt {
                    // convert this to non-optional
                    let inner = mem::replace(inner, Box::new(Digit));
                    *a = *inner;
                } else {
                    // first optional can be kept
                    found_opt = true;
                }
            }
        }
    }
    */
}

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<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);
                /*
                let mut v = vec![lhs];
                for c in v2 {
                    v.push(c);
                }
                Self::reduce_optionals(&mut v);
                */
                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 {
        let lhs = Box::new(self);
        Generator::RepeatedN(lhs, rhs)
    }
}

impl MulAssign<usize> for Generator {
    fn mul_assign(&mut self, rhs: usize) {
        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);
        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);

        // temporarily swap in Digit to avoid cloning self
        let lhs = mem::replace(self, Generator::Digit);
        *self = 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) {
            (Sequence(mut v1), Sequence(v2)) => {
                for c in v2 {
                    v1.push(c);
                }

                Sequence(v1)
            }
            (Sequence(mut v1), rhs) => {
                v1.push(rhs);
                Sequence(v1)
            }
            (lhs, Sequence(v2)) => {
                let mut v = vec![lhs];
                for c in v2 {
                    v.push(c);
                }
                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) {
            (Sequence(v1), Sequence(v2)) => {
                for c in v2 {
                    v1.push(c);
                }
            }
            (Sequence(v1), rhs) => {
                v1.push(rhs);
            }
            (lhs, Sequence(mut v2)) => {
                let left = mem::replace(lhs, Generator::Digit);
                v2.insert(0, left);
                *lhs = Sequence(v2);
            }

            (lhs, rhs) => {
                let left = mem::replace(lhs, Generator::Digit);
                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.push(Digit);
                v1.extend(v2);
                if opt2 {
                    *opt1 = true;
                }
            }
            (OneOf { v, is_optional: _ }, rhs) => {
                v.push(rhs);
            }
            (lhs, OneOf { mut v, is_optional }) => {
                // swap out left to avoid clone
                let left = mem::replace(lhs, Generator::Digit);
                v.insert(0, left);
                *lhs = OneOf { v, is_optional };
            }

            (lhs, rhs) => {
                let left = mem::replace(lhs, Generator::Digit);
                let v = vec![left, rhs];
                //Self::reduce_optionals(&mut v);
                *lhs = OneOf {
                    v,
                    is_optional: false,
                };
            }
        }

        // address potential duplicate optionals
        //let s = mem::replace(self, Digit);
        //*self = s.reduce_optionals();
    }
}

#[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.values();
        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_exact(0);
        assert_eq!(aa, "aa");

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

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

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

        assert_eq!(hex.generate_exact(3_735_928_559), "0xDEADBEEF");
        assert_eq!(hex.generate_exact(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() {
        let foo = gen!("foo").optional();
        let bar = gen!("bar").optional();
        let baz = gen!("baz").optional();
        let foobarbaz1 = foo | bar | baz;

        let foobarbaz2 = gen!("foo").optional() | oneof!("bar", "baz");

        assert_eq!(foobarbaz1, foobarbaz2);
    }
}