dice-nom 0.5.2

A library that utilizes the nom parser for randomly generating numbers to support role-playing games.
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
use super::results::{Pool, Results, Value};
use rand::prelude::*;
use std::cmp::Ordering;
use std::fmt;

/// The top-level generator that can represent complex dice expressions including comparisons.
///
/// A `Generator` consists of a success generator and an optional comparison operator to
/// compare against another generator. This allows for expressions like "3d6 > 2d8+1".
///
/// # Examples
///
/// ```rust
/// use dice_nom::parse;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Simple expression without comparison
/// let simple = parse("3d6+4").unwrap();
/// let result = simple.generate(&mut rng);
/// println!("Result: {}", result.sum());
///
/// // Comparison expression
/// let contest = parse("3d6 > 2d8").unwrap();
/// let result = contest.generate(&mut rng);
/// println!("Contest: {}", result.sum()); // 1 if left wins, 0 otherwise
/// ```
#[derive(Debug, PartialEq)]
pub struct Generator {
    /// The primary success generator for the left side of any comparison
    pub mul_div: MulDivGenerator,
    /// Optional comparison operator for comparing against another generator
    pub op: Option<ComparisonOp>,
}

impl fmt::Display for Generator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.mul_div)?;
        if let Some(op) = &self.op {
            write!(f, " {}", op)?;
        }
        write!(f, "")
    }
}

impl Generator {
    /// generate builds a top-level generator that can compare two
    ///
    /// * Example
    ///
    /// ```
    /// use dice_nom::generators::*;
    /// use dice_nom::results::*;
    /// use rand::prelude::*;
    /// let g = Generator{
    ///     mul_div: MulDivGenerator{
    ///         succ: SuccGenerator{
    ///             hits: HitsGenerator{
    ///                 expr: ExprGenerator{
    ///                     terms: vec![ArithTermGenerator{
    ///                         op: ArithOp::ImplicitAdd,
    ///                         term: TermGenerator::Pool(PoolGenerator{
    ///                             count: 12,
    ///                             range: 6,
    ///                             op: None
    ///                         })
    ///                     }]
    ///                 },
    ///                 op: None
    ///             },
    ///             op: None
    ///         },
    ///         op: None
    ///     },
    ///     op: None,
    /// };
    /// let mut rng = rand::rng();
    /// let pool = g.generate(&mut rng);
    /// ```
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Results {
        let lhs = self.mul_div.generate(rng);
        let (rhs, value) = match &self.op {
            Some(op) => match op {
                ComparisonOp::GT(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = if lhs.value() > rhs.value() { 1 } else { 0 };
                    (Some(rhs), val)
                }

                ComparisonOp::GE(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = if lhs.value() >= rhs.value() { 1 } else { 0 };
                    (Some(rhs), val)
                }

                ComparisonOp::LT(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = if lhs.value() < rhs.value() { 1 } else { 0 };
                    (Some(rhs), val)
                }

                ComparisonOp::LE(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = if lhs.value() <= rhs.value() { 1 } else { 0 };
                    (Some(rhs), val)
                }

                ComparisonOp::EQ(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = if lhs.value() == rhs.value() { 1 } else { 0 };
                    (Some(rhs), val)
                }

                ComparisonOp::CMP(rhs) => {
                    let rhs = rhs.generate(rng);
                    let val = match lhs.value().cmp(&rhs.value()) {
                        Ordering::Less => -1,
                        Ordering::Greater => 1,
                        Ordering::Equal => 0,
                    };
                    (Some(rhs), val)
                }
            },
            None => (None, 0),
        };
        Results { lhs, rhs, value }
    }
}

