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
//! # Operation Order
//!
//! For part one the operator precedence is the same so we proceed from left to right for
//! each expression. Parentheses are handled via recursion, so we return either when encountering
//! the end of the string or a `)` character.
//!
//! For part two whenever we encounter the lower priority `*` operator then we *implicitly* insert
//! parentheses around the remaining expression. For example:
//!
//! * 1 * 2 * 3 * 4 => 1 * (2 * (3 * (4)))
//! * 1 + 2 * 3 + 4 => 1 + 2 * (3 + 4)
//! * 1 + (2 * 3 * 4) + 5 => 1 + (2 * (3 * (4))) + 5
use crate::util::parse::*;
use std::str::Bytes;

pub fn parse(input: &str) -> Vec<&str> {
    input.lines().collect()
}

pub fn part1(input: &[&str]) -> u64 {
    fn helper(bytes: &mut Bytes<'_>) -> u64 {
        let mut total = value(bytes, helper);

        while let Some(operation) = next(bytes) {
            let value = value(bytes, helper);
            if operation == b'+' {
                total += value;
            } else {
                total *= value;
            }
        }

        total
    }

    input.iter().map(|line| helper(&mut line.bytes())).sum()
}

pub fn part2(input: &[&str]) -> u64 {
    fn helper(bytes: &mut Bytes<'_>) -> u64 {
        let mut total = value(bytes, helper);

        while let Some(operation) = next(bytes) {
            if operation == b'+' {
                total += value(bytes, helper);
            } else {
                // Implicitly insert '(' and ')' around the remaining sub-expression so when it
                // finishes we break too.
                total *= helper(bytes);
                break;
            }
        }

        total
    }

    input.iter().map(|line| helper(&mut line.bytes())).sum()
}

/// Convenience wrapper around [`Bytes`] iterator. Encountering a `)` is also considered end of
/// sequence. The expressions are consistently formatted so encountering a space just means
/// skip and return the next character that will always be present.
fn next(bytes: &mut Bytes<'_>) -> Option<u8> {
    match bytes.next() {
        None | Some(b')') => None,
        Some(b' ') => bytes.next(),
        other => other,
    }
}

/// Convenience wrapper to return the value of either the next raw digit literal or a
/// sub-expression nested in parentheses.
fn value(bytes: &mut Bytes<'_>, helper: impl Fn(&mut Bytes<'_>) -> u64) -> u64 {
    match next(bytes).unwrap() {
        b'(' => helper(bytes),
        b => b.to_decimal() as u64,
    }
}