tidy up Position::from_str and add test for bad data
This commit is contained in:
parent
a6bcc763e9
commit
acfb0b6c8f
|
@ -15,17 +15,14 @@ impl FromStr for Position {
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
let mut parts = s.split(',');
|
let mut parts = s.split(',');
|
||||||
let x = parts.next().unwrap().parse();
|
|
||||||
let y = parts.next().unwrap().parse();
|
|
||||||
|
|
||||||
if x.is_err() {
|
let x = parts.next().unwrap();
|
||||||
Err("bad x supplied for position".to_string())
|
let y = parts.next().unwrap();
|
||||||
} else if y.is_err() {
|
|
||||||
Err("bad y supplied for position".to_string())
|
if let (Ok(x), Ok(y)) = (x.parse(), y.parse()) {
|
||||||
} else {
|
|
||||||
let x = x.unwrap();
|
|
||||||
let y = y.unwrap();
|
|
||||||
Ok(Position { x, y })
|
Ok(Position { x, y })
|
||||||
|
} else {
|
||||||
|
Err(format!("Malformed position string: {}", s))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -44,11 +41,16 @@ mod test {
|
||||||
#[test]
|
#[test]
|
||||||
fn position_from_str() {
|
fn position_from_str() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Position::from_str(&"4,12").unwrap(),
|
Position::from_str("4,12").unwrap(),
|
||||||
Position { x: 4, y: 12 }
|
Position { x: 4, y: 12 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn position_from_malformed_str() {
|
||||||
|
assert!(Position::from_str("14,-1").is_err())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn position_to_string() {
|
fn position_to_string() {
|
||||||
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
|
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
|
||||||
|
|
Loading…
Reference in New Issue