/// Comparison operators for comparing two dice expressions.
///
/// Each variant contains the right-hand side generator to compare against.
/// The comparison returns 1 for true, 0 for false, except CMP which returns
/// -1, 0, or 1 for less than, equal, or greater than respectively.
///
/// # Examples
///
/// ```rust
/// use dice_nom::parse;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Greater than comparison
/// let gt_test = parse("2d6+6x5").unwrap();
/// let result = gt_test.generate(&mut rng);
/// assert!(result.sum() >= 40);
/// ```
#[derive(Debug, PartialEq)]
pub enum ComparisonOp {
    /// Greater than (>)
    GT(SuccGenerator),
    /// Greater than or equal (>=)
    GE(SuccGenerator),
    /// Less than (<)
    LT(SuccGenerator),
    /// Less than or equal (<=)
    LE(SuccGenerator),
    /// Equal (=)
    EQ(SuccGenerator),
    /// Three-way comparison (<=>)
    CMP(SuccGenerator),
}

impl fmt::Display for ComparisonOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ComparisonOp::GT(succ) => write!(f, "> {}", succ),
            ComparisonOp::GE(succ) => write!(f, ">= {}", succ),
            ComparisonOp::LT(succ) => write!(f, "< {}", succ),
            ComparisonOp::LE(succ) => write!(f, "<= {}", succ),
            ComparisonOp::EQ(succ) => write!(f, "= {}", succ),
            ComparisonOp::CMP(succ) => write!(f, "<=> {}", succ),
        }
    }
}

/// Multiplication operators for multiplying simple values
///
/// Each variant contains the right-hand side generator to compare against.
/// The comparison returns 1 for true, 0 for false, except CMP which returns
/// -1, 0, or 1 for less than, equal, or greater than respectively.
///
/// # Examples
///
/// ```rust
/// use dice_nom::parse;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Greater than comparison
/// let gt_test = parse("3d6 > 10").unwrap();
/// let result = gt_test.generate(&mut rng);
/// // result.sum() will be 1 if 3d6 > 10, otherwise 0
/// ```
#[derive(Debug, PartialEq, Clone)]
pub enum MulDivOp {
    Mul(i32),
    Div(i32),
}

impl fmt::Display for MulDivOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MulDivOp::Mul(n) => write!(f, " x {}", n),
            MulDivOp::Div(n) => write!(f, " / {}", n),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct MulDivGenerator {
    /// The primary success generator for the left side of any comparison
    pub succ: SuccGenerator,
    /// Optional multiplication or division operator for comparing against another generator
    pub op: Option<MulDivOp>,
}

impl fmt::Display for MulDivGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.succ)?;
        if let Some(op) = &self.op {
            write!(f, "{}", op)?;
        }
        write!(f, "")
    }
}

impl MulDivGenerator {
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = self.succ.generate(rng);
        match &self.op {
            Some(op) => match op {
                MulDivOp::Mul(n) => {
                    let total = pool.sum();
                    pool.set_total(total * n);
                    pool
                }
                MulDivOp::Div(n) => {
                    let total = pool.sum();
                    pool.set_total(total / n);
                    pool
                }
            },
            None => pool,
        }
    }
}

/// Generator for success-based dice systems.
///
/// A success generator evaluates hits from a dice pool and applies success thresholds.
/// This is commonly used in systems where you need to achieve a certain total to succeed,
/// with additional successes for exceeding thresholds.
///
/// # Examples
///
/// ```rust
/// use dice_nom::parse;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Success if total >= 12
/// let success_test = parse("3d6{12}").unwrap();
/// let result = success_test.generate(&mut rng);
///
/// // Success levels: 1 success at 15, +1 for every 5 above
/// let level_test = parse("2d10{15,5}").unwrap();
/// let result = level_test.generate(&mut rng);
/// ```
#[derive(Debug, PartialEq)]
pub struct SuccGenerator {
    /// The hits generator that produces the base dice rolls
    pub hits: HitsGenerator,
    /// Optional success operation for threshold-based success counting
    pub op: Option<SuccessOp>,
}

impl fmt::Display for SuccGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.hits)?;
        if let Some(op) = &self.op {
            write!(f, "{}", op)?;
        }
        write!(f, "")
    }
}

impl SuccGenerator {
    /// generate builds a generator that calculates success based on whether
    /// the pool sum is greater than the target number.
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = self.hits.generate(rng);
        match &self.op {
            Some(op) => match op {
                SuccessOp::TargetSucc(n) => {
                    if pool.sum() >= *n {
                        pool.set_total(pool.sum() - n + 1);
                    } else {
                        pool.set_total(0);
                    }
                    pool
                }
                SuccessOp::TargetSuccNext(n, m) => {
                    if pool.sum() >= *n {
                        pool.set_total(((pool.sum() - n) / m) + 1);
                    } else {
                        pool.set_total(0);
                    }
                    pool
                }
            },
            None => pool,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum SuccessOp {
    TargetSucc(i32),
    TargetSuccNext(i32, i32),
}

impl fmt::Display for SuccessOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SuccessOp::TargetSucc(n) => write!(f, "{{{}}}", n),
            SuccessOp::TargetSuccNext(n, m) => write!(f, "{{{}, {}}}", n, m),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct HitsGenerator {
    pub expr: ExprGenerator,
    pub op: Option<TargetOp>,
}

impl fmt::Display for HitsGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.expr)?;
        if let Some(op) = &self.op {
            write!(f, "{}", op)?;
        }
        write!(f, "")
    }
}

impl HitsGenerator {
    /// generate
    ///
    /// * Example
    ///
    /// ```
    /// use dice_nom::generators::*;
    /// use dice_nom::results::*;
    /// use rand::prelude::*;
    /// let g = HitsGenerator{
    ///     expr: ExprGenerator{
    ///         terms: vec![ArithTermGenerator{
    ///             op: ArithOp::ImplicitAdd,
    ///             term: TermGenerator::Pool(PoolGenerator{
    ///                 count: 12,
    ///                 range: 6,
    ///                 op: None,
    ///             })
    ///         }]
    ///     },
    ///     op: Some(TargetOp::TargetHigh(4))
    /// };
    /// let mut rng = rand::rng();
    /// let pool = g.generate(&mut rng);
    /// assert!(pool.hits() > 0);
    /// ```
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = self.expr.generate(rng);
        match &self.op {
            Some(op) => match op {
                TargetOp::TargetHigh(n) => {
                    for idx in 0..pool.count() {
                        let b = pool.values[idx].sum().abs() >= *n;
                        pool.values[idx].set_hit(b);
                    }
                    pool.set_total(pool.sum());
                    pool
                }
                TargetOp::TargetLow(n) => {
                    for idx in 0..pool.count() {
                        let b = pool.values[idx].sum().abs() <= *n;
                        pool.values[idx].set_hit(b);
                    }
                    pool.set_total(pool.sum());
                    pool
                }
            },
            None => pool,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum TargetOp {
    TargetHigh(i32),
    TargetLow(i32),
}

impl fmt::Display for TargetOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TargetOp::TargetHigh(n) => write!(f, "[{}]", n),
            TargetOp::TargetLow(n) => write!(f, "({})", n),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct ExprGenerator {
    pub terms: Vec<ArithTermGenerator>,
}

impl fmt::Display for ExprGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for t in self.terms.iter() {
            write!(f, "{}", t)?;
        }
        write!(f, "")
    }
}

impl ExprGenerator {
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = Pool::new();
        for t in self.terms.iter() {
            pool.values.append(&mut t.generate(rng).values);
        }
        pool.set_total(pool.sum());
        pool
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum ArithOp {
    ImplicitAdd,
    Add,
    Sub,
}

impl fmt::Display for ArithOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ArithOp::ImplicitAdd => write!(f, ""),
            ArithOp::Add => write!(f, " + "),
            ArithOp::Sub => write!(f, " - "),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct ArithTermGenerator {
    pub op: ArithOp,
    pub term: TermGenerator,
}

impl fmt::Display for ArithTermGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}", self.op, self.term)
    }
}

