one_d_six/lib.rs
1//! Provides utilities for rolling dice.
2//!
3//! # Examples
4//!
5//! ## Simple Usage
6//!
7//! ```
8//! use one_d_six::quickroll;
9//!
10//! if quickroll::<u16>("1d2") == 1 {
11//! println!("Heads!");
12//! } else {
13//! println!("Tails!");
14//! }
15//! ```
16//!
17//! ## Adding Sets of Dice Together
18//!
19//! ```
20//! use one_d_six::Dice;
21//!
22//! // 3d6
23//! let set_1 = Dice::new(3, 6);
24//! // 2d4
25//! let set_2: Dice = "2d4".parse().unwrap();
26//!
27//! // 3d6 + 2d4
28//! let dice = set_1 + set_2;
29//!
30//! // Each set of dice starts pre-rolled
31//! let roll = dice.total();
32//!
33//! println!("Result of 3d6 + 2d4 roll: {}", roll);
34//! ```
35//!
36//! ## Getting Dice as String
37//! ### Simple String
38//!
39//! ```
40//! use one_d_six::Dice;
41//!
42//!
43//! let dice: Dice = Dice::new(3, 6);
44//! println!("3d6: {}", dice);
45//! ```
46//!
47//! ### Complex String
48//!
49//! ```
50//! use one_d_six::Dice;
51//!
52//!
53//! // Will look like "1 2 3"
54//! let dice = Dice::new(3, 6);
55//! println!("3d6: {:?}", dice);
56//! ```
57use std::str::FromStr;
58
59pub use dice::*;
60pub use dice_total::*;
61pub use die::*;
62pub use rollable::*;
63
64mod dice;
65mod dice_total;
66mod die;
67mod rollable;
68
69/// Attempts to roll dice based on a *1d6* style string.
70///
71/// # Example
72///
73/// ```
74/// use one_d_six::try_quickroll;
75///
76/// if let Ok(roll) = try_quickroll::<u32>("1d6") {
77/// assert!(roll >= 1);
78/// assert!(roll <= 6);
79/// } else {
80/// unreachable!();
81/// }
82/// ```
83pub fn try_quickroll<T: Rollable>(dice_format: &str) -> Result<T, String>
84where
85 T: DiceTotal<T>,
86 T: FromStr,
87{
88 let dice: Dice<T> = dice_format.parse()?;
89 Ok(dice.total())
90}
91
92/// Rolls dice based on a *1d6* style string.
93///
94/// # Example
95///
96/// ```
97/// use one_d_six::quickroll;
98///
99/// let coin_flip: u8 = quickroll("1d2");
100///
101/// assert!(coin_flip == 1 || coin_flip == 2);
102/// ```
103///
104/// # Panics
105///
106/// Panics if `dice_format` is in an improper format.
107pub fn quickroll<T: Rollable>(dice_format: &str) -> T
108where
109 T: DiceTotal<T>,
110 T: FromStr,
111{
112 let dice: Dice<T> = dice_format.parse().unwrap();
113 dice.total()
114}