diff options
Diffstat (limited to 'day1/src/main.rs')
| -rw-r--r-- | day1/src/main.rs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/day1/src/main.rs b/day1/src/main.rs new file mode 100644 index 0000000..778fc6d --- /dev/null +++ b/day1/src/main.rs @@ -0,0 +1,52 @@ +use std::str::FromStr; + +#[derive(Debug, PartialEq, Eq)] +enum Rotation { + Left(u16), + Right(u16), +} + +struct ParseRotationError(String); + +impl FromStr for Rotation { + type Err = ParseRotationError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + let mut chars = s.chars(); + let lr = chars.next().ok_or_else(|| ParseRotationError(s.into()))?; + let n: u16 = chars + .collect::<String>() + .parse() + .map_err(|_| ParseRotationError(s.into()))?; + + match lr { + 'L' => Ok(Self::Left(n)), + 'R' => Ok(Self::Right(n)), + _ => Err(ParseRotationError(s.into())), + } + } +} + +fn main() { + println!("Hello, world!"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_rotation() { + assert!("L2" + .parse::<Rotation>() + .is_ok_and(|rot| rot == Rotation::Left(2))); + + assert!("R929" + .parse::<Rotation>() + .is_ok_and(|rot| rot == Rotation::Right(929))); + + assert!("M1".parse::<Rotation>().is_err()); + assert!("L".parse::<Rotation>().is_err()); + assert!("2".parse::<Rotation>().is_err()); + } +} |
