1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::{eyre, Buffer, Parse};

use super::OneOf;

#[derive(Debug, Clone, PartialEq)]
/// `AnyOf1` is a generic type that implements [`Parse`] to match many characters within the given string
///
/// ```
/// use nommy::{Parse, IntoBuf, bytes::AnyOf1};
/// let mut buffer = "-_-.".bytes().into_buf();
/// let c: Vec<u8> = AnyOf1::<b"-_">::parse(&mut buffer).unwrap().into();
/// assert_eq!(c, b"-_-");
/// ```
pub struct AnyOf1<const BYTES: &'static [u8]>(Vec<u8>);

impl<const BYTES: &'static [u8]> From<AnyOf1<BYTES>> for Vec<u8> {
    fn from(v: AnyOf1<BYTES>) -> Self {
        v.0
    }
}

impl<const BYTES: &'static [u8]> Parse<u8> for AnyOf1<BYTES> {
    fn parse(input: &mut impl Buffer<u8>) -> eyre::Result<Self> {
        let mut output = Vec::new();

        while OneOf::<BYTES>::peek(&mut input.cursor()) {
            output.push(
                OneOf::<BYTES>::parse(input)
                    .expect("peek succeeded but parse failed")
                    .into(),
            );
        }

        if output.is_empty() {
            Err(eyre::eyre!("no characters found"))
        } else {
            Ok(Self(output))
        }
    }

    fn peek(input: &mut impl Buffer<u8>) -> bool {
        if !OneOf::<BYTES>::peek(input) {
            return false;
        }
        loop {
            let mut cursor = input.cursor();
            if !OneOf::<BYTES>::peek(&mut cursor) {
                break;
            }
            cursor.fast_forward_parent()
        }
        true
    }
}