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
//! # mice, messing with dice
//! The heading obviates the need for a body.
//!
//! This crate is written primarily for my own
//! usage, and will likely obtain extensions related
//! to games that I play.
//!
//! Some basic usage:
//!
//! ```
//! # use mice::{roll, Error};
//! println!("{}", roll("2d6 + 3")?);
//!
//! println!("{}", roll("2d6 + 3")?.total());
//!
//! let result = roll("2d6 + 3")?;
//! println!("{}\n{}", result, result.total());
//! # Ok::<(), Error>(())
//! ```
//!
//! The parser accepts an arbitrary number of terms in a dice expression.
//! ```
//! # use mice::{roll, Error};
//! println!("{}", roll("9d8 + 4d2 - 5 - 8d7")?);
//! # Ok::<(), Error>(())
//! ```
#![forbid(unsafe_code)]
use rand::Rng;
mod error;
pub use error::Error;
use error::MyResult;
mod post;
use post::{EResult, EvaluatedTerm, RolledDie};
pub use post::{ExpressionResult, FormatOptions};
mod expose;
#[cfg(feature = "thread_rng")]
pub use expose::roll_tuples;
pub use expose::tuple_vec;
pub mod parse;
use parse::{DiceTerm, Expr, Sign, Term};
pub use parse::ParseError;
pub mod builder;
use builder::RollBuilder;
mod display;
pub mod prelude;
pub mod util;
#[derive(::thiserror::Error, Debug, Clone, Copy)]
#[error("sum is too high for `i64`")]
pub struct OverflowPositive;
#[derive(::thiserror::Error, Debug, Clone, Copy)]
#[error("sum is too low for `i64`")]
pub struct OverflowNegative;
#[derive(::thiserror::Error, Debug, Clone, Copy)]
enum Overflow {
    #[error(transparent)]
    Positive(#[from] OverflowPositive),
    #[error(transparent)]
    Negative(#[from] OverflowNegative),
}
impl From<Overflow> for Error {
    fn from(o: Overflow) -> Self {
        match o {
            Overflow::Positive(x) => Self::OverflowPositive(x),
            Overflow::Negative(x) => Self::OverflowNegative(x),
        }
    }
}
impl ::core::ops::Neg for Overflow {
    type Output = Overflow;
    fn neg(self) -> Self::Output {
        use Overflow::*;
        match self {
            Positive(x) => Negative(-x),
            Negative(x) => Positive(-x),
        }
    }
}
fn roll_die_with<R>(a: &DiceTerm, rng: &mut R) -> Result<RolledDie, OverflowPositive>
where
    R: Rng,
{
    if a.size == 1 {
        Ok(RolledDie {
            total: a.number,
            parts: (0..a.number).map(|_| 1).collect(),
            sign_part: Sign::Positive,
        })
    } else {
        let mut total: i64 = 0;
        let mut parts = Vec::new();
        // Rng::gen_range has an exlusive upper bound
        // Rng::gen includes the entire range of a type.
        for _ in 0..a.number {
            let random;
            if let Some(bound) = a.size.checked_add(1) {
                random = rng.gen_range(1, bound);
            } else {
                random = rng.gen();
            }
            total = total.checked_add(random).ok_or(OverflowPositive)?;
            parts.push(random);
        }
        Ok(RolledDie {
            total,
            parts,
            sign_part: Sign::Positive,
        })
    }
}

fn eval_term_with<R>(a: &Expr, rng: &mut R) -> Result<EvaluatedTerm, Overflow>
where
    R: Rng,
{
    let t: MyResult<_, Overflow> = match a.term {
        Term::Dice(x) => roll_die_with(&x, rng).into(),
        Term::Constant(x) => MyResult::Ok(EvaluatedTerm::Constant(x)),
    };
    // No positive number can overflow via negation.
    // Since terms are purely positive, this will never overflow.
    (a.sign * t).into()
}

/// Evaluate a dice expression!
/// This function takes the usual dice expression format,
/// and allows an arbitrary number of terms.
/// ```
/// # use mice::roll;
/// # use mice::Error;
/// let dice_expression = "d20 + 5 - d2";
/// println!("{}", roll(dice_expression)?);
/// # Ok::<(), Error>(())
/// ```
///
/// An `Err` is returned in the following cases:
///   - A d0 is used
///   - The sum of all terms is too high
///   - The sum of all terms is too low
///   - Nonsense input
#[cfg(feature = "thread_rng")]
pub fn roll(input: &str) -> EResult {
    Ok(RollBuilder::new().parse(input)?.into_roll().unwrap().roll()?)
}

fn try_roll_expr_iter_with<I, R>(rng: &mut R, input: I) -> EResult
where
    I: Iterator<Item = Result<Expr, Error>>,
    R: Rng,
{
    // let mut rng = thread_rng(); // This doesn't work in WASM?
    let mut pairs = Vec::new();
    let mut total: i64 = 0;
    for x in input {
        match x {
            Ok(x) => {
                let res = eval_term_with(&x, rng)?;
                let res_val = res.value();
                pairs.push((x, res));
                total = total.checked_add(res_val).ok_or(if res_val > 0 {
                    Error::OverflowPositive(OverflowPositive)
                } else {
                    Error::OverflowNegative(OverflowNegative)
                })?;
            }
            Err(x) => return Err(x),
        }
    }
    Ok(ExpressionResult::new(pairs, total))
}

fn roll_expr_iter_with<I, R>(rng: &mut R, input: I) -> EResult
where
    I: Iterator<Item = Expr>,
    R: Rng,
{
    try_roll_expr_iter_with(rng, input.map(Ok))
}

// N
// dN1   (+/-) N2
// N1dN2 (+/-) N3
// N1dN2 (+/-) N3dN4 (+/-) [...] (+/-) NN

#[cfg(test)]
mod tests {
    use crate::{roll, DiceTerm};
    #[test]
    fn arithmetic() {
        assert_eq!(roll("5 + 3").unwrap().total(), 8);
        assert_eq!(roll("5 - 3").unwrap().total(), 2);
    }
    #[test]
    fn dice() {
        match DiceTerm::new(0, 0) {
            Ok(_) => panic!(),
            Err(_) => (),
        }
    }
}