Created
November 7, 2016 08:41
-
-
Save glaznaj/17d0fd3dc14c96f75336773fd17c1eda to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![macro_use] | |
| extern crate regex; | |
| use regex::Regex; | |
| #[derive(Debug)] | |
| enum Errors { | |
| BadFormat, | |
| } | |
| use self::Errors::*; | |
| impl From<std::num::ParseIntError> for Errors { | |
| fn from(_err: std::num::ParseIntError) -> Errors { | |
| BadFormat | |
| } | |
| } | |
| macro_rules! unwrap_or_return { | |
| ($expr:expr, $ret:expr) => ( | |
| match $expr { | |
| Some(x) => x, | |
| None => { return $ret; } | |
| } | |
| ) | |
| } | |
| macro_rules! unwrap_and_parse_or_return { | |
| ($expr:expr, $ret:expr) => ( | |
| match $expr { | |
| Some(x) => try!(x.parse()), | |
| None => { return $ret; } | |
| } | |
| ) | |
| } | |
| fn main() { | |
| let args = parse_args("100 200 300 400").unwrap(); | |
| let (priority, delay, ttr, bytes) = args; | |
| println!("priority: {}, delay: {}, ttr: {}, bytes: {}", priority, delay, ttr, bytes); | |
| } | |
| fn parse_args(args: &str) -> Result<(u32, u64, u64, u16), Errors> { | |
| let re: Regex = Regex::new(r"^(\d+)\s(\d+)\s(\d+)\s(\d+)$").unwrap(); | |
| let cap = unwrap_or_return!(re.captures(args), Err(BadFormat)); | |
| let priority = unwrap_and_parse_or_return!(cap.at(1), Err(BadFormat)); | |
| let delay = unwrap_and_parse_or_return!(cap.at(2), Err(BadFormat)); | |
| let ttr = unwrap_and_parse_or_return!(cap.at(3), Err(BadFormat)); | |
| let bytes = unwrap_and_parse_or_return!(cap.at(4), Err(BadFormat)); | |
| Ok((priority, delay, ttr, bytes)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment