2020-04-18 15:12:06 +00:00
|
|
|
use std::error::Error;
|
|
|
|
|
2020-04-12 12:21:27 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
|
|
|
pub struct Position {
|
2020-04-12 16:13:08 +00:00
|
|
|
pub x: u8,
|
|
|
|
pub y: u8,
|
2020-04-12 12:21:27 +00:00
|
|
|
}
|
|
|
|
|
2020-04-18 15:12:06 +00:00
|
|
|
impl Position {
|
|
|
|
pub(crate) fn from(string: String) -> Result<Position, &'static dyn Error> {
|
2020-04-12 12:21:27 +00:00
|
|
|
// e.g. "2,5"
|
|
|
|
let xy: Vec<&str> = string.split(',').collect();
|
|
|
|
let x = xy[0].parse().unwrap();
|
2020-04-13 23:37:02 +00:00
|
|
|
|
|
|
|
if xy.len() < 2 {
|
|
|
|
panic!("Bad position : {}", string);
|
|
|
|
}
|
|
|
|
|
2020-04-12 12:21:27 +00:00
|
|
|
let y = xy[1].parse().unwrap();
|
|
|
|
|
2020-04-18 15:12:06 +00:00
|
|
|
Ok(Position { x, y })
|
2020-04-12 12:21:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToString for Position {
|
|
|
|
#[inline]
|
|
|
|
fn to_string(&self) -> String {
|
|
|
|
format!("{},{}", self.x, self.y)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_position_from_string() {
|
2020-04-18 15:58:30 +00:00
|
|
|
assert_eq!(
|
|
|
|
Position::from("4,12".to_string()).unwrap(),
|
|
|
|
Position { x: 4, y: 12 }
|
|
|
|
);
|
2020-04-12 12:21:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_position_to_string() {
|
|
|
|
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
|
|
|
|
}
|