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> {
|
||||
let mut parts = s.split(',');
|
||||
let x = parts.next().unwrap().parse();
|
||||
let y = parts.next().unwrap().parse();
|
||||
|
||||
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();
|
||||
let x = parts.next().unwrap();
|
||||
let y = parts.next().unwrap();
|
||||
|
||||
if let (Ok(x), Ok(y)) = (x.parse(), y.parse()) {
|
||||
Ok(Position { x, y })
|
||||
} else {
|
||||
Err(format!("Malformed position string: {}", s))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -44,11 +41,16 @@ mod test {
|
|||
#[test]
|
||||
fn position_from_str() {
|
||||
assert_eq!(
|
||||
Position::from_str(&"4,12").unwrap(),
|
||||
Position::from_str("4,12").unwrap(),
|
||||
Position { x: 4, y: 12 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_from_malformed_str() {
|
||||
assert!(Position::from_str("14,-1").is_err())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_to_string() {
|
||||
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
|
||||
|
|
Loading…
Reference in New Issue