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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2017 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A dice rolling and statistics library.

#![feature(conservative_impl_trait, i128_type)]

#![warn(missing_copy_implementations, missing_debug_implementations, missing_docs)]

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", warn(clippy))]

extern crate rand;

#[macro_use]
mod utility;

mod statistics;

pub mod syntax;

use std::cmp;

use rand::{Rng};

pub use self::statistics::ratio::{Ratio};

/// The result of rolling a die.
pub type DieResult = (u32, Option<u32>);

/// The result of rolling a set of same-sized dice.
pub type DiceResult = (u32, Vec<DieResult>);

//================================================
// Enums
//================================================

// Binary ________________________________________

/// An operation used to combine the results of two dice rolling expressions.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Binary {
    /// Add the results.
    Add,
    /// Divide the results.
    Divide,
    /// Multiply the results.
    Multiply,
    /// Subtract the results.
    Subtract,
}

impl Binary {
    //- Accessors --------------------------------

    /// Combines the supplied results using this binary operation.
    ///
    /// This method returns `None` if the binary operation fails (e.g., integer overflow).
    pub fn combine(&self, left: i32, right: i32) -> Option<i32> {
        match *self {
            Binary::Add => left.checked_add(right),
            Binary::Divide => left.checked_div(right),
            Binary::Multiply => left.checked_mul(right),
            Binary::Subtract => left.checked_sub(right),
        }
    }
}

// Expression ____________________________________

/// A dice rolling expression.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Expression {
    /// A binary expression.
    Binary(Binary, Box<Expression>, Box<Expression>),
    /// A constant expression.
    Constant(u32),
    /// A die expression.
    Die(Die, Option<Reroll>),
    /// A dice expression.
    Dice(Dice, Option<Reroll>, Fold),
}

impl Expression {
    //- Accessors --------------------------------

    /// Rolls this dice rolling expression and returns the result.
    ///
    /// This method returns `None` if any of the binary operations fail (e.g., integer overflow).
    pub fn roll(&self, rng: &mut Rng) -> Option<i32> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => {
                let left = try_opt!(left.roll(rng));
                let right = try_opt!(right.roll(rng));
                binary.combine(left, right)
            },
            Expression::Constant(constant) => Some(constant as i32),
            Expression::Die(die, reroll) => Some(die.roll(rng, reroll).0 as i32),
            Expression::Dice(dice, reroll, fold) => Some(dice.roll(rng, reroll, fold).0 as i32),
        }
    }
}

// Fold __________________________________________

/// An operation used to combine the results of rolling a set of same-sized dice.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Fold {
    /// Sum the results after dropping the smallest result.
    DropMinimum,
    /// Sum the results after dropping the largest result.
    DropMaximum,
    /// Take the smallest result.
    Minimum,
    /// Take the largest result.
    Maximum,
    /// Sum the results.
    Sum,
}

impl Fold {
    //- Accessors --------------------------------

    /// Combines the supplied results using this fold operation.
    pub fn combine<R>(&self, results: R) -> u32 where R: Iterator<Item=u32> {
        match *self {
            Fold::DropMinimum => {
                let start = (0, u32::max_value());
                let (sum, minimum) = results.fold(start, |(s, m), r| (s + r, cmp::min(r, m)));
                sum - minimum
            },
            Fold::DropMaximum => {
                let start = (0, u32::min_value());
                let (sum, maximum) = results.fold(start, |(s, m), r| (s + r, cmp::max(r, m)));
                sum - maximum
            },
            Fold::Minimum => results.min().unwrap_or(0),
            Fold::Maximum => results.max().unwrap_or(0),
            Fold::Sum => results.sum(),
        }
    }
}

//================================================
// Structs
//================================================

// Dice __________________________________________

/// A set of same-sized dice.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Dice(u32, Die);

impl Dice {
    //- Constructors -----------------------------

    /// Constructs a new `Dice`.
    ///
    /// # Panics
    ///
    /// * `size` is zero
    pub fn new(size: u32, die: Die) -> Self {
        assert!(size != 0, "`size` is zero");
        Dice(size, die)
    }

    //- Accessors --------------------------------

    /// Returns the size of this set of dice.
    pub fn size(&self) -> u32 {
        self.0
    }

    /// Returns the die used in this set of dice.
    pub fn die(&self) -> Die {
        self.1
    }

    /// Rolls this set of dice and returns the combined result.
    pub fn roll(&self, rng: &mut Rng, reroll: Option<Reroll>, fold: Fold) -> DiceResult {
        let results = (0..self.0).map(|_| self.1.roll(rng, reroll)).collect::<Vec<_>>();
        (fold.combine(results.iter().map(|&(r, _)| r)), results)
    }
}

// Die ___________________________________________

/// A die.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Die(u32);

impl Die {
    //- Constructors -----------------------------

    /// Constructs a new `Die`.
    ///
    /// # Panics
    ///
    /// * `size` is zero
    pub fn new(size: u32) -> Die {
        assert!(size != 0, "`size` is zero");
        Die(size)
    }

    //- Accessors --------------------------------

    /// Returns the size of this die.
    pub fn size(&self) -> u32 {
        self.0
    }

    /// Rolls this die and returns the result.
    pub fn roll(&self, rng: &mut Rng, reroll: Option<Reroll>) -> DieResult {
        let roll = generate(rng, 1, self.0);
        if reroll.map_or(false, |r| r.reroll(roll, *self)) {
            (generate(rng, 1, self.0), Some(roll))
        } else {
            (roll, None)
        }
    }
}

// Reroll ________________________________________

/// An inclusive upper bound on rolls that should be rerolled once.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Reroll(u32);

impl Reroll {
    //- Constructors -----------------------------

    /// Constructs a new `Reroll`.
    ///
    /// # Panics
    ///
    /// * `maximum` is zero
    pub fn new(maximum: u32) -> Self {
        assert!(maximum != 0, "`maximum` is zero");
        Reroll(maximum)
    }

    //- Accessors --------------------------------

    /// Returns whether the supplied roll on the supplied die should be rerolled once.
    ///
    /// This method returns `true` only when it would be advantagous to reroll the die. In other
    /// words, this method always returns `false` when supplied with a roll that is above average
    /// for the supplied die.
    pub fn reroll(&self, roll: u32, die: Die) -> bool {
        roll <= (die.size() / 2) && roll <= self.0
    }
}

//================================================
// Functions
//================================================

fn generate(rng: &mut Rng, minimum: u32, maximum: u32) -> u32 {
    assert!(minimum <= maximum);
    let size = (maximum - minimum) + 1;
    let mut number = rng.next_u32();
    while number >= u32::max_value() - (u32::max_value() % size) {
        number = rng.next_u32();
    }
    (number % size) + minimum
}