Smarter arg setup

This commit is contained in:
Beefki 2017-11-02 11:34:30 -05:00
parent 9b2044a00a
commit 61346fcf10
2 changed files with 22 additions and 16 deletions

View File

@ -1,10 +1,7 @@
//! A simple and efficient library to make dice rolls into easy to use values.
pub extern crate rand;
pub mod roll;
pub mod config;
//pub mod error;
pub use roll::*;
pub use roll::Roll;
pub use std::{num, io};
//pub use error::RollError;

View File

@ -22,9 +22,9 @@ impl Roll {
}
}
/// Returns the value stored in the number field of a roll.
/// Allows the fields of `Roll` to be private (and unchangable)
/// while still allowing access to act on their internal value
///Returns the value stored in the number field of a roll.
///Allows the fields of `Roll` to be private (and unchangable)
///while still allowing access to act on their internal value
/// ```
/// let x = Roll::new(&2, &6);
/// assert!(x.number() == 2);
@ -39,30 +39,40 @@ impl Roll {
self.die
}
/// Creates a Vector to hold each of the values rolled. Making
///a Vector ensures the ability to work on exactly the same
///die rolls easily and accurately, since calling the `Roll`
///iterator again will produce new results.
/// a Vector ensures the ability to work on exactly the same
/// die rolls easily and accurately, since calling the `Roll`
/// iterator again will produce new results.
pub fn rolls(self) -> Vec<usize> {
self.collect()
}
/// Used on a `Roll` to return only the final value, ignoring
///the values used to add up to that result. Allows `.total()`
///syntax when used
/// the values used to add up to that result. Allows `.total()`
/// syntax when used
pub fn total(self) -> usize {
self.sum()
}
/// Takes arguments and turns them into a `Roll` if possible,
/// failing that it returns an error to be handled.
/// Keeps taking args until less than 2 remain so it returns a
/// `Vec<Roll>`
pub fn from_args(args: &mut std::env::Args) -> Result<Vec<Roll>, ParseIntError> {
//first arg is the path to the executable so skip it
args.next();
let mut total: Vec<Roll> = vec![];
// loop that checks that there's enough elements in args remaining
// to make a `Roll` from.
while args.len() >= 2 {
// Collect 2 args into a `Vec<String>` and turn them into
// a `Roll`
let roll: Vec<String> = args.take(2).collect();
total.push(Roll::new(
roll[0].parse::<usize>()?,
roll[1].parse::<usize>()?,
)
);
));
}
Ok(total)
}
@ -119,11 +129,10 @@ fn rolls() {
}
#[test]
fn totaling() {
for _ in 0 .. 21 {
for _ in 0..21 {
let x = Roll::new(2, 6);
assert!(x.total() <= 12 && x.total() >= 2);
let y = Roll::new(3, 20);
assert!(y.total() <= 60 && y.total() >= 3);
}
}