Skip to main content

aoc/util/
parse.rs

1//! Extracts and parses signed and unsigned integers from surrounding text and whitespace.
2//!
3//! A common pattern in Advent of Code is to parse and return `123`, `456` and `789` from input
4//! resembling the following form:
5//!
6//! ```none
7//! Lorem ipsum 123 dolor 456 sit 789 amet
8//! ```
9//!
10//! This module provides two [`&str`] extension methods [`iter_signed`] and [`iter_unsigned`]. The
11//! reason for the separate methods is that some Advent of Code inputs contain the `-` character
12//! as a delimiter and this would cause numbers to be incorrectly parsed as negative.
13//!
14//! [`iter_unsigned`]: ParseExt::iter_unsigned
15//! [`iter_signed`]: ParseExt::iter_signed
16use std::iter::from_fn;
17
18use crate::util::integer::*;
19
20const MINUS: u8 = b'-'.wrapping_sub(b'0');
21
22pub trait ParseByteExt {
23    #[must_use]
24    fn to_decimal<T: Integer>(self) -> T;
25}
26
27impl ParseByteExt for u8 {
28    #[inline]
29    fn to_decimal<T: Integer>(self) -> T {
30        T::from(self.wrapping_sub(b'0'))
31    }
32}
33
34pub trait ParseExt {
35    #[must_use]
36    fn unsigned<T: Unsigned>(&self) -> T;
37    #[must_use]
38    fn signed<T: Signed>(&self) -> T;
39    #[must_use = "Iterators are lazy and do nothing unless consumed"]
40    fn iter_unsigned<T: Unsigned>(&self) -> impl Iterator<Item = T>;
41    #[must_use = "Iterators are lazy and do nothing unless consumed"]
42    fn iter_signed<T: Signed>(&self) -> impl Iterator<Item = T>;
43}
44
45impl<S: AsRef<str> + ?Sized> ParseExt for S {
46    #[inline]
47    fn unsigned<T: Unsigned>(&self) -> T {
48        let mut bytes = self.as_ref().bytes();
49        try_unsigned(&mut bytes).unwrap()
50    }
51
52    #[inline]
53    fn signed<T: Signed>(&self) -> T {
54        let mut bytes = self.as_ref().bytes();
55        try_signed(&mut bytes).unwrap()
56    }
57
58    #[inline]
59    fn iter_unsigned<T: Unsigned>(&self) -> impl Iterator<Item = T> {
60        let mut bytes = self.as_ref().bytes();
61        from_fn(move || try_unsigned(&mut bytes))
62    }
63
64    #[inline]
65    fn iter_signed<T: Signed>(&self) -> impl Iterator<Item = T> {
66        let mut bytes = self.as_ref().bytes();
67        from_fn(move || try_signed(&mut bytes))
68    }
69}
70
71fn try_unsigned<T: Unsigned>(bytes: &mut impl Iterator<Item = u8>) -> Option<T> {
72    let mut n = loop {
73        let digit = bytes.next()?.to_decimal();
74        if digit < 10 {
75            break T::from(digit);
76        }
77    };
78
79    for byte in bytes {
80        let digit = byte.to_decimal();
81        if digit >= 10 {
82            break;
83        }
84        n = T::TEN * n + T::from(digit);
85    }
86
87    Some(n)
88}
89
90fn try_signed<T: Signed>(bytes: &mut impl Iterator<Item = u8>) -> Option<T> {
91    let (mut n, negative) = loop {
92        let digit = bytes.next()?.to_decimal();
93        if digit == MINUS {
94            break (T::ZERO, true);
95        }
96        if digit < 10 {
97            break (T::from(digit), false);
98        }
99    };
100
101    for byte in bytes {
102        let digit = byte.to_decimal();
103        if digit >= 10 {
104            break;
105        }
106        n = T::TEN * n + T::from(digit);
107    }
108
109    Some(if negative { -n } else { n })
110}