From 77b8c9ec5cf93bcb767af97b11230577d86b55ea Mon Sep 17 00:00:00 2001 From: Milo Turner Date: Sat, 7 Mar 2020 13:35:03 -0500 Subject: [PATCH] enterprise scale rust --- hptp-recv/src/main.rs | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/hptp-recv/src/main.rs b/hptp-recv/src/main.rs index 8b1ce00..2cd28ba 100644 --- a/hptp-recv/src/main.rs +++ b/hptp-recv/src/main.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + extern crate hptp; #[derive(Debug)] @@ -6,8 +8,17 @@ struct Hostname { port: u16, } -fn go(hn: Hostname) { - println!("ip={}, port={}", hn.ip, hn.port) +struct InvalidHostnameError; + +impl FromStr for Hostname { + type Err = InvalidHostnameError; + fn from_str(s: &str) -> Result { + let i = s.find(':').ok_or(InvalidHostnameError)?; + Ok(Hostname { + ip: s[..i].into(), + port: s[i + 1..].parse().map_err(|_| InvalidHostnameError)?, + }) + } } fn usage() { @@ -15,20 +26,16 @@ fn usage() { } fn parse_args() -> Result { - let mut args = std::env::args(); - let arg = args.nth(1).ok_or(())?; - let i = arg.find(':').ok_or(())?; - let ip = &arg[..i]; - let port: u16 = arg[i + 1..].parse().map_err(|_| ())?; - Ok(Hostname { - ip: ip.into(), - port, - }) + std::env::args().nth(1).ok_or(())?.parse().map_err(|_| ()) } fn main() { match parse_args() { - Ok(x) => go(x), + Ok(x) => start(x), Err(_) => usage(), } } + +fn start(hn: Hostname) { + println!("ip={}, port={}", hn.ip, hn.port) +}