impl ArithTermGenerator {
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = self.term.generate(rng);
        match &self.op {
            ArithOp::Sub => {
                for idx in 0..pool.count() {
                    pool.values[idx].mark_penalty();
                }
                pool
            }
            _ => pool,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum TermGenerator {
    Pool(PoolGenerator),
    Constant(i32),
}

impl fmt::Display for TermGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TermGenerator::Pool(pg) => write!(f, "{}", pg),
            TermGenerator::Constant(n) => write!(f, "{}", n),
        }
    }
}

impl TermGenerator {
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        match self {
            TermGenerator::Pool(pg) => pg.generate(rng),
            TermGenerator::Constant(n) => Pool::new_with_values(vec![Value::constant(*n)]),
        }
    }
}

/// Generator for a pool of dice with optional operations.
///
/// This is the fundamental building block representing "XdY" notation, where X is the
/// count of dice and Y is the range (number of sides). Optional operations can modify
/// how the dice behave (exploding, advantage, etc.).
///
/// # Examples
///
/// ```rust
/// use dice_nom::generators::PoolGenerator;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Simple 3d6
/// let basic = PoolGenerator { count: 3, range: 6, op: None };
/// let result = basic.generate(&mut rng);
///
/// // Using the convenience function
/// use dice_nom::roller;
/// let exploding = roller(2, 8, Some("!"));
/// let result = exploding.generate(&mut rng);
/// ```
#[derive(Debug, PartialEq, Clone)]
pub struct PoolGenerator {
    /// Number of dice to roll
    pub count: i32,
    /// Number of sides on each die (range 1 to this value)
    pub range: i32,
    /// Optional operation to apply to the dice pool
    pub op: Option<PoolOp>,
}

impl fmt::Display for PoolGenerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}d{}", self.count, self.range)?;
        if let Some(op) = &self.op {
            write!(f, "{}", op)?;
        }
        write!(f, "")
    }
}

impl PoolGenerator {
    /// generate
    ///
    /// * Example
    ///
    /// ```
    /// use dice_nom::generators::{PoolGenerator, PoolOp};
    /// use dice_nom::results::Pool;
    /// use rand::prelude::*;
    /// let mut rng = rand::rng();
    /// let g = PoolGenerator{ count: 3, range: 6, op: Some(PoolOp::ExplodeEach(None)) };
    /// let pool = g.generate(&mut rng);
    /// assert!(pool.count() >= 3);
    /// ```
    pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Pool {
        let mut pool = Pool::new();
        for _ in 0..self.count {
            let val = Value::random(self.range, false, rng);
            pool.values.push(val);
            if let Some(op) = &self.op {
                op.apply_last(&mut pool, rng);
            }
        }

        if let Some(op) = &self.op {
            op.apply_all(&mut pool, rng);
        }

        pool
    }
}

/// Operations that can be applied to dice pools.
///
/// These operations modify how dice behave after being rolled, such as exploding
/// on maximum values, keeping only certain dice, or adding modifiers.
///
/// # Examples
///
/// ```rust
/// use dice_nom::roller;
/// use rand::prelude::*;
///
/// let mut rng = rand::rng();
///
/// // Exploding dice - reroll on max, once per pool
/// let exploding = roller(3, 6, Some("!"));
///
/// // Advantage - roll twice, keep higher
/// let advantage = roller(1, 20, Some("ADV"));
///
/// // Keep highest 3 of 4 dice
/// let drop_lowest = roller(4, 6, Some("^3"));
/// ```
#[derive(Debug, PartialEq, Clone)]
pub enum PoolOp {
    /// Explode: reroll if all dice are max (or >= threshold)
    Explode(Option<i32>),
    /// Explode until: keep rerolling while all dice are max
    ExplodeUntil(Option<i32>),
    /// Explode each: reroll each die that is max (or >= threshold)
    ExplodeEach(Option<i32>),
    /// Explode each until: keep rerolling each die while it's max
    ExplodeEachUntil(Option<i32>),
    /// Add the given value to each die
    AddEach(Option<i32>),
    /// Subtract the given value from each die
    SubEach(Option<i32>),
    /// Keep the middle N dice (drop highest and lowest)
    TakeMid(i32),
    /// Keep the lowest N dice
    TakeLow(i32),
    /// Keep the highest N dice
    TakeHigh(i32),
    /// Roll twice, keep the lower result
    Disadvantage,
    /// Roll twice, keep the higher result
    Advantage,
    /// Keep the largest group of matching dice values
    BestGroup,
}

