aoc-rust 0.2.2

A tiny ergonomic helper crate for advent-of-code
Documentation
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::fmt::Display;
use std::path::Path;
use std::path::PathBuf;
use std::time::{Duration, Instant};

pub type Solver = fn(&str) -> Option<String>;

// ---------------------------------------------------------------------------
// Macro Exports
// ---------------------------------------------------------------------------

/// Generates `main` for a day. Expects 'part_one' and 'part_two' functions.
#[macro_export]
macro_rules! solution {
    ($year:expr, $day:expr) => {
        #[allow(unused_imports)]
        use $crate::debug;

        fn main() {
            if let ::core::result::Result::Err(e) = $crate::run(
                match ::core::option_env!("CARGO_MANIFEST_DIR") {
                    ::core::option::Option::Some(dir) => ::std::path::Path::new(dir),
                    ::core::option::Option::None => ::std::path::Path::new("."),
                },
                $year,
                $day,
                |input: &str| part_one(input).map(|a| ::std::string::ToString::to_string(&a)),
                |input: &str| part_two(input).map(|a| ::std::string::ToString::to_string(&a)),
            ) {
                ::std::eprintln!("error: {e}");
                ::std::process::exit(1);
            }
        }
    };
}

/// 'eprintln!' which does not get compiled into release builds.
#[macro_export]
macro_rules! debug {
    ($($t:tt)*) => {{
        #[cfg(debug_assertions)]
        {
            eprintln!($($t)*);
        }
    }};
}

// ---------------------------------------------------------------------------
// EntryPoint
// ---------------------------------------------------------------------------

struct Puzzle {
    root: PathBuf,
    year: u16,
    day: u8,
    part_one: Solver,
    part_two: Solver,
}

pub fn run(
    root: &Path,
    year: u16,
    day: u8,
    part_one: Solver,
    part_two: Solver,
) -> Result<(), String> {
    let puzzle = Puzzle {
        root: root.to_path_buf(),
        year,
        day,
        part_one,
        part_two,
    };
    Cli::parse().command.execute(&puzzle)
}

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

struct Cli {
    command: CliCommand,
}

enum CliCommand {
    Help,
    Run(Options),
}

#[derive(Debug, Default)]
enum Input {
    #[default]
    Puzzle,
    Example,
    Stdin,
    File(PathBuf),
}

#[derive(Debug, Default)]
struct Options {
    input: Input,
    submit: bool,
}

const HELP: &str = "\
Usage: <DAY> [OPTIONS]
       cargo run [--release] --bin <DAY> -- [OPTIONS]

Options:
  -s, --submit        Submit the answer of the highest solved part
  -e, --example       Use the example input instead of your puzzle input
  -f, --file <PATH>   Use the input file at <PATH> (- reads from stdin)
  -h, --help          Print help

By default, the puzzle input is read from data/inputs/<DAY>.txt.";

impl Cli {
    fn parse() -> Self {
        match Self::try_parse() {
            Ok(cli) => cli,
            Err(e) => {
                println!("{e}");
                std::process::exit(2);
            }
        }
    }

    fn try_parse() -> Result<Self, String> {
        let args: Vec<String> = std::env::args().skip(1).collect();
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        Ok(Cli {
            command: parse(&args, Options::default())?,
        })
    }
}

fn parse(args: &[&str], opts: Options) -> Result<CliCommand, String> {
    match args {
        [] => Ok(CliCommand::Run(opts)),
        ["-h" | "--help", ..] => Ok(CliCommand::Help),
        ["-s" | "--submit", rest @ ..] => parse(
            rest,
            Options {
                submit: true,
                ..opts
            },
        ),
        ["-e" | "--example", rest @ ..] => parse(
            rest,
            Options {
                input: Input::Example,
                ..opts
            },
        ),
        ["-f" | "--file", "-", rest @ ..] => parse(
            rest,
            Options {
                input: Input::Stdin,
                ..opts
            },
        ),
        ["-f" | "--file", path, rest @ ..] => parse(
            rest,
            Options {
                input: Input::File(PathBuf::from(path)),
                ..opts
            },
        ),
        ["-f" | "--file"] => Err("--file needs path".into()),
        [other, ..] => Err(format!("unknown option {other}")),
    }
}

impl CliCommand {
    fn execute(self, puzzle: &Puzzle) -> Result<(), String> {
        let Puzzle {
            ref root,
            year,
            day,
            part_one,
            part_two,
        } = *puzzle;

        match self {
            CliCommand::Run(opts) => {
                let input = match opts.input {
                    Input::Puzzle => get_input(root, year, day, false)?,
                    Input::Example => get_input(root, year, day, true)?,
                    Input::Stdin => std::io::read_to_string(std::io::stdin())
                        .map_err(|e| format!("failed to read from stdin: {e}"))?,
                    Input::File(path) => std::fs::read_to_string(&path)
                        .map_err(|e| format!("failed to read from {}: {e}", path.display()))?,
                };
                let answers = Answers::solve(&input, &(part_one, part_two));
                answers.print(year, day);

                if opts.submit {
                    let (part, answer) = answers.highest().ok_or("nothing to submit")?;
                    crate::submit(year, day, part, &answer)?;
                }
            }
            CliCommand::Help => {
                println!("{HELP}");
            }
        }
        Ok(())
    }
}

fn get_input(root: &Path, _year: u16, day: u8, example: bool) -> Result<String, String> {
    let path = if example {
        root.join(format!("data/examples/day{day:02}.txt"))
    } else {
        root.join(format!("data/inputs/day{day:02}.txt"))
    };
    std::fs::read_to_string(&path)
        .map_err(|e| format!("failed to read from {}: {e}", path.display()))
}

// ---------------------------------------------------------------------------
// Submitting
// ---------------------------------------------------------------------------

