bitsy-parser/src/position.rs

58 lines
1.2 KiB
Rust
Raw Normal View History

2020-04-18 15:12:06 +00:00
use std::error::Error;
2020-04-29 17:33:22 +00:00
use std::fmt;
use std::str::FromStr;
2020-04-18 15:12:06 +00:00
2020-04-12 12:21:27 +00:00
#[derive(Debug, Eq, PartialEq)]
pub struct Position {
pub x: u8,
pub y: u8,
2020-04-12 12:21:27 +00:00
}
2020-04-29 17:33:22 +00:00
impl Error for Position {}
impl FromStr for Position {
2020-04-29 19:16:15 +00:00
type Err = String;
2020-04-29 17:33:22 +00:00
fn from_str(s: &str) -> Result<Self, Self::Err> {
2020-04-29 19:16:15 +00:00
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();
Ok(Position { x, y })
2020-04-13 23:37:02 +00:00
}
2020-04-12 12:21:27 +00:00
}
}
2020-04-29 17:33:22 +00:00
impl fmt::Display for Position {
2020-04-12 12:21:27 +00:00
#[inline]
2020-04-29 17:33:22 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.x, self.y)
2020-04-12 12:21:27 +00:00
}
}
2020-04-19 07:13:55 +00:00
#[cfg(test)]
mod test {
use crate::position::Position;
2020-04-29 17:33:22 +00:00
use std::str::FromStr;
2020-04-19 07:13:55 +00:00
#[test]
2020-04-29 17:33:22 +00:00
fn test_position_from_str() {
2020-04-19 07:13:55 +00:00
assert_eq!(
2020-04-29 17:33:22 +00:00
Position::from_str(&"4,12").unwrap(),
2020-04-19 07:13:55 +00:00
Position { x: 4, y: 12 }
);
}
2020-04-12 12:21:27 +00:00
2020-04-19 07:13:55 +00:00
#[test]
fn test_position_to_string() {
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
}
2020-04-12 12:21:27 +00:00
}