extern crate rand;
use rand::Rng;
#[macro_use]
extern crate nom;
use nom::IResult;
use std::str::{from_utf8_unchecked, FromStr};
mod error;
use error::DiceFormatError;
fn buf_to_i32(buf: &[u8]) -> i32 {
FromStr::from_str(unsafe { from_utf8_unchecked(buf) }).unwrap()
}
named!(
parse_dice<(usize, u8, i32)>,
do_parse!(
count: call!(nom::digit) >>
tag!("d") >>
dice: call!(nom::digit) >>
opt!(complete!(tag!(" + "))) >>
bonus: opt!(complete!(call!(nom::digit))) >>
((buf_to_i32(count) as usize, buf_to_i32(dice) as u8, buf_to_i32(bonus.unwrap_or(b"0"))))
)
);
pub fn roll(count: usize, dice: u8, bonus: i32) -> i32 {
let mut rng = rand::thread_rng();
(0..count)
.map(|_| rng.gen_range(0, dice as i32))
.fold(0i32, |total, value| total + value)
+ bonus
+ 1
}
pub fn roll_from_str(cmd: &str) -> Result<i32, DiceFormatError> {
return match parse_dice(cmd.as_bytes()) {
IResult::Done(_, dice) => Ok(roll(dice.0, dice.1, dice.2)),
_ => Err(DiceFormatError::new(cmd)),
};
}
#[test]
fn test_roll() {
assert_eq!(nom::IResult::Done(&[][..], (1, 8, 0)), parse_dice(b"1d8"));
assert_eq!(
nom::IResult::Done(&[][..], (1, 8, 0)),
parse_dice(b"1d8 + 0")
);
assert_eq!(
nom::IResult::Done(&[][..], (3, 4, 2)),
parse_dice(b"3d4 + 2")
);
assert_eq!(
nom::IResult::Done(&[][..], (1, 8, 0)),
parse_dice(b"1d8 + ")
);
assert_eq!(
nom::IResult::Done(&b"+"[..], (1, 8, 0)),
parse_dice(b"1d8+")
);
}