refactor parse_n to not require borrowing closures

This commit is contained in:
Jan Christian Grünhage 2021-12-13 05:58:20 +01:00
parent 577e2a2c78
commit 123c62f810
4 changed files with 17 additions and 11 deletions

View file

@ -3,14 +3,14 @@ use crate::parsing::{newline, parse_n, parse_number};
use yap::Tokens;
pub fn parse_point(tokens: &mut impl Tokens<Item = char>) -> Option<Point> {
parse_n(tokens, &|t| parse_number(t), &|t| t.token(',')).map(|point: [usize; 2]| Point {
parse_n(tokens, |t| parse_number(t), |t| t.token(',')).map(|point: [usize; 2]| Point {
x: point[0],
y: point[1],
})
}
pub fn parse_line(tokens: &mut impl Tokens<Item = char>) -> Option<Line> {
parse_n(tokens, &|t| parse_point(t), &|t| t.tokens(" -> ".chars())).map(|points: [Point; 2]| {
parse_n(tokens, |t| parse_point(t), |t| t.tokens(" -> ".chars())).map(|points: [Point; 2]| {
Line {
start: points[0],
end: points[1],

View file

@ -7,8 +7,8 @@ use super::OctopusGrid;
pub fn parse_octopus_grid(tokens: &mut impl Tokens<Item = char>) -> Option<OctopusGrid> {
parse_n(
tokens,
&|t| parse_n(t, &|t| parse_digit(t), &|_| true),
&|t| newline(t),
|t| parse_n(t, |t| parse_digit(t), |_| true),
|t| newline(t),
)
.map(|grid| OctopusGrid { grid })
}

View file

@ -10,7 +10,7 @@ pub fn parse_cave_system(tokens: &mut impl Tokens<Item = char>) -> Option<CaveSy
}
pub fn parse_edge(tokens: &mut impl Tokens<Item = char>) -> Option<[Cave; 2]> {
parse_n(tokens, &|t| parse_cave(t), &|t| t.token('-'))
parse_n(tokens, |t| parse_cave(t), |t| t.token('-'))
}
pub fn parse_cave(tokens: &mut impl Tokens<Item = char>) -> Option<Cave> {

View file

@ -35,14 +35,20 @@ pub fn parse_number_with_radix<T: Num>(
.flatten()
}
pub fn parse_n<T: Debug, P: Tokens<Item = char>, const N: usize>(
tokens: &mut P,
parser: &dyn Fn(&mut P) -> Option<T>,
separator: &dyn Fn(&mut P) -> bool,
) -> Option<[T; N]> {
pub fn parse_n<R, T, I, P, S, const N: usize>(
tokens: &mut T,
parser: P,
separator: S,
) -> Option<[R; N]>
where
R: Debug,
T: Tokens<Item = I>,
P: FnMut(&mut T) -> Option<R>,
S: FnMut(&mut T) -> bool,
{
tokens
.sep_by(parser, separator)
.collect::<Vec<T>>()
.collect::<Vec<R>>()
.try_into()
.ok()
}