summaryrefslogtreecommitdiff
path: root/src/bin/day_5.rs
blob: 07f7af8c8a65953ef187db5878a5880b2daecd85 (plain)
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
use aoc2019::*;
use std::io;
use std::io::prelude::*;
use std::process;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "Day 5: Sunny with a Chance of Asteroids")]
/// Executes an Intcode program
///
/// The program is read from stdin as a series of comma-separated
/// values. Newlines are ignored.
///
/// See https://adventofcode.com/2019/day/5 for details.
struct Opt {
    #[structopt(short = "i", long = "input")]
    input: Vec<Intcode>,
}

fn main() {
    let stdin = io::stdin();
    let opt = Opt::from_args();

    let program: IntcodeProgram = stdin
        .lock()
        .split(b',')
        .map(|x| exit_on_failed_assertion(x, "Error reading input"))
        .map(|x| exit_on_failed_assertion(String::from_utf8(x), "Input was not valid UTF-8"))
        .map(|x| exit_on_failed_assertion(x.trim().parse::<Intcode>(), "Invalid number"))
        .collect::<IntcodeProgram>()
        .with_input(opt.input.into_iter().collect());

    let result = exit_on_failed_assertion(program.execute(), "Program errored");
    println!("{}", result);
}

fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
    match data {
        Ok(data) => data,
        Err(e) => {
            eprintln!("{}: {}", message, e);
            process::exit(1);
        }
    }
}