Skip to content

Commit

Permalink
implement alt for dynamic arrays (#1754)
Browse files Browse the repository at this point in the history
  • Loading branch information
Geal committed May 5, 2024
1 parent 5c4fe61 commit 56b6e54
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/branch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,44 @@ impl<
}
}

impl<
Input: Clone,
Output,
Error: ParseError<Input>,
A: Parser<Input, Output = Output, Error = Error>,
> Parser<Input> for Choice<&mut [A]>
{
type Output = Output;
type Error = Error;

#[inline]
fn process<OM: crate::OutputMode>(
&mut self,
input: Input,
) -> crate::PResult<OM, Input, Self::Output, Self::Error> {
let mut error = None;

for branch in self.parser.iter_mut() {
match branch.process::<OM>(input.clone()) {
Err(Err::Error(e)) => match error {
None => error = Some(e),
Some(err) => error = Some(OM::Error::combine(err, e, |e1, e2| e1.or(e2))),
},
res => return res,
}
}

match error {
Some(e) => Err(Err::Error(OM::Error::map(e, |err| {
Error::append(input, ErrorKind::Alt, err)
}))),
None => Err(Err::Error(OM::Error::bind(|| {
Error::from_error_kind(input, ErrorKind::Alt)
}))),
}
}
}

macro_rules! permutation_trait(
(
$name1:ident $ty1:ident $item1:ident
Expand Down
16 changes: 16 additions & 0 deletions src/branch/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,22 @@ fn alt_array() {
assert_eq!(alt1(defg), Ok((&b"g"[..], (&b"def"[..]))));
}

#[test]
fn alt_dynamic_array() {
fn alt1(i: &[u8]) -> IResult<&[u8], &[u8]> {
alt(&mut [tag("a"), tag("bc"), tag("def")][..]).parse(i)
}

let a = &b"a"[..];
assert_eq!(alt1(a), Ok((&b""[..], (&b"a"[..]))));

let bc = &b"bc"[..];
assert_eq!(alt1(bc), Ok((&b""[..], (&b"bc"[..]))));

let defg = &b"defg"[..];
assert_eq!(alt1(defg), Ok((&b"g"[..], (&b"def"[..]))));
}

#[test]
fn permutation_test() {
#[allow(clippy::type_complexity)]
Expand Down

0 comments on commit 56b6e54

Please sign in to comment.