const USER_AGENT: &str = "github.com/zaperfish/aoc-rust";

#[derive(Debug)]
enum SubmissionResult {
    Correct,
    Wrong(Option<String>),
    TooSoon(Option<String>),
    WrongLevel,
    Unknown,
}

impl From<&String> for SubmissionResult {
    fn from(html: &String) -> Self {
        if html.contains("That's the right answer") {
            SubmissionResult::Correct
        } else if html.contains("That's not the right answer") {
            let hint = if html.contains("too high") {
                Some("Too high".to_string())
            } else if html.contains("too low") {
                Some("Too low".to_string())
            } else {
                None
            };
            SubmissionResult::Wrong(hint)
        } else if html.contains("You gave an answer too recently") {
            let wait = html
                .split_once("You have")
                .and_then(|(_, rest)| rest.split_once("left"))
                .map(|(wait, _)| wait.trim().to_string());
            SubmissionResult::TooSoon(wait)
        } else if html.contains("You don't seem to be solving the right level") {
            SubmissionResult::WrongLevel
        } else {
            SubmissionResult::Unknown
        }
    }
}

impl Display for SubmissionResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "\n  ")?;
        match self {
            SubmissionResult::Correct => {
                write!(f, "\x1b[92m*\\(^o^)/*\x1b[m That's the correct answer!")?;
            }
            SubmissionResult::Wrong(hint) => {
                write!(f, "\x1b[31m(>︿<)\x1b[m Wrong answer.",)?;
                if let Some(hint) = hint {
                    write!(f, " {hint}.")?;
                }
            }
            SubmissionResult::TooSoon(wait) => {
                write!(f, "(-.-) Too soon.",)?;
                if let Some(wait) = wait {
                    write!(f, " Please wait {wait}.")?;
                }
            }
            SubmissionResult::WrongLevel => {
                write!(f, "¯\\_(•_•)_/¯ You seem to be solving the wrong level.")?;
            }
            SubmissionResult::Unknown => {
                write!(f, "Could not deduce submission response from html",)?;
            }
        }
        writeln!(f, "")?;
        Ok(())
    }
}

fn session() -> Result<String, String> {
    if let Ok(s) = std::env::var("ADVENT_OF_CODE_SESSION") {
        return Ok(s.trim().to_string());
    }
    let home = std::env::var_os("HOME").ok_or("HOME is not set")?;
    let path = std::path::Path::new(&home).join(".adventofcode.session");
    std::fs::read_to_string(&path)
        .map(|s| s.trim().to_string())
        .map_err(|e| format!("no session cookie found ({}: {e})", path.display()))
}

fn submit(year: u16, day: u8, part: u8, answer: &str) -> Result<(), String> {
    println!("\nSubmitting \"{answer}\" for part {part}:");
    let session = session()?;
    let url = format!("https://adventofcode.com/{year}/day/{day}/answer");

    let output = std::process::Command::new("curl")
        .args([
            "--silent",
            "--show-error",
            "--fail",
            "--user-agent",
            USER_AGENT,
            "--cookie",
            &format!("session={session}"),
            "--data",
            &format!("level={part}"),
            "--data-urlencode",
            &format!("answer={answer}"),
            &url,
        ])
        .output()
        .map_err(|e| format!("could not run curl: {e}"))?;

    if !output.status.success() {
        return Err(format!(
            "request failed: {}",
            String::from_utf8_lossy(&output.stderr).trim(),
        ));
    }

    println!(
        "{}",
        SubmissionResult::from(&String::from_utf8_lossy(&output.stdout).to_string())
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// Puzzle Solving
// ---------------------------------------------------------------------------

struct Answer {
    value: String,
    time: Duration,
}

struct Answers {
    part_one: Option<Answer>,
    part_two: Option<Answer>,
}

pub trait Solution {
    fn part_one(&self, input: &str) -> Option<String>;
    fn part_two(&self, input: &str) -> Option<String>;
}

impl Answers {
    fn solve<S>(input: &str, solution: &S) -> Self
    where
        S: Solution,
    {
        Self {
            part_one: timed(|| solution.part_one(input)),
            part_two: timed(|| solution.part_two(input)),
        }
    }

    fn highest(&self) -> Option<(u8, String)> {
        match self {
            Self {
                part_two: Some(Answer { value, .. }),
                ..
            } => Some((2, value.to_owned())),
            Self {
                part_one: Some(Answer { value, .. }),
                part_two: None,
            } => Some((1, value.to_owned())),
            Self {
                part_one: None,
                part_two: None,
            } => None,
        }
    }

    fn print(&self, year: u16, day: u8) {
        println!("{year} Day {day}:");
        match self.part_one {
            Some(ref a) => {
                println!("  Part 1: {:<20} {:.2?}", a.value, a.time);
            }
            None => {
                println!("  Part 1: unsolved");
            }
        };
        match self.part_two {
            Some(ref a) => {
                println!("  Part 2: {:<20} {:.2?}", a.value, a.time);
            }
            None => {
                println!("  Part 2: unsolved");
            }
        };
    }
}

impl<F1, F2, T1, T2> Solution for (F1, F2)
where
    F1: Fn(&str) -> Option<T1>,
    F2: Fn(&str) -> Option<T2>,
    T1: Display,
    T2: Display,
{
    fn part_one(&self, input: &str) -> Option<String> {
        self.0(input).map(|a| a.to_string())
    }

    fn part_two(&self, input: &str) -> Option<String> {
        self.1(input).map(|a| a.to_string())
    }
}

fn timed<F>(f: F) -> Option<Answer>
where
    F: FnOnce() -> Option<String>,
{
    let start = Instant::now();
    let value = f()?;
    let time = start.elapsed();
    Some(Answer { value, time })
}