handle error in position
This commit is contained in:
parent
56f85470ff
commit
5bfcc9ab4c
|
@ -11,23 +11,23 @@ pub struct Position {
|
||||||
impl Error for Position {}
|
impl Error for Position {}
|
||||||
|
|
||||||
impl FromStr for Position {
|
impl FromStr for Position {
|
||||||
type Err = ();
|
type Err = String;
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
let string = s.to_string();
|
let mut parts = s.split(',');
|
||||||
|
let x = parts.next().unwrap().parse();
|
||||||
// e.g. "2,5"
|
let y = parts.next().unwrap().parse();
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
let y = xy[1].parse().expect("Bad y coordinate supplied for Position");
|
|
||||||
|
|
||||||
|
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 })
|
Ok(Position { x, y })
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Position {
|
impl fmt::Display for Position {
|
||||||
|
|
Loading…
Reference in New Issue