impl fmt::Display for PoolOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PoolOp::Explode(n) => {
                if let Some(n) = *n {
                    if n > 1 {
                        write!(f, "!{}", n)
                    } else {
                        write!(f, "!")
                    }
                } else {
                    write!(f, "!")
                }
            }

            PoolOp::ExplodeUntil(n) => {
                if let Some(n) = *n {
                    if n > 1 {
                        write!(f, "!!{}", n)
                    } else {
                        write!(f, "!!")
                    }
                } else {
                    write!(f, "!!")
                }
            }

            PoolOp::ExplodeEach(n) => {
                if let Some(n) = *n {
                    if n > 1 {
                        write!(f, "*{}", n)
                    } else {
                        write!(f, "*")
                    }
                } else {
                    write!(f, "*")
                }
            }

            PoolOp::ExplodeEachUntil(n) => {
                if let Some(n) = *n {
                    if n > 1 {
                        write!(f, "**{}", n)
                    } else {
                        write!(f, "**")
                    }
                } else {
                    write!(f, "**")
                }
            }

            PoolOp::AddEach(n) => {
                if let Some(n) = n {
                    write!(f, "++{}", n)
                } else {
                    write!(f, "++")
                }
            }

            PoolOp::SubEach(n) => {
                if let Some(n) = n {
                    write!(f, "--{}", n)
                } else {
                    write!(f, "--")
                }
            }

            PoolOp::TakeMid(n) => write!(f, "~{}", n),
            PoolOp::TakeLow(n) => write!(f, "`{}", n),
            PoolOp::TakeHigh(n) => write!(f, "^{}", n),
            PoolOp::Disadvantage => write!(f, " DIS"),
            PoolOp::Advantage => write!(f, " ADV"),
            PoolOp::BestGroup => write!(f, "Y"),
        }
    }
}

