Skip to content

Commit

Permalink
optional verbose flag for expression before/after rolling
Browse files Browse the repository at this point in the history
  • Loading branch information
dgunay committed Apr 20, 2024
1 parent 862b5fd commit 5bbf0f9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
13 changes: 12 additions & 1 deletion src/bin/dice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ struct Cli {
/// An optional random seed for repeatable results.
#[structopt(short, long)]
random_seed: Option<u64>,

/// If set, the expression after rolling the dice will be printed.
#[structopt(short, long)]
verbose: bool,
}

// fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -31,7 +35,14 @@ fn main() {

let result = solve_dice_expression(&combined_expression, args.random_seed);
match result {
Ok(out) => println!("{}", out),
Ok(out) => {
if args.verbose {
println!("Before: {}", combined_expression);
println!("After: {}", out.rolled_expression);
}

println!("{}", out.result);
}
Err(e) => {
println!("Error: {}", e);
std::process::exit(1);
Expand Down
16 changes: 14 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ use rand::{rngs::SmallRng, SeedableRng};
use regex::{Captures, Regex};
use std::borrow::Cow;

/// A struct representing the result of a dice roll.
pub struct DiceResult {
/// The final result of the dice roll.
pub result: i64,

/// The expression after rolling all the dice.
pub rolled_expression: String,
}

/// Solves a dice expression string by rolling each dice in-place and then
/// evaluating the resulting arithmetic expression.
///
Expand All @@ -35,7 +44,7 @@ use std::borrow::Cow;
///
/// # Panics
/// - Will panic if invalid `DiceRoll` expression given
pub fn solve_dice_expression(expression: &str, random_seed: Option<u64>) -> Result<i64> {
pub fn solve_dice_expression(expression: &str, random_seed: Option<u64>) -> Result<DiceResult> {
lazy_static! {
static ref PATTERN: Regex = Regex::new(r"(\d+)d(\d+)").expect("Problem compiling regex");
}
Expand Down Expand Up @@ -73,6 +82,9 @@ pub fn solve_dice_expression(expression: &str, random_seed: Option<u64>) -> Resu
} else {
// Calculate the result
let result = eval(&rolled_expression)?.as_int()?;
Ok(result)
Ok(DiceResult {
result,
rolled_expression: rolled_expression.to_string(),
})
}
}

0 comments on commit 5bbf0f9

Please sign in to comment.