Skip to main content

rollpoly/
lib.rs

1// Copyright 2025 Ray Krueger
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(clippy::multiple_crate_versions)]
16
17//! `Rollpoly` - A comprehensive dice rolling library for tabletop gaming
18//!
19//! This library provides functionality to parse and evaluate dice notation
20//! strings and return the results as arrays of numbers.
21//!
22//! # Features
23//!
24//! - **Basic dice rolling**: Roll any number of dice with any number of sides (e.g., `4d10`, `d20`)
25//! - **Arithmetic operations**: Add, subtract, multiply, and divide dice results (e.g., `3d6 + 5`)
26//! - **Advanced mechanics**: Keep highest/lowest, drop highest, exploding dice, rerolling, success counting
27//! - **Safety limits**: Maximum of 25 dice per roll to prevent excessive resource usage
28//! - **Error handling**: Comprehensive error reporting for invalid input
29//! - **Random number generation**: Uses cryptographically secure random number generation
30//!
31//! # Quick Start
32//!
33//! ```
34//! use rollpoly::roll;
35//!
36//! // Roll 4 ten-sided dice and add 17
37//! let results = roll("4d10 + 17").unwrap();
38//! println!("Rolled: {:?}", results);
39//!
40//! // Handle errors gracefully
41//! match roll("invalid input") {
42//!     Ok(results) => println!("Results: {:?}", results),
43//!     Err(error) => println!("Error: {}", error),
44//! }
45//! ```
46//!
47//! # Supported Syntax
48//!
49//! The library supports the following dice notation syntax:
50//!
51//! - `4d10`: Roll a 10-sided die 4 times
52//! - `d20`: Roll a 20-sided die once (implicit count)
53//! - `2d6 + 3`: Roll 2d6 and add 3
54//! - `3d8 - 2`: Roll 3d8 and subtract 2
55//! - `1d4 * 3`: Roll 1d4 and multiply by 3
56//! - `5d6 / 2`: Roll 5d6 and divide by 2
57//! - `4d8 // 3`: Roll 4d8 and floor divide by 3
58//!
59//! # Safety Limits
60//!
61//! To prevent excessive resource usage and potential abuse, the library enforces
62//! a maximum limit of 25 dice per roll. Attempts to roll more than 25 dice will
63//! result in a [`DiceError::TooManyDice`] error.
64//!
65//! # Error Handling
66//!
67//! All functions return `Result` types with descriptive error messages.
68//! The [`DiceError`] type provides both the original input and a description
69//! of what went wrong.
70
71use thiserror::Error;
72
73mod evaluator;
74mod parser;
75
76use evaluator::evaluate;
77use parser::DiceParser;
78
79/// Error type for dice rolling operations
80#[derive(Error, Debug, Clone, PartialEq, Eq)]
81pub enum DiceError {
82    #[error("Empty dice notation provided")]
83    EmptyInput,
84
85    #[error("Invalid dice notation '{input}': {reason}")]
86    InvalidNotation { input: String, reason: String },
87
88    #[error("Invalid die size '{size}': must be a positive integer")]
89    InvalidDieSize { size: String },
90
91    #[error("Invalid dice count '{count}': must be a positive integer")]
92    InvalidDiceCount { count: String },
93
94    #[error("Invalid modifier '{modifier}': must be a valid integer")]
95    InvalidModifier { modifier: String },
96
97    #[error("Unsupported operator '{operator}' in dice notation '{input}'")]
98    UnsupportedOperator { operator: String, input: String },
99
100    #[error("Too many dice '{count}': maximum allowed is {max}")]
101    TooManyDice { count: usize, max: usize },
102}
103
104/// Rolls dice based on the provided dice notation string.
105///
106/// # Arguments
107///
108/// * `dice_notation` - A string slice containing the dice notation (e.g., "4d10 + 17")
109///
110/// # Returns
111///
112/// Returns a `Result<Vec<i32>, DiceError>` containing the individual dice roll results and any modifiers,
113/// or an error if the input is invalid.
114/// For basic rolls like "4d10 + 17", this would return the 4 individual die results
115/// plus the modifier as separate elements.
116///
117/// # Errors
118///
119/// This function will return an error if:
120/// * The dice notation is empty or contains only whitespace
121/// * The dice notation contains invalid characters or syntax
122/// * The dice notation is malformed (e.g., missing die size, invalid operators)
123/// * Numeric values in the notation cannot be parsed
124///
125/// # Examples
126///
127/// ```
128/// use rollpoly::roll;
129///
130/// let results = roll("2d6 + 3").unwrap();
131/// assert_eq!(results.len(), 3); // 2 dice + 1 modifier
132///
133/// // Invalid input returns an error
134/// let error = roll("invalid nonsense").unwrap_err();
135/// assert!(error.to_string().contains("invalid nonsense"));
136/// ```
137pub fn roll(dice_notation: &str) -> Result<Vec<i32>, DiceError> {
138    // Trim whitespace and check for empty input
139    let notation = dice_notation.trim();
140
141    if notation.is_empty() {
142        return Err(DiceError::EmptyInput);
143    }
144
145    // Parse the dice notation using the recursive descent parser
146    let mut parser = DiceParser::new(notation);
147    let expression = parser.parse().map_err(|e| match e {
148        // Pass through specific errors
149        e @ (DiceError::TooManyDice { .. }
150        | DiceError::InvalidDiceCount { .. }
151        | DiceError::InvalidDieSize { .. }) => e,
152        // Wrap other errors as InvalidNotation
153        _ => DiceError::InvalidNotation {
154            input: dice_notation.to_string(),
155            reason: e.to_string(),
156        },
157    })?;
158
159    // Evaluate the parsed expression
160    evaluate(&expression).map_err(|e| match e {
161        // Pass through specific errors
162        e @ (DiceError::TooManyDice { .. }
163        | DiceError::InvalidDiceCount { .. }
164        | DiceError::InvalidDieSize { .. }) => e,
165        // Wrap other errors as InvalidNotation
166        _ => DiceError::InvalidNotation {
167            input: dice_notation.to_string(),
168            reason: e.to_string(),
169        },
170    })
171}
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    // Test constants for reusable values
177    const MIN_DIE_VALUE: i32 = 1;
178    const D4_MAX: i32 = 4;
179    const D6_MAX: i32 = 6;
180    const D8_MAX: i32 = 8;
181    const D10_MAX: i32 = 10;
182    const D12_MAX: i32 = 12;
183    const D20_MAX: i32 = 20;
184    const D100_MAX: i32 = 100;
185
186    // Helper function for creating test data
187    fn assert_die_result_in_range(result: i32, min: i32, max: i32, die_type: &str) {
188        assert!(
189            result >= min && result <= max,
190            "Die result {} for {} should be between {} and {} inclusive",
191            result,
192            die_type,
193            min,
194            max
195        );
196    }
197
198    // Group tests by functionality
199    mod basic_dice_rolling {
200        use super::*;
201
202        #[test]
203        fn test_roll_single_d6_returns_one_result() {
204            // Arrange
205            let dice_notation = "1d6";
206
207            // Act
208            let result = roll(dice_notation).expect("Valid dice notation should not error");
209
210            // Assert
211            assert_eq!(
212                result.len(),
213                1,
214                "Single d6 should return exactly one result"
215            );
216            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D6_MAX, "d6");
217        }
218
219        #[test]
220        fn test_roll_multiple_dice_returns_correct_count() {
221            // Arrange
222            let dice_notation = "4d10";
223
224            // Act
225            let result = roll(dice_notation).expect("Valid dice notation should not error");
226
227            // Assert
228            assert_eq!(result.len(), 4, "4d10 should return exactly 4 results");
229            for (index, &die_result) in result.iter().enumerate() {
230                assert_die_result_in_range(
231                    die_result,
232                    MIN_DIE_VALUE,
233                    D10_MAX,
234                    &format!("d10 at index {}", index),
235                );
236            }
237        }
238
239        #[test]
240        fn test_roll_implicit_single_die_defaults_to_one() {
241            // Arrange
242            let dice_notation = "d20";
243
244            // Act
245            let result = roll(dice_notation).expect("Valid dice notation should not error");
246
247            // Assert
248            assert_eq!(
249                result.len(),
250                1,
251                "Implicit single die should return exactly one result"
252            );
253            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D20_MAX, "d20");
254        }
255    }
256
257    mod arithmetic_operations {
258        use super::*;
259
260        #[test]
261        fn test_roll_with_addition_includes_modifier() {
262            // Arrange
263            let dice_notation = "4d10 + 17";
264            let expected_modifier = 17;
265
266            // Act
267            let result = roll(dice_notation).expect("Valid dice notation should not error");
268
269            // Assert
270            assert_eq!(
271                result.len(),
272                5,
273                "4d10 + 17 should return 4 dice results + 1 modifier"
274            );
275
276            // Verify dice results are in valid range
277            for (index, &die_result) in result[0..4].iter().enumerate() {
278                assert_die_result_in_range(
279                    die_result,
280                    MIN_DIE_VALUE,
281                    D10_MAX,
282                    &format!("d10 at index {}", index),
283                );
284            }
285
286            // Verify modifier is correct
287            assert_eq!(
288                result[4], expected_modifier,
289                "Last element should be the addition modifier"
290            );
291        }
292
293        #[test]
294        fn test_roll_with_subtraction_includes_negative_modifier() {
295            // Arrange
296            let dice_notation = "2d20 - 3";
297            let expected_modifier = -3;
298
299            // Act
300            let result = roll(dice_notation).expect("Valid dice notation should not error");
301
302            // Assert
303            assert_eq!(
304                result.len(),
305                3,
306                "2d20 - 3 should return 2 dice results + 1 modifier"
307            );
308
309            // Verify dice results are in valid range
310            for (index, &die_result) in result[0..2].iter().enumerate() {
311                assert_die_result_in_range(
312                    die_result,
313                    MIN_DIE_VALUE,
314                    D20_MAX,
315                    &format!("d20 at index {}", index),
316                );
317            }
318
319            // Verify negative modifier is correct
320            assert_eq!(
321                result[2], expected_modifier,
322                "Last element should be the subtraction modifier"
323            );
324        }
325
326        #[test]
327        fn test_roll_with_multiplication_multiplies_sums() {
328            // Arrange
329            let dice_notation = "1d4 * 3";
330
331            // Act
332            let result = roll(dice_notation).expect("Valid dice notation should not error");
333
334            // Assert
335            assert_eq!(
336                result.len(),
337                1,
338                "1d4 * 3 should return 1 result (the product)"
339            );
340
341            // The result should be between 1*3=3 and 4*3=12
342            assert!(
343                result[0] >= 3 && result[0] <= 12,
344                "1d4 * 3 should be between 3 and 12, got {}",
345                result[0]
346            );
347
348            // Verify it's actually a multiple of 3
349            assert_eq!(
350                result[0] % 3,
351                0,
352                "Result should be divisible by 3, got {}",
353                result[0]
354            );
355        }
356
357        #[test]
358        fn test_roll_with_division_divides_sums() {
359            // Arrange
360            let dice_notation = "5d6 / 3";
361
362            // Act
363            let result = roll(dice_notation).expect("Valid dice notation should not error");
364
365            // Assert
366            assert_eq!(
367                result.len(),
368                1,
369                "5d6 / 3 should return 1 result (the quotient)"
370            );
371
372            // The result should be between (5*1)/3=1 and (5*6)/3=10
373            assert!(
374                result[0] >= 1 && result[0] <= 10,
375                "5d6 / 3 should be between 1 and 10, got {}",
376                result[0]
377            );
378        }
379
380        #[test]
381        fn test_roll_with_floor_division_floor_divides_sums() {
382            // Arrange
383            let dice_notation = "5d6 // 3";
384
385            // Act
386            let result = roll(dice_notation).expect("Valid dice notation should not error");
387
388            // Assert
389            assert_eq!(
390                result.len(),
391                1,
392                "5d6 // 3 should return 1 result (the floor quotient)"
393            );
394
395            // The result should be between floor((5*1)/3)=1 and floor((5*6)/3)=10
396            assert!(
397                result[0] >= 1 && result[0] <= 10,
398                "5d6 // 3 should be between 1 and 10, got {}",
399                result[0]
400            );
401        }
402
403        #[test]
404        fn test_roll_with_addition_no_spaces() {
405            // Arrange
406            let dice_notation = "2d12+2";
407            let expected_modifier = 2;
408
409            // Act
410            let result = roll(dice_notation).expect("Valid dice notation should not error");
411
412            // Assert
413            assert_eq!(
414                result.len(),
415                3,
416                "2d12+2 should return 2 dice results + 1 modifier"
417            );
418
419            // Verify dice results are in valid range
420            for (index, &die_result) in result[0..2].iter().enumerate() {
421                assert_die_result_in_range(
422                    die_result,
423                    MIN_DIE_VALUE,
424                    D12_MAX,
425                    &format!("d12 at index {}", index),
426                );
427            }
428
429            // Verify modifier is correct
430            assert_eq!(
431                result[2], expected_modifier,
432                "Last element should be the addition modifier"
433            );
434        }
435
436        #[test]
437        fn test_roll_with_subtraction_no_spaces() {
438            // Arrange
439            let dice_notation = "3d6-1";
440            let expected_modifier = -1;
441
442            // Act
443            let result = roll(dice_notation).expect("Valid dice notation should not error");
444
445            // Assert
446            assert_eq!(
447                result.len(),
448                4,
449                "3d6-1 should return 3 dice results + 1 modifier"
450            );
451
452            // Verify dice results are in valid range
453            for (index, &die_result) in result[0..3].iter().enumerate() {
454                assert_die_result_in_range(
455                    die_result,
456                    MIN_DIE_VALUE,
457                    D6_MAX,
458                    &format!("d6 at index {}", index),
459                );
460            }
461
462            // Verify negative modifier is correct
463            assert_eq!(
464                result[3], expected_modifier,
465                "Last element should be the subtraction modifier"
466            );
467        }
468
469        #[test]
470        fn test_spaced_vs_non_spaced_operators_consistency() {
471            // Test that spaced and non-spaced operators produce the same structure
472            let spaced_result = roll("2d6 + 3").expect("Spaced notation should work");
473            let non_spaced_result = roll("2d6+3").expect("Non-spaced notation should work");
474
475            // Both should have the same length and structure
476            assert_eq!(
477                spaced_result.len(),
478                non_spaced_result.len(),
479                "Spaced and non-spaced should have same result length"
480            );
481
482            // Last element should be the same (the modifier)
483            assert_eq!(
484                spaced_result.last(),
485                non_spaced_result.last(),
486                "Modifiers should be the same"
487            );
488        }
489
490        #[test]
491        fn test_keep_dice_with_arithmetic_no_spaces() {
492            // Arrange
493            let dice_notation = "4d6K3+2";
494            let expected_modifier = 2;
495
496            // Act
497            let result = roll(dice_notation).expect("Valid dice notation should not error");
498
499            // Assert
500            assert_eq!(
501                result.len(),
502                4,
503                "4d6K3+2 should return 3 kept dice + 1 modifier"
504            );
505
506            // Verify kept dice are in descending order
507            for i in 1..3 {
508                assert!(
509                    result[i - 1] >= result[i],
510                    "Kept dice should be in descending order: {:?}",
511                    result
512                );
513            }
514
515            // Verify modifier is correct
516            assert_eq!(
517                result[3], expected_modifier,
518                "Last element should be the addition modifier"
519            );
520        }
521
522        #[test]
523        fn test_dice_to_dice_operations_no_spaces() {
524            // Arrange
525            let dice_notation = "2d12+1d6";
526
527            // Act
528            let result = roll(dice_notation).expect("Valid dice notation should not error");
529
530            // Assert
531            assert_eq!(
532                result.len(),
533                3,
534                "2d12+1d6 should return 2d12 + 1d6 = 3 elements"
535            );
536
537            // Verify first two dice are d12 results
538            for (index, &die_result) in result[0..2].iter().enumerate() {
539                assert_die_result_in_range(
540                    die_result,
541                    MIN_DIE_VALUE,
542                    D12_MAX,
543                    &format!("d12 at index {}", index),
544                );
545            }
546
547            // Verify third element is d6 result
548            assert_die_result_in_range(result[2], MIN_DIE_VALUE, D6_MAX, "d6 result");
549        }
550
551        #[test]
552        fn test_dice_to_dice_spaced_vs_non_spaced_consistency() {
553            // Test that dice-to-dice operations work consistently with and without spaces
554            let spaced_result = roll("2d6 + 1d4").expect("Spaced dice-to-dice should work");
555            let non_spaced_result = roll("2d6+1d4").expect("Non-spaced dice-to-dice should work");
556
557            // Both should have the same structure
558            assert_eq!(
559                spaced_result.len(),
560                non_spaced_result.len(),
561                "Spaced and non-spaced dice-to-dice should have same result length"
562            );
563
564            // Should have 2d6 + 1d4 = 3 elements
565            assert_eq!(spaced_result.len(), 3, "Should have 2d6 + 1d4 = 3 elements");
566        }
567    }
568
569    mod die_size_variations {
570        use super::*;
571
572        #[test]
573        fn test_roll_d4_returns_valid_range() {
574            // Arrange
575            let dice_notation = "1d4";
576
577            // Act
578            let result = roll(dice_notation).expect("Valid dice notation should not error");
579
580            // Assert
581            assert_eq!(result.len(), 1);
582            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D4_MAX, "d4");
583        }
584
585        #[test]
586        fn test_roll_d6_returns_valid_range() {
587            // Arrange
588            let dice_notation = "1d6";
589
590            // Act
591            let result = roll(dice_notation).expect("Valid dice notation should not error");
592
593            // Assert
594            assert_eq!(result.len(), 1);
595            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D6_MAX, "d6");
596        }
597
598        #[test]
599        fn test_roll_d8_returns_valid_range() {
600            // Arrange
601            let dice_notation = "1d8";
602
603            // Act
604            let result = roll(dice_notation).expect("Valid dice notation should not error");
605
606            // Assert
607            assert_eq!(result.len(), 1);
608            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D8_MAX, "d8");
609        }
610
611        #[test]
612        fn test_roll_d10_returns_valid_range() {
613            // Arrange
614            let dice_notation = "1d10";
615
616            // Act
617            let result = roll(dice_notation).expect("Valid dice notation should not error");
618
619            // Assert
620            assert_eq!(result.len(), 1);
621            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D10_MAX, "d10");
622        }
623
624        #[test]
625        fn test_roll_d12_returns_valid_range() {
626            // Arrange
627            let dice_notation = "1d12";
628
629            // Act
630            let result = roll(dice_notation).expect("Valid dice notation should not error");
631
632            // Assert
633            assert_eq!(result.len(), 1);
634            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D12_MAX, "d12");
635        }
636
637        #[test]
638        fn test_roll_d20_returns_valid_range() {
639            // Arrange
640            let dice_notation = "1d20";
641
642            // Act
643            let result = roll(dice_notation).expect("Valid dice notation should not error");
644
645            // Assert
646            assert_eq!(result.len(), 1);
647            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D20_MAX, "d20");
648        }
649
650        #[test]
651        fn test_roll_d100_returns_valid_range() {
652            // Arrange
653            let dice_notation = "1d100";
654
655            // Act
656            let result = roll(dice_notation).expect("Valid dice notation should not error");
657
658            // Assert
659            assert_eq!(result.len(), 1);
660            assert_die_result_in_range(result[0], MIN_DIE_VALUE, D100_MAX, "d100");
661        }
662    }
663
664    mod dice_count_variations {
665        use super::*;
666
667        #[test]
668        fn test_roll_two_dice_returns_two_results() {
669            // Arrange
670            let dice_notation = "2d6";
671
672            // Act
673            let result = roll(dice_notation).expect("Valid dice notation should not error");
674
675            // Assert
676            assert_eq!(result.len(), 2, "2d6 should return exactly 2 results");
677            for (index, &die_result) in result.iter().enumerate() {
678                assert_die_result_in_range(
679                    die_result,
680                    MIN_DIE_VALUE,
681                    D6_MAX,
682                    &format!("d6 at index {}", index),
683                );
684            }
685        }
686
687        #[test]
688        fn test_roll_three_dice_returns_three_results() {
689            // Arrange
690            let dice_notation = "3d8";
691
692            // Act
693            let result = roll(dice_notation).expect("Valid dice notation should not error");
694
695            // Assert
696            assert_eq!(result.len(), 3, "3d8 should return exactly 3 results");
697            for (index, &die_result) in result.iter().enumerate() {
698                assert_die_result_in_range(
699                    die_result,
700                    MIN_DIE_VALUE,
701                    D8_MAX,
702                    &format!("d8 at index {}", index),
703                );
704            }
705        }
706
707        #[test]
708        fn test_roll_ten_dice_returns_ten_results() {
709            // Arrange
710            let dice_notation = "10d10";
711
712            // Act
713            let result = roll(dice_notation).expect("Valid dice notation should not error");
714
715            // Assert
716            assert_eq!(result.len(), 10, "10d10 should return exactly 10 results");
717            for (index, &die_result) in result.iter().enumerate() {
718                assert_die_result_in_range(
719                    die_result,
720                    MIN_DIE_VALUE,
721                    D10_MAX,
722                    &format!("d10 at index {}", index),
723                );
724            }
725        }
726    }
727
728    mod randomness_and_edge_cases {
729        use super::*;
730        use std::collections::HashSet;
731
732        #[test]
733        fn test_roll_produces_varied_results_over_multiple_calls() {
734            // Arrange
735            let dice_notation = "1d20";
736            let mut results = HashSet::new();
737            let iterations = 50;
738
739            // Act
740            for _ in 0..iterations {
741                let roll_result =
742                    roll(dice_notation).expect("Valid dice notation should not error");
743                results.insert(roll_result[0]);
744            }
745
746            // Assert
747            assert!(
748                results.len() > 5,
749                "Expected varied random results over {} iterations, got only {} unique values",
750                iterations,
751                results.len()
752            );
753        }
754
755        #[test]
756        fn test_roll_with_whitespace_handles_spaces_correctly() {
757            // Arrange
758            let dice_notation = " 2d6 + 5 ";
759            let expected_modifier = 5;
760
761            // Act
762            let result = roll(dice_notation).expect("Valid dice notation should not error");
763
764            // Assert
765            assert_eq!(result.len(), 3, "Whitespace should not affect parsing");
766            assert_eq!(
767                result[2], expected_modifier,
768                "Modifier should be parsed correctly despite whitespace"
769            );
770        }
771
772        #[test]
773        fn test_roll_with_spaces_in_dice_notation() {
774            // Test spaces within dice notation components
775            let test_cases = vec![
776                ("2 d 6", "2d6"),             // Spaces around 'd'
777                ("2d 6", "2d6"),              // Space after 'd'
778                ("2 d6", "2d6"),              // Space before 'd'
779                ("4 d 6 K 3", "4d6K3"),       // Spaces in keep notation
780                ("3 d 8 + 2", "3d8+2"),       // Spaces with arithmetic
781                ("d 20", "d20"),              // Space in implicit single die
782                ("2 d 6 + 1 d 4", "2d6+1d4"), // Spaces in dice-to-dice
783            ];
784
785            for (spaced, compact) in test_cases {
786                let spaced_result = roll(spaced);
787                let compact_result = roll(compact);
788
789                assert!(
790                    spaced_result.is_ok(),
791                    "Spaced notation '{}' should parse successfully",
792                    spaced
793                );
794                assert!(
795                    compact_result.is_ok(),
796                    "Compact notation '{}' should parse successfully",
797                    compact
798                );
799
800                let spaced_results = spaced_result.unwrap();
801                let compact_results = compact_result.unwrap();
802
803                assert_eq!(
804                    spaced_results.len(),
805                    compact_results.len(),
806                    "Spaced '{}' and compact '{}' should have same result length",
807                    spaced,
808                    compact
809                );
810            }
811        }
812
813        #[test]
814        fn test_roll_stays_within_bounds_over_many_iterations() {
815            // Arrange
816            let dice_notation = "1d6";
817            let iterations = 100; // Reduced from 1000 for faster tests
818
819            // Act & Assert
820            for iteration in 0..iterations {
821                let result = roll(dice_notation).expect("Valid dice notation should not error");
822                assert_eq!(result.len(), 1, "Should always return exactly one result");
823                assert_die_result_in_range(
824                    result[0],
825                    MIN_DIE_VALUE,
826                    D6_MAX,
827                    &format!("d6 at iteration {}", iteration),
828                );
829            }
830        }
831    }
832
833    mod keep_dice_operations {
834        use super::*;
835
836        #[test]
837        fn test_keep_highest_single_die() {
838            // Arrange
839            let notation = "4d6K";
840
841            // Act
842            let result = roll(notation);
843
844            // Assert
845            assert!(result.is_ok(), "Keep highest should work");
846            let results = result.unwrap();
847            assert_eq!(results.len(), 1, "Should keep only 1 die");
848            assert!(
849                results[0] >= 1 && results[0] <= 6,
850                "Result should be valid die roll"
851            );
852        }
853
854        #[test]
855        fn test_keep_highest_multiple_dice() {
856            // Arrange
857            let notation = "7d12K3";
858
859            // Act
860            let result = roll(notation);
861
862            // Assert
863            assert!(result.is_ok(), "Keep highest multiple should work");
864            let results = result.unwrap();
865            assert_eq!(results.len(), 3, "Should keep exactly 3 dice");
866
867            // Results should be in descending order (highest first)
868            for i in 1..results.len() {
869                assert!(
870                    results[i - 1] >= results[i],
871                    "Results should be in descending order: {:?}",
872                    results
873                );
874            }
875
876            // All results should be valid
877            for &result in &results {
878                assert!(
879                    result >= 1 && result <= 12,
880                    "All results should be valid d12 rolls"
881                );
882            }
883        }
884
885        #[test]
886        fn test_keep_lowest_single_die() {
887            // Arrange
888            let notation = "3d6k";
889
890            // Act
891            let result = roll(notation);
892
893            // Assert
894            assert!(result.is_ok(), "Keep lowest should work");
895            let results = result.unwrap();
896            assert_eq!(results.len(), 1, "Should keep only 1 die");
897            assert!(
898                results[0] >= 1 && results[0] <= 6,
899                "Result should be valid die roll"
900            );
901        }
902
903        #[test]
904        fn test_keep_lowest_multiple_dice() {
905            // Arrange
906            let notation = "5d6k3";
907
908            // Act
909            let result = roll(notation);
910
911            // Assert
912            assert!(result.is_ok(), "Keep lowest multiple should work");
913            let results = result.unwrap();
914            assert_eq!(results.len(), 3, "Should keep exactly 3 dice");
915
916            // Results should be in ascending order (lowest first)
917            for i in 1..results.len() {
918                assert!(
919                    results[i - 1] <= results[i],
920                    "Results should be in ascending order: {:?}",
921                    results
922                );
923            }
924
925            // All results should be valid
926            for &result in &results {
927                assert!(
928                    result >= 1 && result <= 6,
929                    "All results should be valid d6 rolls"
930                );
931            }
932        }
933
934        #[test]
935        fn test_keep_highest_with_arithmetic() {
936            // Arrange
937            let notation = "4d6K2 + 5";
938
939            // Act
940            let result = roll(notation);
941
942            // Assert
943            assert!(result.is_ok(), "Keep highest with arithmetic should work");
944            let results = result.unwrap();
945            assert_eq!(results.len(), 3, "Should have 2 kept dice + 1 modifier");
946
947            // Last element should be the modifier
948            assert_eq!(results[2], 5, "Last element should be the +5 modifier");
949
950            // First two should be dice results in descending order
951            assert!(
952                results[0] >= results[1],
953                "Kept dice should be in descending order: {:?}",
954                results
955            );
956        }
957
958        #[test]
959        fn test_disadvantage_roll() {
960            // Arrange - This is a common D&D 5e disadvantage roll
961            let notation = "2d20k";
962
963            // Act
964            let result = roll(notation);
965
966            // Assert
967            assert!(result.is_ok(), "Disadvantage roll should work");
968            let results = result.unwrap();
969            assert_eq!(results.len(), 1, "Should keep only the lowest die");
970            assert!(
971                results[0] >= 1 && results[0] <= 20,
972                "Result should be valid d20 roll"
973            );
974        }
975
976        #[test]
977        fn test_advantage_roll() {
978            // Arrange - This is a common D&D 5e advantage roll
979            let notation = "2d20K";
980
981            // Act
982            let result = roll(notation);
983
984            // Assert
985            assert!(result.is_ok(), "Advantage roll should work");
986            let results = result.unwrap();
987            assert_eq!(results.len(), 1, "Should keep only the highest die");
988            assert!(
989                results[0] >= 1 && results[0] <= 20,
990                "Result should be valid d20 roll"
991            );
992        }
993    }
994
995    mod drop_dice_operations {
996        use super::*;
997
998        #[test]
999        fn test_drop_highest_single_die() {
1000            // Arrange
1001            let notation = "6d8X";
1002
1003            // Act
1004            let result = roll(notation);
1005
1006            // Assert
1007            assert!(result.is_ok(), "Drop highest should work");
1008            let results = result.unwrap();
1009            assert_eq!(results.len(), 5, "Should keep 5 dice after dropping 1");
1010
1011            // Results should be in ascending order (lowest first, highest dropped)
1012            for i in 1..results.len() {
1013                assert!(
1014                    results[i - 1] <= results[i],
1015                    "Results should be in ascending order: {:?}",
1016                    results
1017                );
1018            }
1019
1020            // All results should be valid d8 rolls
1021            for &result in &results {
1022                assert!(
1023                    result >= 1 && result <= 8,
1024                    "All results should be valid d8 rolls"
1025                );
1026            }
1027        }
1028
1029        #[test]
1030        fn test_drop_highest_multiple_dice() {
1031            // Arrange
1032            let notation = "5d10X3";
1033
1034            // Act
1035            let result = roll(notation);
1036
1037            // Assert
1038            assert!(result.is_ok(), "Drop highest multiple should work");
1039            let results = result.unwrap();
1040            assert_eq!(results.len(), 2, "Should keep 2 dice after dropping 3");
1041
1042            // Results should be in ascending order (lowest kept)
1043            for i in 1..results.len() {
1044                assert!(
1045                    results[i - 1] <= results[i],
1046                    "Results should be in ascending order: {:?}",
1047                    results
1048                );
1049            }
1050
1051            // All results should be valid d10 rolls
1052            for &result in &results {
1053                assert!(
1054                    result >= 1 && result <= 10,
1055                    "All results should be valid d10 rolls"
1056                );
1057            }
1058        }
1059
1060        #[test]
1061        fn test_drop_highest_with_arithmetic() {
1062            // Arrange
1063            let notation = "6d6X2 + 5";
1064
1065            // Act
1066            let result = roll(notation);
1067
1068            // Assert
1069            assert!(result.is_ok(), "Drop highest with arithmetic should work");
1070            let results = result.unwrap();
1071            assert_eq!(results.len(), 5, "Should have 4 kept dice + 1 modifier");
1072
1073            // Last element should be the modifier
1074            assert_eq!(results[4], 5, "Last element should be the +5 modifier");
1075
1076            // First four should be dice results in ascending order (lowest kept)
1077            for i in 1..4 {
1078                assert!(
1079                    results[i - 1] <= results[i],
1080                    "Kept dice should be in ascending order: {:?}",
1081                    results
1082                );
1083            }
1084        }
1085
1086        #[test]
1087        fn test_drop_consistency_over_multiple_rolls() {
1088            // Arrange
1089            let notation = "8d6X3";
1090
1091            // Act & Assert - Test multiple times to ensure consistency
1092            for _ in 0..20 {
1093                let result = roll(notation);
1094                assert!(result.is_ok(), "Drop should work consistently");
1095
1096                let results = result.unwrap();
1097                assert_eq!(results.len(), 5, "Should always keep exactly 5 dice");
1098
1099                // Should be in ascending order (lowest kept)
1100                for i in 1..results.len() {
1101                    assert!(
1102                        results[i - 1] <= results[i],
1103                        "Results should always be in ascending order: {:?}",
1104                        results
1105                    );
1106                }
1107
1108                // All should be valid d6 rolls
1109                for &result in &results {
1110                    assert!(
1111                        result >= 1 && result <= 6,
1112                        "All results should be valid d6 rolls"
1113                    );
1114                }
1115            }
1116        }
1117    }
1118
1119    mod reroll_dice_operations {
1120        use super::*;
1121
1122        #[test]
1123        fn test_reroll_once_on_value() {
1124            // This test can't guarantee the rerolled value isn't the same.
1125            // We are just testing that it runs without error.
1126            for _ in 0..100 {
1127                let result = roll("1d6r1").unwrap();
1128                assert_eq!(result.len(), 1);
1129            }
1130        }
1131
1132        #[test]
1133        fn test_reroll_continuous_on_value() {
1134            for _ in 0..100 {
1135                let result = roll("1d6R1").unwrap();
1136                assert_eq!(result.len(), 1);
1137                assert_ne!(result[0], 1);
1138            }
1139        }
1140
1141        #[test]
1142        fn test_reroll_once_less_than() {
1143            // This test can't guarantee the rerolled value is not less than 3.
1144            // We are just testing that it runs without error.
1145            for _ in 0..100 {
1146                let result = roll("1d6r<3").unwrap();
1147                assert_eq!(result.len(), 1);
1148            }
1149        }
1150
1151        #[test]
1152        fn test_reroll_continuous_less_than() {
1153            for _ in 0..100 {
1154                let result = roll("1d6R<3").unwrap();
1155                assert_eq!(result.len(), 1);
1156                assert!(result[0] >= 3);
1157            }
1158        }
1159    }
1160
1161    mod dice_to_dice_operations {
1162        use super::*;
1163
1164        #[test]
1165        fn test_dice_plus_dice() {
1166            // Arrange
1167            let notation = "2d6 + 1d4";
1168
1169            // Act
1170            let result = roll(notation);
1171
1172            // Assert
1173            assert!(result.is_ok(), "Dice + dice should work");
1174            let results = result.unwrap();
1175            assert_eq!(results.len(), 3, "Should have 2d6 + 1d4 = 3 dice");
1176
1177            // First two should be d6 results
1178            for i in 0..2 {
1179                assert!(
1180                    results[i] >= 1 && results[i] <= 6,
1181                    "d6 results should be 1-6"
1182                );
1183            }
1184
1185            // Last should be d4 result
1186            assert!(
1187                results[2] >= 1 && results[2] <= 4,
1188                "d4 result should be 1-4"
1189            );
1190        }
1191
1192        #[test]
1193        fn test_dice_minus_dice() {
1194            // Arrange
1195            let notation = "2d12 - 1d6";
1196
1197            // Act
1198            let result = roll(notation);
1199
1200            // Assert
1201            assert!(result.is_ok(), "Dice - dice should work");
1202            let results = result.unwrap();
1203            assert_eq!(results.len(), 3, "Should have 2d12 - 1d6 = 3 values");
1204
1205            // First two should be d12 results
1206            for i in 0..2 {
1207                assert!(
1208                    results[i] >= 1 && results[i] <= 12,
1209                    "d12 results should be 1-12"
1210                );
1211            }
1212
1213            // Last should be negative d6 result
1214            assert!(
1215                results[2] >= -6 && results[2] <= -1,
1216                "Subtracted d6 should be -6 to -1"
1217            );
1218        }
1219
1220        #[test]
1221        fn test_daggerheart_advantage_roll() {
1222            // Arrange - Daggerheart with Advantage
1223            let notation = "2d12 + 1d6";
1224
1225            // Act
1226            let result = roll(notation);
1227
1228            // Assert
1229            assert!(result.is_ok(), "Daggerheart Advantage roll should work");
1230            let results = result.unwrap();
1231            assert_eq!(results.len(), 3, "Should have 2d12 + 1d6 = 3 dice");
1232
1233            // Check ranges
1234            let sum: i32 = results.iter().sum();
1235            assert!(
1236                sum >= 3 && sum <= 30,
1237                "Daggerheart Advantage sum should be 3-30"
1238            );
1239        }
1240
1241        #[test]
1242        fn test_daggerheart_disadvantage_roll() {
1243            // Arrange - Daggerheart with Disadvantage
1244            let notation = "2d12 - 1d6";
1245
1246            // Act
1247            let result = roll(notation);
1248
1249            // Assert
1250            assert!(result.is_ok(), "Daggerheart Disadvantage roll should work");
1251            let results = result.unwrap();
1252            assert_eq!(results.len(), 3, "Should have 2d12 - 1d6 = 3 values");
1253
1254            // Check ranges: 2d12 (2-24) - 1d6 (1-6) = -4 to 23
1255            let sum: i32 = results.iter().sum();
1256            assert!(
1257                sum >= -4 && sum <= 23,
1258                "Daggerheart Disadvantage sum should be -4 to 23, got {}",
1259                sum
1260            );
1261        }
1262
1263        #[test]
1264        fn test_keep_dice_plus_dice() {
1265            // Arrange
1266            let notation = "4d6K3 + 1d4";
1267
1268            // Act
1269            let result = roll(notation);
1270
1271            // Assert
1272            assert!(result.is_ok(), "Keep dice + dice should work");
1273            let results = result.unwrap();
1274            assert_eq!(results.len(), 4, "Should have 3 kept d6 + 1d4 = 4 dice");
1275
1276            // First three should be d6 results in descending order
1277            for i in 0..3 {
1278                assert!(
1279                    results[i] >= 1 && results[i] <= 6,
1280                    "Kept d6 results should be 1-6"
1281                );
1282            }
1283            for i in 1..3 {
1284                assert!(
1285                    results[i - 1] >= results[i],
1286                    "Kept dice should be in descending order"
1287                );
1288            }
1289
1290            // Last should be d4 result
1291            assert!(
1292                results[3] >= 1 && results[3] <= 4,
1293                "d4 result should be 1-4"
1294            );
1295        }
1296
1297        #[test]
1298        fn test_dice_to_dice_consistency() {
1299            // Arrange
1300            let notation = "3d6 + 2d4";
1301
1302            // Act & Assert - Test multiple times to ensure consistency
1303            for _ in 0..20 {
1304                let result = roll(notation);
1305                assert!(result.is_ok(), "Dice + dice should work consistently");
1306
1307                let results = result.unwrap();
1308                assert_eq!(results.len(), 5, "Should always have 5 dice");
1309
1310                // Check ranges
1311                for i in 0..3 {
1312                    assert!(
1313                        results[i] >= 1 && results[i] <= 6,
1314                        "d6 results should be 1-6"
1315                    );
1316                }
1317                for i in 3..5 {
1318                    assert!(
1319                        results[i] >= 1 && results[i] <= 4,
1320                        "d4 results should be 1-4"
1321                    );
1322                }
1323
1324                let sum: i32 = results.iter().sum();
1325                assert!(sum >= 5 && sum <= 26, "Sum should be in valid range");
1326            }
1327        }
1328    }
1329
1330    mod success_counting_operations {
1331        use super::*;
1332
1333        #[test]
1334        fn test_count_successes_greater_than() {
1335            // Arrange
1336            let notation = "5d10>7";
1337
1338            // Act
1339            let result = roll(notation);
1340
1341            // Assert
1342            assert!(result.is_ok(), "Success counting should work");
1343            let results = result.unwrap();
1344            assert_eq!(results.len(), 1, "Should return single success count");
1345
1346            // Success count should be between 0 and 5
1347            let success_count = results[0];
1348            assert!(
1349                success_count >= 0 && success_count <= 5,
1350                "Success count should be 0-5, got {}",
1351                success_count
1352            );
1353        }
1354
1355        #[test]
1356        fn test_count_successes_less_than() {
1357            // Arrange
1358            let notation = "8d6<3";
1359
1360            // Act
1361            let result = roll(notation);
1362
1363            // Assert
1364            assert!(result.is_ok(), "Success counting with < should work");
1365            let results = result.unwrap();
1366            assert_eq!(results.len(), 1, "Should return single success count");
1367
1368            // Success count should be between 0 and 8
1369            let success_count = results[0];
1370            assert!(
1371                success_count >= 0 && success_count <= 8,
1372                "Success count should be 0-8, got {}",
1373                success_count
1374            );
1375        }
1376
1377        #[test]
1378        fn test_world_of_darkness_style() {
1379            // Arrange - World of Darkness typically uses d10>7
1380            let notation = "5d10>7";
1381
1382            // Act
1383            let result = roll(notation);
1384
1385            // Assert
1386            assert!(result.is_ok(), "World of Darkness style should work");
1387            let results = result.unwrap();
1388            assert_eq!(results.len(), 1, "Should return single success count");
1389
1390            let success_count = results[0];
1391            assert!(
1392                success_count >= 0 && success_count <= 5,
1393                "Success count should be valid range"
1394            );
1395        }
1396
1397        #[test]
1398        fn test_shadowrun_style() {
1399            // Arrange - Shadowrun typically uses d6>4
1400            let notation = "10d6>4";
1401
1402            // Act
1403            let result = roll(notation);
1404
1405            // Assert
1406            assert!(result.is_ok(), "Shadowrun style should work");
1407            let results = result.unwrap();
1408            assert_eq!(results.len(), 1, "Should return single success count");
1409
1410            let success_count = results[0];
1411            assert!(
1412                success_count >= 0 && success_count <= 10,
1413                "Success count should be 0-10, got {}",
1414                success_count
1415            );
1416        }
1417
1418        #[test]
1419        fn test_success_failure_counting() {
1420            // Arrange
1421            let notation = "10d10>6f<3";
1422
1423            // Act
1424            let result = roll(notation);
1425
1426            // Assert
1427            assert!(result.is_ok(), "Success/failure counting should work");
1428            let results = result.unwrap();
1429            assert_eq!(results.len(), 1, "Should return single net success count");
1430
1431            // Net successes can be negative due to failures
1432            let net_successes = results[0];
1433            assert!(
1434                net_successes >= -10 && net_successes <= 10,
1435                "Net successes should be -10 to 10, got {}",
1436                net_successes
1437            );
1438        }
1439
1440        #[test]
1441        fn test_success_failure_opposite_conditions() {
1442            // Arrange
1443            let notation = "4d20<5f>19";
1444
1445            // Act
1446            let result = roll(notation);
1447
1448            // Assert
1449            assert!(result.is_ok(), "Success < failure > should work");
1450            let results = result.unwrap();
1451            assert_eq!(results.len(), 1, "Should return single net success count");
1452
1453            let net_successes = results[0];
1454            assert!(
1455                net_successes >= -4 && net_successes <= 4,
1456                "Net successes should be -4 to 4, got {}",
1457                net_successes
1458            );
1459        }
1460
1461        #[test]
1462        fn test_success_counting_consistency() {
1463            // Arrange
1464            let notation = "6d6>4";
1465
1466            // Act & Assert - Test multiple times to ensure consistency
1467            for _ in 0..20 {
1468                let result = roll(notation);
1469                assert!(result.is_ok(), "Success counting should work consistently");
1470
1471                let results = result.unwrap();
1472                assert_eq!(
1473                    results.len(),
1474                    1,
1475                    "Should always return single success count"
1476                );
1477
1478                let success_count = results[0];
1479                assert!(
1480                    success_count >= 0 && success_count <= 6,
1481                    "Success count should always be 0-6"
1482                );
1483            }
1484        }
1485
1486        #[test]
1487        fn test_implicit_single_die_success_counting() {
1488            // Arrange
1489            let notation = "d20>15";
1490
1491            // Act
1492            let result = roll(notation);
1493
1494            // Assert
1495            assert!(
1496                result.is_ok(),
1497                "Implicit single die success counting should work"
1498            );
1499            let results = result.unwrap();
1500            assert_eq!(results.len(), 1, "Should return single success count");
1501
1502            let success_count = results[0];
1503            assert!(
1504                success_count >= 0 && success_count <= 1,
1505                "Single die success count should be 0 or 1"
1506            );
1507        }
1508    }
1509
1510    mod exploding_dice_operations {
1511        use super::*;
1512
1513        #[test]
1514        fn test_simple_exploding_dice() {
1515            // Arrange
1516            let notation = "2d6!";
1517
1518            // Act
1519            let result = roll(notation);
1520
1521            // Assert
1522            assert!(result.is_ok(), "Simple exploding dice should work");
1523            let results = result.unwrap();
1524
1525            // Should have at least 2 dice (the original rolls)
1526            assert!(results.len() >= 2, "Should have at least 2 dice results");
1527
1528            // All results should be valid d6 rolls
1529            for &roll in &results {
1530                assert!(
1531                    roll >= 1 && roll <= 6,
1532                    "All rolls should be 1-6, got {}",
1533                    roll
1534                );
1535            }
1536
1537            // Total should be at least 2 (minimum possible)
1538            let total: i32 = results.iter().sum();
1539            assert!(total >= 2, "Total should be at least 2");
1540        }
1541
1542        #[test]
1543        fn test_exploding_on_specific_number() {
1544            // Arrange
1545            let notation = "3d10!5";
1546
1547            // Act
1548            let result = roll(notation);
1549
1550            // Assert
1551            assert!(result.is_ok(), "Exploding on specific number should work");
1552            let results = result.unwrap();
1553
1554            // Should have at least 3 dice (the original rolls)
1555            assert!(results.len() >= 3, "Should have at least 3 dice results");
1556
1557            // All results should be valid d10 rolls
1558            for &roll in &results {
1559                assert!(
1560                    roll >= 1 && roll <= 10,
1561                    "All rolls should be 1-10, got {}",
1562                    roll
1563                );
1564            }
1565        }
1566
1567        #[test]
1568        fn test_exploding_greater_than() {
1569            // Arrange
1570            let notation = "d20!>15";
1571
1572            // Act
1573            let result = roll(notation);
1574
1575            // Assert
1576            assert!(result.is_ok(), "Exploding greater than should work");
1577            let results = result.unwrap();
1578
1579            // Should have at least 1 die
1580            assert!(results.len() >= 1, "Should have at least 1 die result");
1581
1582            // All results should be valid d20 rolls
1583            for &roll in &results {
1584                assert!(
1585                    roll >= 1 && roll <= 20,
1586                    "All rolls should be 1-20, got {}",
1587                    roll
1588                );
1589            }
1590        }
1591
1592        #[test]
1593        fn test_exploding_less_than() {
1594            // Arrange
1595            let notation = "2d12!<3";
1596
1597            // Act
1598            let result = roll(notation);
1599
1600            // Assert
1601            assert!(result.is_ok(), "Exploding less than should work");
1602            let results = result.unwrap();
1603
1604            // Should have at least 2 dice
1605            assert!(results.len() >= 2, "Should have at least 2 dice results");
1606
1607            // All results should be valid d12 rolls
1608            for &roll in &results {
1609                assert!(
1610                    roll >= 1 && roll <= 12,
1611                    "All rolls should be 1-12, got {}",
1612                    roll
1613                );
1614            }
1615        }
1616
1617        #[test]
1618        fn test_implicit_single_die_exploding() {
1619            // Arrange
1620            let notation = "d6!";
1621
1622            // Act
1623            let result = roll(notation);
1624
1625            // Assert
1626            assert!(result.is_ok(), "Implicit single die exploding should work");
1627            let results = result.unwrap();
1628
1629            // Should have at least 1 die
1630            assert!(results.len() >= 1, "Should have at least 1 die result");
1631
1632            // All results should be valid d6 rolls
1633            for &roll in &results {
1634                assert!(
1635                    roll >= 1 && roll <= 6,
1636                    "All rolls should be 1-6, got {}",
1637                    roll
1638                );
1639            }
1640        }
1641
1642        #[test]
1643        fn test_exploding_dice_consistency() {
1644            // Arrange
1645            let notation = "2d8!";
1646
1647            // Act & Assert - Test multiple times to ensure consistency
1648            for _ in 0..20 {
1649                let result = roll(notation);
1650                assert!(result.is_ok(), "Exploding dice should work consistently");
1651
1652                let results = result.unwrap();
1653                assert!(results.len() >= 2, "Should always have at least 2 dice");
1654
1655                // All results should be valid d8 rolls
1656                for &roll in &results {
1657                    assert!(roll >= 1 && roll <= 8, "All rolls should be 1-8");
1658                }
1659
1660                // Total should be reasonable (at least 2, but not impossibly high)
1661                let total: i32 = results.iter().sum();
1662                assert!(
1663                    total >= 2 && total <= 200,
1664                    "Total should be reasonable range"
1665                );
1666            }
1667        }
1668
1669        #[test]
1670        fn test_shadowrun_exploding_sixes() {
1671            // Arrange - Shadowrun style: d6 exploding on 6
1672            let notation = "4d6!6";
1673
1674            // Act
1675            let result = roll(notation);
1676
1677            // Assert
1678            assert!(result.is_ok(), "Shadowrun exploding sixes should work");
1679            let results = result.unwrap();
1680
1681            // Should have at least 4 dice
1682            assert!(results.len() >= 4, "Should have at least 4 dice results");
1683
1684            // All results should be valid d6 rolls
1685            for &roll in &results {
1686                assert!(
1687                    roll >= 1 && roll <= 6,
1688                    "All rolls should be 1-6, got {}",
1689                    roll
1690                );
1691            }
1692        }
1693
1694        #[test]
1695        fn test_exploding_edge_cases() {
1696            // Test exploding on specific number (limited iterations to avoid long test)
1697            let result1 = roll("d6!6"); // Explode on 6 instead of 1 (less frequent)
1698            assert!(result1.is_ok(), "Exploding on 6 should work");
1699
1700            // Test exploding on max value
1701            let result2 = roll("d20!");
1702            assert!(result2.is_ok(), "Exploding on max should work");
1703
1704            // Test exploding with comparison
1705            let result3 = roll("d10!>8");
1706            assert!(result3.is_ok(), "Exploding >8 should work");
1707
1708            let result4 = roll("d10!<3");
1709            assert!(result4.is_ok(), "Exploding <3 should work");
1710        }
1711
1712        #[test]
1713        fn test_multiple_exploding_dice() {
1714            // Arrange
1715            let notation = "5d6!";
1716
1717            // Act
1718            let result = roll(notation);
1719
1720            // Assert
1721            assert!(result.is_ok(), "Multiple exploding dice should work");
1722            let results = result.unwrap();
1723
1724            // Should have at least 5 dice (the original rolls)
1725            assert!(results.len() >= 5, "Should have at least 5 dice results");
1726
1727            // All results should be valid d6 rolls
1728            for &roll in &results {
1729                assert!(
1730                    roll >= 1 && roll <= 6,
1731                    "All rolls should be 1-6, got {}",
1732                    roll
1733                );
1734            }
1735
1736            // Total should be at least 5
1737            let total: i32 = results.iter().sum();
1738            assert!(total >= 5, "Total should be at least 5");
1739        }
1740    }
1741
1742    mod repeat_roll_operations {
1743        use super::*;
1744
1745        #[test]
1746        fn test_repeat_simple_dice() {
1747            // Arrange
1748            let notation = "1d6x3";
1749
1750            // Act
1751            let result = roll(notation);
1752
1753            // Assert
1754            assert!(result.is_ok(), "Repeat simple dice should work");
1755            let results = result.unwrap();
1756            assert_eq!(results.len(), 3, "Should have 3 roll results");
1757
1758            // All results should be valid d6 roll sums
1759            for &roll_sum in &results {
1760                assert!(
1761                    roll_sum >= 1 && roll_sum <= 6,
1762                    "All roll sums should be 1-6, got {}",
1763                    roll_sum
1764                );
1765            }
1766        }
1767
1768        #[test]
1769        fn test_repeat_multiple_dice() {
1770            // Arrange
1771            let notation = "2d6x4";
1772
1773            // Act
1774            let result = roll(notation);
1775
1776            // Assert
1777            assert!(result.is_ok(), "Repeat multiple dice should work");
1778            let results = result.unwrap();
1779            assert_eq!(results.len(), 4, "Should have 4 roll results (2d6 x 4)");
1780
1781            // All results should be valid 2d6 roll sums
1782            for &roll_sum in &results {
1783                assert!(
1784                    roll_sum >= 2 && roll_sum <= 12,
1785                    "All roll sums should be 2-12, got {}",
1786                    roll_sum
1787                );
1788            }
1789        }
1790
1791        #[test]
1792        fn test_repeat_with_keep_highest() {
1793            // Arrange
1794            let notation = "4d6K3x2";
1795
1796            // Act
1797            let result = roll(notation);
1798
1799            // Assert
1800            assert!(result.is_ok(), "Repeat with keep highest should work");
1801            let results = result.unwrap();
1802            assert_eq!(results.len(), 2, "Should have 2 roll results (4d6K3 x 2)");
1803
1804            // All results should be valid 4d6K3 roll sums
1805            for &roll_sum in &results {
1806                assert!(
1807                    roll_sum >= 3 && roll_sum <= 18,
1808                    "All roll sums should be 3-18, got {}",
1809                    roll_sum
1810                );
1811            }
1812        }
1813
1814        #[test]
1815        fn test_repeat_consistency() {
1816            // Arrange
1817            let notation = "1d4x10";
1818
1819            // Act & Assert - Test multiple times to ensure consistency
1820            for _ in 0..5 {
1821                let result = roll(notation);
1822                assert!(result.is_ok(), "Repeat should work consistently");
1823
1824                let results = result.unwrap();
1825                assert_eq!(results.len(), 10, "Should always have 10 roll results");
1826
1827                // All results should be valid d4 roll sums
1828                for &roll_sum in &results {
1829                    assert!(
1830                        roll_sum >= 1 && roll_sum <= 4,
1831                        "All roll sums should be 1-4, got {}",
1832                        roll_sum
1833                    );
1834                }
1835            }
1836        }
1837
1838        #[test]
1839        fn test_repeat_single_execution() {
1840            // Arrange
1841            let notation = "3d6x1";
1842
1843            // Act
1844            let result = roll(notation);
1845
1846            // Assert
1847            assert!(result.is_ok(), "Repeat x1 should work");
1848            let results = result.unwrap();
1849            assert_eq!(results.len(), 1, "Should have 1 roll result");
1850
1851            // Result should be valid 3d6 roll sum
1852            let roll_sum = results[0];
1853            assert!(
1854                roll_sum >= 3 && roll_sum <= 18,
1855                "Roll sum should be 3-18, got {}",
1856                roll_sum
1857            );
1858        }
1859    }
1860
1861    mod error_handling {
1862        use super::*;
1863
1864        #[test]
1865        fn test_roll_with_invalid_input_returns_error_with_input() {
1866            // Arrange
1867            let invalid_input = "unparsable nonsense";
1868
1869            // Act
1870            let result = roll(invalid_input);
1871
1872            // Assert
1873            assert!(result.is_err(), "Invalid input should return an error");
1874
1875            let error = result.unwrap_err();
1876
1877            // Check the full error display includes the input
1878            let error_display = error.to_string();
1879            assert!(
1880                error_display.contains(invalid_input),
1881                "Error display should contain the invalid input: {}",
1882                error_display
1883            );
1884            assert!(
1885                error_display.contains("Invalid dice notation"),
1886                "Error display should contain error context: {}",
1887                error_display
1888            );
1889
1890            // Now check the specific error type
1891            match error {
1892                DiceError::InvalidNotation { input, reason: _ } => {
1893                    assert_eq!(
1894                        input, invalid_input,
1895                        "Error should contain the original input"
1896                    );
1897                }
1898                _ => panic!("Expected InvalidNotation error, got: {:?}", error),
1899            }
1900        }
1901
1902        #[test]
1903        fn test_roll_with_empty_string_returns_error() {
1904            // Arrange
1905            let empty_input = "";
1906
1907            // Act
1908            let result = roll(empty_input);
1909
1910            // Assert
1911            assert!(result.is_err(), "Empty input should return an error");
1912
1913            let error = result.unwrap_err();
1914            assert!(
1915                matches!(error, DiceError::EmptyInput),
1916                "Expected EmptyInput error, got: {:?}",
1917                error
1918            );
1919        }
1920
1921        #[test]
1922        fn test_roll_with_malformed_dice_notation_returns_error() {
1923            // Arrange
1924            let test_cases = vec![
1925                "d",         // Missing die size
1926                "4d",        // Missing die size
1927                "d + 5",     // Missing die size with modifier
1928                "4x6",       // Wrong separator
1929                "abc",       // Non-numeric
1930                "4d6 +",     // Incomplete modifier
1931                "4d6 + abc", // Invalid modifier
1932            ];
1933
1934            for invalid_input in test_cases {
1935                // Act
1936                let result = roll(invalid_input);
1937
1938                // Assert
1939                assert!(
1940                    result.is_err(),
1941                    "Invalid input '{}' should return an error",
1942                    invalid_input
1943                );
1944
1945                let error = result.unwrap_err();
1946                match error {
1947                    DiceError::InvalidNotation { input, reason: _ } => {
1948                        assert_eq!(
1949                            input, invalid_input,
1950                            "Error should contain the original input for '{}'",
1951                            invalid_input
1952                        );
1953                    }
1954                    DiceError::EmptyInput => {
1955                        // Empty input is also acceptable for some test cases
1956                        assert_eq!(
1957                            invalid_input, "",
1958                            "EmptyInput error should only occur for empty input"
1959                        );
1960                    }
1961                    _ => panic!("Unexpected error type for '{}': {:?}", invalid_input, error),
1962                }
1963            }
1964        }
1965
1966        #[test]
1967        fn test_roll_with_too_many_dice_returns_error() {
1968            // Arrange
1969            let test_cases = vec![
1970                "26d6",   // Just over the limit
1971                "30d10",  // Well over the limit
1972                "100d20", // Way over the limit
1973                "30d6K3", // Too many dice with keep operation
1974                "27d8>4", // Too many dice with success counting
1975                "40d10!", // Too many dice with exploding
1976                "50d6r1", // Too many dice with rerolling
1977            ];
1978
1979            for invalid_input in test_cases {
1980                // Act
1981                let result = roll(invalid_input);
1982
1983                // Assert
1984                assert!(
1985                    result.is_err(),
1986                    "Input with too many dice '{}' should return an error",
1987                    invalid_input
1988                );
1989
1990                let error = result.unwrap_err();
1991                match error {
1992                    DiceError::TooManyDice { count, max } => {
1993                        assert!(
1994                            count > 25,
1995                            "Dice count should be greater than 25, got {}",
1996                            count
1997                        );
1998                        assert_eq!(max, 25, "Max should be 25");
1999                    }
2000                    _ => panic!(
2001                        "Expected TooManyDice error for '{}', got: {:?}",
2002                        invalid_input, error
2003                    ),
2004                }
2005            }
2006        }
2007
2008        #[test]
2009        fn test_roll_with_exactly_max_dice_succeeds() {
2010            // Arrange
2011            let test_cases = vec![
2012                "25d6",   // Exactly at the limit
2013                "25d20",  // Exactly at the limit with different die size
2014                "25d6K3", // Exactly at limit with keep operation
2015                "25d8>4", // Exactly at limit with success counting
2016                "25d10!", // Exactly at limit with exploding
2017                "25d6r1", // Exactly at limit with rerolling
2018            ];
2019
2020            for valid_input in test_cases {
2021                // Act
2022                let result = roll(valid_input);
2023
2024                // Assert
2025                assert!(
2026                    result.is_ok(),
2027                    "Input with exactly max dice '{}' should succeed, got error: {:?}",
2028                    valid_input,
2029                    result.unwrap_err()
2030                );
2031
2032                let results = result.unwrap();
2033                assert!(
2034                    !results.is_empty(),
2035                    "Should return at least one result for '{}'",
2036                    valid_input
2037                );
2038            }
2039        }
2040
2041        #[test]
2042        fn test_roll_with_arithmetic_and_too_many_dice_returns_error() {
2043            // Arrange
2044            let test_cases = vec![
2045                "26d6 + 5",    // Left side has too many dice
2046                "5d6 + 26d4",  // Right side has too many dice
2047                "30d8 - 3",    // Left side has too many dice with subtraction
2048                "2d6 * 30d10", // Right side has too many dice with multiplication
2049            ];
2050
2051            for invalid_input in test_cases {
2052                // Act
2053                let result = roll(invalid_input);
2054
2055                // Assert
2056                assert!(
2057                    result.is_err(),
2058                    "Arithmetic with too many dice '{}' should return an error",
2059                    invalid_input
2060                );
2061
2062                let error = result.unwrap_err();
2063                match error {
2064                    DiceError::TooManyDice { count, max } => {
2065                        assert!(
2066                            count > 25,
2067                            "Dice count should be greater than 25, got {}",
2068                            count
2069                        );
2070                        assert_eq!(max, 25, "Max should be 25");
2071                    }
2072                    _ => panic!(
2073                        "Expected TooManyDice error for '{}', got: {:?}",
2074                        invalid_input, error
2075                    ),
2076                }
2077            }
2078        }
2079
2080        #[test]
2081        fn test_dice_count_limit_error_message() {
2082            // Arrange
2083            let invalid_input = "30d6";
2084
2085            // Act
2086            let result = roll(invalid_input);
2087
2088            // Assert
2089            assert!(result.is_err(), "Should return error for too many dice");
2090
2091            let error = result.unwrap_err();
2092            let error_message = error.to_string();
2093
2094            assert!(
2095                error_message.contains("Too many dice"),
2096                "Error message should mention too many dice: {}",
2097                error_message
2098            );
2099            assert!(
2100                error_message.contains("30"),
2101                "Error message should contain the actual count: {}",
2102                error_message
2103            );
2104            assert!(
2105                error_message.contains("25"),
2106                "Error message should contain the maximum allowed: {}",
2107                error_message
2108            );
2109        }
2110    }
2111}