aoc_parse/util.rs
1//! Utility function for compatibility with aoc-runner.
2
3use crate::{ParseError, Parser};
4
5/// Parse the given puzzle input supplied by `#[aoc_generator]`.
6///
7/// This function is like `parser.parse(puzzle_input)` except that
8/// `#[aoc_generator]` unfortunately [strips off trailing newlines][bad]. This
9/// function therefore checks to see if the last line is missing its final `\n`
10/// and, if so, re-adds it before parsing.
11///
12/// # Example
13///
14/// ```no_run
15/// use aoc_runner_derive::*;
16/// use aoc_parse::{parser, prelude::*};
17///
18/// #[aoc_generator(day1)]
19/// fn parse_input(text: &str) -> anyhow::Result<Vec<Vec<u64>>> {
20/// let p = parser!(repeat_sep(lines(u64), "\n"));
21/// aoc_parse(text, p)
22/// }
23/// ```
24///
25/// [bad]: https://github.com/gobanos/aoc-runner/blob/master/src/lib.rs#L17
26#[doc(hidden)]
27pub fn aoc_parse<P, E>(puzzle_input: &str, parser: P) -> Result<P::Output, E>
28where
29 P: Parser,
30 E: From<ParseError>,
31{
32 let mut p = puzzle_input.to_string();
33 if !p.ends_with('\n') {
34 p.push('\n');
35 }
36 Ok(parser.parse(&p)?)
37}