Skip to content

Commit

Permalink
Add clearer conversion error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
pashadia committed Dec 18, 2023
1 parent a31222f commit 6f66114
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions src/core/card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,23 +299,32 @@ impl From<i32> for Card {
}

impl TryFrom<String> for Card {
type Error = &'static str;
type Error = String;
fn try_from(s: String) -> Result<Self, Self::Error> {
if s.len() != 2 {
return Err("Card string is not exactly a length of 2");
return Err(format!(
r#"Card string "{}" is not exactly a length of 2"#,
s
));
}

let mut chars = s.chars();

let value = Value::try_from(chars.next().unwrap());
if value.is_err() {
return Err("Card value was not a valid character");
return Err(format!(
r#"Card value "{}" was not a valid character"#,
value.unwrap_err()
));
}
let value = value.unwrap();

let suit = Suit::try_from(chars.next().unwrap());
if suit.is_err() {
return Err("Card suit was not a valid character");
return Err(format!(
r#"Card suit "{}" was not a valid character"#,
suit.unwrap_err()
));
}
let suit = suit.unwrap();

Expand All @@ -330,7 +339,7 @@ impl From<Card> for String {
}

impl FromStr for Card {
type Err = &'static str;
type Err = String;
fn from_str(s: &'_ str) -> Result<Self, Self::Err> {
Self::try_from(s.to_string())
}
Expand Down Expand Up @@ -397,4 +406,22 @@ mod tests {
assert_eq!(card.to_int(), 49);
}
}

#[test]
fn conversion_error() {
assert_eq!(
Card::from_str("xh").unwrap_err(),
r#"Card value "x" was not a valid character"#
);

assert_eq!(
Card::from_str("Ky").unwrap_err(),
r#"Card suit "y" was not a valid character"#,
);

assert_eq!(
Card::from_str("abc").unwrap_err(),
r#"Card string "abc" is not exactly a length of 2"#,
);
}
}

0 comments on commit 6f66114

Please sign in to comment.