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
#![deny(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unstable_features,
unused_import_braces, unused_qualifications)]
extern crate rand;
use rand::Rng;
#[macro_use]
extern crate nom;
use nom::IResult;
use std::str::{FromStr, from_utf8_unchecked};
mod error;
use error::DiceFormatError;
#[allow(dead_code)]
fn buf_to_i32(buf: &[u8]) -> i32 {
FromStr::from_str(unsafe { from_utf8_unchecked(buf) }).unwrap()
}
#[allow(dead_code)]
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+"));
}