diff options
| author | Josh Kingsley <josh@joshkingsley.me> | 2025-12-04 14:33:59 +0200 |
|---|---|---|
| committer | Josh Kingsley <josh@joshkingsley.me> | 2025-12-04 14:33:59 +0200 |
| commit | a69f1e59006b6fd5709e470d9f5af54879cffde4 (patch) | |
| tree | 40a26b6b421e5fdd97666632204398e4b44f1ce5 /day3/src | |
| parent | 6d26f1cbda0eaa41fc735a2e340ec7612a5461e0 (diff) | |
Day 3: parse input
Diffstat (limited to 'day3/src')
| -rw-r--r-- | day3/src/main.rs | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/day3/src/main.rs b/day3/src/main.rs new file mode 100644 index 0000000..dbbd303 --- /dev/null +++ b/day3/src/main.rs @@ -0,0 +1,72 @@ +use std::{env, fs, num::ParseIntError, str::FromStr}; + +#[derive(Debug)] +struct BatteryBank(Vec<u8>); + +struct ParseBatteryBankError; + +impl From<ParseIntError> for ParseBatteryBankError { + fn from(_: ParseIntError) -> Self { + Self + } +} + +impl FromStr for BatteryBank { + type Err = ParseBatteryBankError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Ok(Self( + s.chars() + .map(|ch| ch.to_string().parse()) + .collect::<Result<_, _>>()?, + )) + } +} + +#[derive(Debug)] +struct Input(Vec<BatteryBank>); + +#[derive(Debug)] +enum ParseInputError { + BadBank(String), +} + +impl FromStr for Input { + type Err = ParseInputError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Ok(Self( + s.split_whitespace() + .map(|bank| bank.parse().map_err(|_| ParseInputError::BadBank(s.into()))) + .collect::<Result<_, _>>()?, + )) + } +} + +#[derive(Debug)] +enum Error { + BadArgument, + BadInput(ParseInputError), +} + +impl From<std::io::Error> for Error { + fn from(value: std::io::Error) -> Self { + Self::BadArgument + } +} + +impl From<ParseInputError> for Error { + fn from(value: ParseInputError) -> Self { + Self::BadInput(value) + } +} + +fn main() -> Result<(), Error> { + let mut args = env::args(); + let input_path = args.nth(1).ok_or(Error::BadArgument)?; + let input: Input = fs::read_to_string(input_path)?.parse()?; + + dbg!(input); + + Ok(()) +} |
