aoc_next/
parser.rs

1// SPDX-FileCopyrightText: 2020 Florian Warzecha <liketechnik@disroot.org>
2//
3// SPDX-License-Identifier: MPL-2.0
4
5use anyhow::Result;
6
7/// Container for a parsing function.
8///
9/// The contained function transforms the input file into
10/// a better usable structure.
11///
12/// Allows to have both failable and infailable parsers,
13/// respective [`Parser`] and [`FailableParser`] (where the function type is a result).
14pub trait Parsing<P> {
15    /// Transforms the file input into a better usable structure.
16    fn run(&self, input: &str) -> Result<P>;
17    /// The name of the parsing function.
18    fn name(&self) -> &'static str;
19}
20
21/// Container for an infailable parser.
22pub struct Parser<F, P>
23where
24    F: Fn(&str) -> P,
25{
26    pub run: F,
27    pub name: &'static str,
28}
29
30impl<F, P> Parsing<P> for Parser<F, P>
31where
32    F: Fn(&str) -> P,
33{
34    fn run(&self, input: &str) -> Result<P> {
35        Ok((self.run)(input))
36    }
37
38    fn name(&self) -> &'static str {
39        self.name
40    }
41}
42
43/// Container for an failable parser.
44pub struct FailableParser<F, P>
45where
46    F: Fn(&str) -> Result<P>,
47{
48    pub run: F,
49    pub name: &'static str,
50}
51
52impl<F, P> Parsing<P> for FailableParser<F, P>
53where
54    F: Fn(&str) -> Result<P>,
55{
56    fn run(&self, input: &str) -> Result<P> {
57        (self.run)(input)
58    }
59
60    fn name(&self) -> &'static str {
61        self.name
62    }
63}