From 5bfcc9ab4cfb197a7416d84dece8fef5569d8b6f Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Wed, 29 Apr 2020 20:16:15 +0100 Subject: [PATCH] handle error in position --- src/position.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/position.rs b/src/position.rs index 6d13002..390eee5 100644 --- a/src/position.rs +++ b/src/position.rs @@ -11,22 +11,22 @@ pub struct Position { impl Error for Position {} impl FromStr for Position { - type Err = (); + type Err = String; fn from_str(s: &str) -> Result { - let string = s.to_string(); + let mut parts = s.split(','); + let x = parts.next().unwrap().parse(); + let y = parts.next().unwrap().parse(); - // e.g. "2,5" - let xy: Vec<&str> = string.split(',').collect(); - let x = xy[0].parse().expect("Bad x coordinate supplied for Position"); - - if xy.len() < 2 { - panic!("Bad position : {}", string); + if x.is_err() { + Err("bad x supplied for position".to_string()) + } else if y.is_err() { + Err("bad y supplied for position".to_string()) + } else { + let x = x.unwrap(); + let y = y.unwrap(); + Ok(Position { x, y }) } - - let y = xy[1].parse().expect("Bad y coordinate supplied for Position"); - - Ok(Position { x, y }) } }