gcg_parser/gcg/events/
event.rs

1use crate::token::{Error, Result};
2
3#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4pub enum Coordinate {
5	Horizontal(u32, char),
6	Vertical(char, u32),
7}
8
9impl Coordinate {
10	/// # Examples
11	/// ```
12	/// # use gcg_parser::events::Coordinate;
13	/// # use anyhow::Ok;
14	///
15	/// let coordinate = Coordinate::build("a1")?;
16	/// assert_eq!(coordinate, Coordinate::Vertical('a', 1));
17	///
18	/// let coordinate = Coordinate::build("8n")?;
19	/// assert_eq!(coordinate, Coordinate::Horizontal(8, 'n'));
20	///
21	/// # Ok(())
22	/// ```
23	///
24	pub fn build(x: &str) -> Result<Self> {
25		let mut chars = x.chars();
26
27		match (chars.next(), chars.next()) {
28			(Some(first), Some(second)) if first.is_alphabetic() && second.is_ascii_digit() => {
29				Ok(Coordinate::Vertical(first, second.to_digit(10).unwrap()))
30			}
31			(Some(first), Some(second)) if first.is_ascii_digit() && second.is_alphabetic() => {
32				Ok(Coordinate::Horizontal(first.to_digit(10).unwrap(), second))
33			}
34			_ => Err(Error::InvalidToken {
35				token: "coordinate".to_string(),
36				text: x.to_string(),
37			}),
38		}
39	}
40}
41
42#[cfg(test)]
43mod tests {
44	use super::*;
45	use anyhow::{Ok, Result};
46
47	#[test]
48	fn should_not_parse_invalid_coords() -> Result<()> {
49		let s = "whatIsThis?";
50		let coordinates = Coordinate::build(s);
51
52		let error = coordinates.unwrap_err().to_string();
53
54		assert!(error.contains(s));
55
56		Ok(())
57	}
58}