Skip to content

Commit 7cee8b5

Browse files
committed
impl From<char> for WhichHandle
1 parent 8857f30 commit 7cee8b5

2 files changed

Lines changed: 44 additions & 5 deletions

File tree

src/point.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -290,11 +290,21 @@ impl FromStr for PointType {
290290
impl FromStr for WhichHandle {
291291
type Err = ();
292292
fn from_str(s: &str) -> Result<WhichHandle, ()> {
293-
Ok(match s.trim() {
294-
"A" | "a" => WhichHandle::A,
295-
"B" | "b" => WhichHandle::B,
296-
_ => WhichHandle::Neither,
297-
})
293+
debug_assert!(s.chars().count() == 1);
294+
s.trim().chars().nth(0).map(|c| Ok(c.into())).unwrap_or(Err(()))
295+
}
296+
}
297+
298+
impl From<char> for WhichHandle {
299+
fn from(c: char) -> WhichHandle {
300+
match c {
301+
'A' | 'a' | 'A' | 'a' => WhichHandle::A,
302+
'B' | 'b' | 'B' | 'b' => WhichHandle::B,
303+
_ => {
304+
debug_assert!(c == 0 as char);
305+
WhichHandle::Neither
306+
},
307+
}
298308
}
299309
}
300310

tests/handle.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,32 @@ fn test_handles() {
1515
assert_eq!(wh.opposite(), WhichHandle::B);
1616
assert_eq!(wh.opposite().opposite(), WhichHandle::A);
1717
}
18+
19+
#[test]
20+
fn test_which_handle() {
21+
let wh1: WhichHandle = 'A'.into();
22+
assert_eq!(wh1, WhichHandle::A);
23+
let wh1: WhichHandle = 'A'.into();
24+
assert_eq!(wh1, WhichHandle::A);
25+
let wh1: WhichHandle = "A".into();
26+
assert_eq!(wh1, WhichHandle::A);
27+
let wh1: WhichHandle = "b".into();
28+
assert_eq!(wh1, WhichHandle::B);
29+
let wh1: WhichHandle = '\u{0}'.into();
30+
assert_eq!(wh1, WhichHandle::Neither);
31+
}
32+
33+
#[cfg(not(debug_assertions))]
34+
#[test]
35+
fn test_which_handle_nonstrict() {
36+
use std::str::FromStr as _;
37+
38+
let wh1: WhichHandle = " b ".into();
39+
assert_eq!(wh1, WhichHandle::B);
40+
let wh1: WhichHandle = 'C'.into();
41+
assert_eq!(wh1, WhichHandle::Neither);
42+
let wh1 = WhichHandle::from_str("");
43+
assert!(wh1.is_err());
44+
let wh1 = WhichHandle::from_str(" BBBB ");
45+
assert_eq!(wh1, Ok(WhichHandle::B));
46+
}

0 commit comments

Comments
 (0)