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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Simple library to roll dices
//!
//!## Note
//!
//!All ops are saturating.
//!
//!## Available features
//!
//!- `std` - Enables std support. Enabled  by default.
//!
//!## Usage
//!
//!```rust
//!extern crate cute_dnd_dice;
//!
//!use cute_dnd_dice::Roll;
//!
//!fn main() {
//!    let roll = Roll::from_str("2d20+10").expect("To parse roll");
//!    println!("I roll {}", roll.roll());
//!}
//!```

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
use std as core;

use core::fmt;
use core::ops;

pub extern crate rand;

#[derive(PartialEq, Eq, Debug)]
///Possible errors when parsing roll
pub enum ParseError {
    ///Couldn't find `d`
    MissingD,
    ///Missing dice faces
    MissingFaces,
    ///Modifier value is not present
    MissingModifierValue,
    ///Invalid number of dices
    InvalidNum,
    ///Invalid number of faces
    InvalidFaces,
    ///Invalid number of extra
    InvalidExtra,
}

impl ParseError {
    ///Returns text description of error.
    pub fn desc(&self) -> &'static str {
        match self {
            ParseError::MissingD => "'d' is missing",
            ParseError::MissingFaces => "Number of dice's faces is missing",
            ParseError::MissingModifierValue => "Modifier for roll is missing",
            ParseError::InvalidNum => "Number of dices is invalid. Should be positive integer",
            ParseError::InvalidFaces => "Number of faces is invalid. Should be positive integer",
            ParseError::InvalidExtra => "Number of extra is invalid. Should be positive integer",
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.desc())
    }
}

#[cfg(feature = "std")]
impl core::error::Error for ParseError {
    fn description(&self) -> &str {
        self.desc()
    }
}

#[derive(Eq, PartialEq, Debug, Clone, Copy)]
///Roll Modifier
pub enum Modifier {
    ///Plus variant
    Plus(u16),
    ///Minus variant
    Minus(u16),
}

impl ops::Add<u16> for Modifier {
    type Output = Modifier;

    fn add(self, other: u16) -> Self::Output {
        match self {
            Modifier::Plus(modifier) => Modifier::Plus(modifier.saturating_add(other)),
            Modifier::Minus(modifier) => match other >= modifier {
                true => Modifier::Plus(other - modifier),
                false => Modifier::Minus(modifier - other),
            },
        }
    }
}

impl ops::AddAssign<u16> for Modifier {
    fn add_assign(&mut self, other: u16) {
        *self = *self + other;
    }
}

impl ops::Sub<u16> for Modifier {
    type Output = Modifier;

    fn sub(self, other: u16) -> Self::Output {
        match self {
            Modifier::Minus(modifier) => Modifier::Minus(modifier.saturating_sub(other)),
            Modifier::Plus(modifier) => match other > modifier {
                true => Modifier::Minus(other - modifier),
                false => Modifier::Plus(modifier - other),
            },
        }
    }
}

impl ops::SubAssign<u16> for Modifier {
    fn sub_assign(&mut self, other: u16) {
        *self = *self - other;
    }
}


impl Modifier {
    fn modify(&self, value: u16) -> u16 {
        match *self {
            Modifier::Plus(modifier) => value.saturating_add(modifier),
            Modifier::Minus(modifier) => value.saturating_sub(modifier),
        }
    }

    ///Returns whether modifier is negative.
    pub fn is_neg(&self) -> bool {
        match self {
            Modifier::Plus(_) => false,
            Modifier::Minus(_) => true,
        }
    }
}

impl fmt::Display for Modifier {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Modifier::Plus(0) => Ok(()),
            Modifier::Plus(value) => write!(fmt, "+{}", value),
            Modifier::Minus(0) => Ok(()),
            Modifier::Minus(value) => write!(fmt, "-{}", value),
        }
    }
}

#[derive(Debug)]
///D&D Roll representation
pub struct Roll {
    ///Number of dices
    pub num: u16,
    ///Number of faces on dice
    pub faces: u16,
    ///Bonus to roll
    pub extra: Modifier,
}

impl Roll {
    ///Attempts to parse Roll from string `[num]d<faces> [+ <extra>]`
    pub fn from_str(text: &str) -> Result<Self, ParseError> {
        const D: &[char] = &['d', 'D'];
        const PLUS: char = '+';
        const MINUS: char = '-';

        let text = text.trim();

        let dice_idx = match text.find(D) {
            Some(idx) => idx,
            None => return Err(ParseError::MissingD),
        };

        if dice_idx == text.len() - 1 {
            return Err(ParseError::MissingFaces);
        }

        let num = match dice_idx {
            0 => 1,
            dice_idx => match text[..dice_idx].trim().parse() {
                Ok(0) => return Err(ParseError::InvalidNum),
                Ok(num) => num,
                Err(_) => return Err(ParseError::InvalidNum),
            }
        };

        let extra = text.find(PLUS)
                        .map(|extra| (extra, false))
                        .or_else(|| text.find(MINUS).map(|extra| (extra, true)));

        let (extra, dice_end) = match extra {
            Some((idx, is_extra_neg)) => match text.len() - 1 == idx {
                true => return Err(ParseError::MissingModifierValue),
                false => match text[idx+1..].trim().parse() {
                    Ok(extra) => match is_extra_neg {
                        true => (Modifier::Minus(extra), idx),
                        false => (Modifier::Plus(extra), idx),
                    }
                    Err(_) => return Err(ParseError::InvalidExtra),
                },
            },
            None => (Modifier::Plus(0), text.len()),
        };

        let faces = match text[dice_idx+1..dice_end].trim().parse() {
            Ok(0) => return Err(ParseError::InvalidFaces),
            Ok(faces) => faces,
            Err(_) => return Err(ParseError::InvalidFaces),
        };

        Ok(Self {
            num,
            faces,
            extra,
        })
    }

    ///Returns minimum possible value.
    pub fn min(&self) -> u16 {
        self.extra.modify(self.num)
    }

    ///Returns maximum possible value.
    pub fn max(&self) -> u16 {
        let res = self.num.saturating_mul(self.faces);
        self.extra.modify(res)
    }

    #[cfg(feature = "std")]
    #[inline]
    ///Calculates roll using `rand::thread_rng()`
    pub fn roll(&self) -> u16 {
        self.calc(&mut rand::thread_rng())
    }

    ///Calculates result of roll using provided `rand::Rng`
    pub fn calc<R: rand::Rng>(&self, rng: &mut R) -> u16 {
        let mut result: u16 = 0;

        for roll in rng.sample_iter(&rand::distributions::Uniform::new_inclusive(1, self.faces)).take(self.num as usize) {
            result = result.saturating_add(roll);
        }

        self.extra.modify(result)
    }
}

impl fmt::Display for Roll {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}d{}{}", self.num, self.faces, self.extra)
    }
}