error handling for position
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fmt::Formatter;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub struct Position {
|
||||
@@ -6,9 +9,14 @@ pub struct Position {
|
||||
pub y: u8,
|
||||
}
|
||||
|
||||
impl Position {
|
||||
#[inline]
|
||||
pub(crate) fn from(string: String) -> Result<Position, &'static dyn Error> {
|
||||
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");
|
||||
@@ -23,21 +31,22 @@ impl Position {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for Position {
|
||||
impl fmt::Display for Position {
|
||||
#[inline]
|
||||
fn to_string(&self) -> String {
|
||||
format!("{},{}", self.x, self.y)
|
||||
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_string() {
|
||||
fn test_position_from_str() {
|
||||
assert_eq!(
|
||||
Position::from("4,12".to_string()).unwrap(),
|
||||
Position::from_str(&"4,12").unwrap(),
|
||||
Position { x: 4, y: 12 }
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user