impl PoolOp {
    /// apply_last modifies the pool based on the current operator.
    /// Some operators do not act on individual values and are skipped.
    ///
    /// * Examples
    ///
    /// ```
    /// use dice_nom::generators::PoolOp;
    /// use dice_nom::results::{ Value, Pool };
    /// use rand::prelude::*;
    /// let mut rng = rand::rng();
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6)]);
    /// PoolOp::ExplodeEach(None).apply_last(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 2); // value is max so it should "explode"
    /// assert_eq!(pool.bonus(), 1); // rerolled value is considered bonus
    /// assert_eq!(pool.kept(), 2); // all values are kept
    /// assert!(pool.sum() > 6); // new roll is added to existing roll
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6)]);
    /// PoolOp::ExplodeEachUntil(None).apply_last(&mut pool, &mut rng);
    /// assert!(pool.count() >= 2); // value is max so it should "explode"; may continue to explode
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(4)]);
    /// PoolOp::AddEach(Some(4)).apply_last(&mut pool, &mut rng);
    /// assert_eq!(pool.sum(), 8);
    /// assert_eq!(pool.values[0].modifier(), 4);
    /// assert_eq!(pool.values[0].sum(), 8);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(4)]);
    /// PoolOp::SubEach(Some(4)).apply_last(&mut pool, &mut rng);
    /// assert_eq!(pool.sum(), 0);
    /// assert_eq!(pool.values[0].modifier(), -4);
    /// assert_eq!(pool.values[0].sum(), 0);
    /// ```
    pub fn apply_last<R: Rng + ?Sized>(&self, pool: &mut Pool, rng: &mut R) {
        if pool.count() == 0 {
            return;
        }

        match self {
            PoolOp::ExplodeEach(n) => {
                let n = self.safe_n(n, pool.last_range());
                if pool.last_value() >= n {
                    let new_roll = Value::random(pool.last_range(), true, rng);
                    pool.values.push(new_roll);
                }
            }

            PoolOp::ExplodeEachUntil(n) => loop {
                let n = self.safe_n(n, pool.last_range());
                if pool.last_value() >= n {
                    let new_roll = Value::random(pool.last_range(), true, rng);
                    pool.values.push(new_roll);
                } else {
                    break;
                }
            },

            PoolOp::AddEach(n) => {
                let mut last = pool.values.pop().unwrap();
                let n = n.unwrap_or(1);
                last.set_modifier(n);
                pool.values.push(last);
            }

            PoolOp::SubEach(n) => {
                let mut last = pool.values.pop().unwrap();
                let n = -n.unwrap_or(1);
                last.set_modifier(n);
                pool.values.push(last);
            }
            _ => (),
        }
    }

    fn safe_n(&self, n: &Option<i32>, range: i32) -> i32 {
        match *n {
            Some(n) => {
                if n <= 1 || n > range {
                    range
                } else {
                    n
                }
            }
            None => range,
        }
    }

    /// apply_all modifies the pool based on the current operator
    /// that may modify the entire dice pool. Some operators only apply to
    /// individual values and are ignored here.
    ///
    /// * Examples
    ///
    /// ```
    /// use dice_nom::generators::PoolOp;
    /// use dice_nom::results::{ Value, Pool };
    /// use rand::prelude::*;
    /// let mut rng = rand::rng();
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5)]);
    /// PoolOp::Explode(Some(5)).apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 4);
    /// assert_eq!(pool.bonus(), 2);
    /// assert_eq!(pool.kept(), 4);
    /// assert!(pool.sum() >= 13);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5)]);
    /// PoolOp::ExplodeUntil(Some(5)).apply_all(&mut pool, &mut rng);
    /// assert!(pool.count() >= 4);
    /// assert!(pool.bonus() >= 2);
    /// assert!(pool.kept() >= 4);
    /// assert!(pool.sum() >= 13);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(1), Value::d6(4)]);
    /// PoolOp::TakeHigh(2).apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 4);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 2);
    /// assert_eq!(pool.sum(), 11);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(1), Value::d6(4)]);
    /// PoolOp::TakeLow(2).apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 4);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 2);
    /// assert_eq!(pool.sum(), 5);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(1), Value::d6(4)]);
    /// PoolOp::TakeMid(2).apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 4);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 2);
    /// assert_eq!(pool.sum(), 9);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(1)]);
    /// let old_sum = pool.sum();
    /// PoolOp::Advantage.apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 6);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 3);
    /// assert!(old_sum <= pool.sum());
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(1)]);
    /// let old_sum = pool.sum();
    /// PoolOp::Disadvantage.apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 6);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 3);
    /// assert!(old_sum >= pool.sum());
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(6), Value::d6(5), Value::d6(6), Value::d6(2), Value::d6(2)]);
    /// PoolOp::BestGroup.apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.count(), 5);
    /// assert_eq!(pool.bonus(), 0);
    /// assert_eq!(pool.kept(), 2);
    /// assert_eq!(pool.sum(), 12);
    ///
    /// let mut pool = Pool::new_with_values(vec![Value::d6(5), Value::d6(6), Value::d6(2), Value::d6(2)]);
    /// PoolOp::BestGroup.apply_all(&mut pool, &mut rng);
    /// assert_eq!(pool.kept(), 2);
    /// assert_eq!(pool.sum(), 4);
    /// ```
    pub fn apply_all<R: Rng + ?Sized>(&self, pool: &mut Pool, rng: &mut R) {
        let cnt = pool.count();
        if cnt == 0 {
            return;
        }

        match self {
            PoolOp::Explode(n) => {
                let range = pool.range();
                let n = self.safe_n(n, range);
                let explode = pool.values.iter().all(|v| v.value >= n);
                if explode {
                    for _ in 0..cnt {
                        let roll = Value::random(range, true, rng);
                        pool.values.push(roll);
                    }
                }
            }

            PoolOp::ExplodeUntil(n) => {
                let range = pool.range();
                let n = self.safe_n(n, range);
                let mut explode = pool.values.iter().all(|v| v.value >= n);
                while explode {
                    for _ in 0..cnt {
                        pool.values.push(Value::random(range, true, rng));
                        if pool.last_value() < n {
                            explode = false;
                        }
                    }
                }
            }

            PoolOp::TakeLow(take) => {
                let take = *take as usize;
                if cnt <= take {
                    return;
                }

                pool.values.sort_by(|a, b| a.value.cmp(&b.value));
                for idx in 0..cnt {
                    if idx >= take {
                        pool.values[idx].mark_discarded();
                    }
                }
            }

            PoolOp::TakeMid(take) => {
                let take = *take as usize;
                if cnt <= take {
                    return;
                }

                pool.values.sort_by(|a, b| b.value.cmp(&a.value));
                let skip_start = (cnt - take) / 2;
                let skip_end = skip_start + take;
                for idx in 0..cnt {
                    if idx < skip_start || idx >= skip_end {
                        pool.values[idx].mark_discarded();
                    }
                }
            }

            PoolOp::TakeHigh(take) => {
                let take = *take as usize;
                if cnt <= take {
                    return;
                }

                pool.values.sort_by(|a, b| b.value.cmp(&a.value));
                for idx in 0..cnt {
                    if idx >= take {
                        pool.values[idx].mark_discarded();
                    }
                }
            }

            PoolOp::Advantage => {
                let old = pool.sum();
                let range = pool.range();
                for _ in 0..cnt {
                    let roll = Value::random(range, false, rng);
                    pool.values.push(roll);
                }

                if pool.sum() > old * 2 {
                    for idx in 0..cnt {
                        pool.values[idx].mark_discarded();
                    }
                } else {
                    for idx in cnt..cnt * 2 {
                        pool.values[idx].mark_discarded();
                    }
                }
            }

            PoolOp::Disadvantage => {
                let old = pool.sum();
                let range = pool.range();
                for _ in 0..cnt {
                    let roll = Value::random(range, false, rng);
                    pool.values.push(roll);
                }

                if pool.sum() > old * 2 {
                    for idx in cnt..cnt * 2 {
                        pool.values[idx].mark_discarded();
                    }
                } else {
                    for idx in 0..cnt {
                        pool.values[idx].mark_discarded();
                    }
                }
            }

            PoolOp::BestGroup => {
                pool.values.sort_by(|a, b| b.value.cmp(&a.value));
                let mut last_val = 0;
                let mut max_val = 0;
                let mut max_run = 0;
                let mut curr_run = 0;
                let values = pool.values();
                for val in values.into_iter() {
                    if let Some(n) = val {
                        if last_val == n {
                            curr_run += 1;
                            if curr_run > max_run {
                                max_run = curr_run;
                                max_val = last_val;
                            }
                        } else {
                            last_val = n;
                            curr_run = 0;
                        }
                    }
                }

                for v in &mut pool.values {
                    if v.value != max_val {
                        v.mark_discarded();
                    }
                }
            }
            _ => (),
        }
    }
}