Skip to main content

utils/
input.rs

1//! Items relating to puzzle input.
2
3use std::borrow::Cow;
4use std::error::Error;
5use std::fmt::{Display, Formatter};
6
7/// Enum for distinguishing between example and real inputs.
8///
9/// Some puzzles require this as different constants may be used for example inputs to simplify the
10/// problem. For example [2022 day 15](https://adventofcode.com/2022/day/15) part 1, which uses
11/// `y=10` in the example, but `y=2000000` for real inputs.
12///
13/// Most puzzle solutions should ignore this value.
14#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
15pub enum InputType {
16    Example,
17    Real,
18}
19
20/// Error type that shows the error's location in the input, returned by puzzle `new` functions.
21///
22/// # Examples
23///
24/// ```
25/// # use utils::input::InputError;
26/// let input = "12 34\n56 78\n90 abc";
27/// let error = InputError::new(input, 15, "expected number");
28/// assert_eq!(error.to_string(), "
29/// invalid input: expected number
30///   --> line 3 column 4
31///   |
32/// 3 | 90 abc
33///   |    ^
34/// ".trim_start());
35/// ```
36#[must_use]
37#[derive(Debug)]
38pub struct InputError(Box<Details>);
39
40#[derive(Debug)]
41struct Details {
42    line_number: usize,
43    column_number: usize,
44    line: String,
45    source: Box<dyn Error>,
46}
47
48impl InputError {
49    /// Create a new [`InputError`].
50    ///
51    /// See [`ToIndex`] implementations for details on supported indexes.
52    #[cold]
53    pub fn new(input: &str, index: impl ToIndex, source: impl Into<Box<dyn Error>>) -> Self {
54        let index = index.input_index(input);
55        let (line_number, column_number, line) = Self::line_position(input, index);
56        let line = line.replace('\t', " ");
57
58        InputError(Box::new(Details {
59            line_number,
60            column_number,
61            line,
62            source: source.into(),
63        }))
64    }
65
66    #[cold]
67    fn line_position(input: &str, index: usize) -> (usize, usize, String) {
68        let start = input[..index].rfind('\n').map_or(0, |p| p + 1);
69        let end = input[start..].find('\n').map_or(input.len(), |p| p + start);
70        let line = input[start..end].trim_suffix('\r');
71
72        let line_number = input[..start].matches('\n').count() + 1;
73        let column_number = index - start + 1;
74
75        (line_number, column_number, line.to_string())
76    }
77
78    /// Returns the source error.
79    #[must_use]
80    pub fn into_source(self) -> Box<dyn Error> {
81        self.0.source
82    }
83}
84
85impl Display for InputError {
86    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
87        let pad = " ".repeat(self.0.line_number.to_string().len());
88
89        write!(
90            f,
91            "invalid input: {}\n  --> line {} column {}\n{pad} |\n{} | {}\n{pad} |{}^\n",
92            self.0.source,
93            self.0.line_number,
94            self.0.column_number,
95            self.0.line_number,
96            self.0.line,
97            " ".repeat(self.0.column_number),
98        )
99    }
100}
101
102impl Error for InputError {
103    fn source(&self) -> Option<&(dyn Error + 'static)> {
104        Some(&*self.0.source)
105    }
106}
107
108/// Helper trait to simplify error location tracking.
109///
110/// Used in [`InputError::new`].
111pub trait ToIndex {
112    fn input_index(self, input: &str) -> usize;
113}
114
115impl ToIndex for &str {
116    /// Find index of this substring in the provided input.
117    ///
118    /// Uses the pointer offset, meaning it works if this substring is not the first occurrence in
119    /// the string. This allows recovering the error position without tracking an offset into the
120    /// string, which is useful when using [`Iterator`]s such as [`str::lines`] on an input.
121    ///
122    /// # Panics
123    ///
124    /// This function panics if this string is not a substring inside the provided string.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// # use utils::input::ToIndex;
130    /// let string = "abcabc";
131    /// assert_eq!(string[4..].input_index(string), 4);
132    /// ```
133    ///
134    /// ```should_panic
135    /// # use utils::input::ToIndex;
136    /// let string = "abcabc";
137    /// let mut other = String::new();
138    /// other.push('b');
139    /// other.push('c');
140    /// other.input_index(string);
141    /// ```
142    fn input_index(self, input: &str) -> usize {
143        self.as_bytes().input_index(input)
144    }
145}
146
147impl ToIndex for &[u8] {
148    /// Find index of this subslice in the provided input.
149    ///
150    /// For use with functions that iterate over a string's bytes.
151    /// See the [`&str`](#impl-ToIndex-for-%26str) implementation.
152    fn input_index(self, input: &str) -> usize {
153        match input.as_bytes().subslice_range(self) {
154            Some(range) => range.start,
155            None => panic!("invalid string index: {self:p} is not a substring of {input:p}"),
156        }
157    }
158}
159
160impl ToIndex for char {
161    /// Find the first instance of this character in the string.
162    ///
163    /// Intended for puzzles where the entire input should be a certain set of characters, so
164    /// if an invalid character is found, the instance in the error doesn't matter.
165    ///
166    /// # Panics
167    ///
168    /// This function panics if this character is not present in the string
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// # use utils::input::ToIndex;
174    /// let string = "abca bc";
175    /// assert_eq!(' '.input_index(string), 4);
176    /// ```
177    ///
178    /// ```should_panic
179    /// # use utils::input::ToIndex;
180    /// let string = "abcdef";
181    /// ' '.input_index(string);
182    /// ```
183    fn input_index(self, input: &str) -> usize {
184        input
185            .find(self)
186            .unwrap_or_else(|| panic!("invalid string index: char {self:?} not found in {input:?}"))
187    }
188}
189
190impl ToIndex for usize {
191    /// Index into the input string.
192    ///
193    /// # Panics
194    ///
195    /// This function panics if the index is out of range for the provided string.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// # use utils::input::ToIndex;
201    /// let string = "abcdef";
202    /// assert_eq!(4.input_index(string), 4);
203    /// ```
204    ///
205    /// ```should_panic
206    /// # use utils::input::ToIndex;
207    /// let string = "abcdef";
208    /// 10.input_index(string);
209    /// ```
210    fn input_index(self, input: &str) -> usize {
211        assert!(
212            self <= input.len(),
213            "invalid string index: index {self} out of range"
214        );
215        self
216    }
217}
218
219/// Strips the final newline from a borrowed string.
220///
221/// Equivalent to `s.strip_suffix("\r\n").or_else(|| s.strip_suffix("\n")).unwrap_or(s)`.
222///
223/// # Examples
224/// ```
225/// # use utils::input::strip_final_newline;
226/// assert_eq!(
227///     strip_final_newline("abc\ndef\n"),
228///     "abc\ndef"
229/// );
230/// assert_eq!(
231///     strip_final_newline("12\r\n34\r\n\r\n"),
232///     "12\r\n34\r\n"
233/// );
234/// ```
235#[must_use]
236#[inline]
237pub const fn strip_final_newline(s: &str) -> &str {
238    match s.as_bytes() {
239        // Use split_at as string slicing isn't const
240        [.., b'\r', b'\n'] => s.split_at(s.len() - 2).0,
241        [.., b'\n'] => s.split_at(s.len() - 1).0,
242        _ => s,
243    }
244}
245
246/// Convert a string to both LF and CRLF if it contains a newline.
247///
248/// # Examples
249/// ```
250/// # use utils::input::to_lf_crlf;
251/// assert_eq!(
252///     to_lf_crlf("abc\ndef\nghi"),
253///     ("abc\ndef\nghi".into(), Some("abc\r\ndef\r\nghi".into()))
254/// );
255/// assert_eq!(
256///     to_lf_crlf("12\r\n34\r\n56\r\n78"),
257///     ("12\n34\n56\n78".into(), Some("12\r\n34\r\n56\r\n78".into()))
258/// );
259/// assert_eq!(
260///     to_lf_crlf("abc123"),
261///     ("abc123".into(), None),
262/// );
263/// ```
264#[must_use]
265pub fn to_lf_crlf(s: &str) -> (Cow<'_, str>, Option<Cow<'_, str>>) {
266    let (mut has_lf, mut has_crlf) = (false, false);
267    let mut prev = 0;
268    for b in s.bytes() {
269        has_lf |= b == b'\n' && prev != b'\r';
270        has_crlf |= b == b'\n' && prev == b'\r';
271        prev = b;
272    }
273    if !has_lf && !has_crlf {
274        return (Cow::Borrowed(s), None);
275    }
276
277    let lf = if has_crlf {
278        Cow::Owned(s.replace("\r\n", "\n"))
279    } else {
280        Cow::Borrowed(s)
281    };
282    let crlf = if has_lf {
283        Cow::Owned(lf.replace('\n', "\r\n"))
284    } else {
285        Cow::Borrowed(s)
286    };
287    (lf, Some(crlf))
288}