1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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(())
}
|