bitsy-parser/src/position.rs

58 lines
1.2 KiB
Rust

use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Eq, PartialEq)]
pub struct Position {
pub x: u8,
pub y: u8,
}
impl Error for Position {}
impl FromStr for Position {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let string = s.to_string();
// e.g. "2,5"
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");
Ok(Position { x, y })
}
}
impl fmt::Display for Position {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.x, self.y)
}
}
#[cfg(test)]
mod test {
use crate::position::Position;
use std::str::FromStr;
#[test]
fn test_position_from_str() {
assert_eq!(
Position::from_str(&"4,12").unwrap(),
Position { x: 4, y: 12 }
);
}
#[test]
fn test_position_to_string() {
assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
}
}