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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use std::fmt::{self, Display};

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Token<'b> {
    bytes: &'b [u8],
    quoted: bool,
}

impl<'tn> Token<'tn> {
    pub fn text_node(bytes: &'tn [u8], quoted: bool) -> Self {
        Token { bytes, quoted }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes
    }

    pub fn is_quoted(&self) -> bool {
        self.quoted
    }
}

impl<'b> Display for Token<'b> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(self.bytes))
    }
}

impl<'b> fmt::Debug for Token<'b> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.quoted {
            write!(f, "Token(\"{}\")", String::from_utf8_lossy(self.bytes))
        } else {
            write!(f, "Token({})", String::from_utf8_lossy(self.bytes))
        }
    }
}

impl<'b, const N: usize> From<&'b [u8; N]> for Token<'b> {
    fn from(bytes: &'b [u8; N]) -> Self {
        Self {
            bytes,
            quoted: false,
        }
    }
}

pub struct TokenDeclarations<'kv, 'k, 'tnv, 'tn> {
    tokens: &'tnv [Token<'tn>],
    keywords: &'kv [&'k [u8]],
    finished: bool,
}

pub fn declarations_by_keywords<'kv, 'k, 'tnv, 'tn>(
    tokens: &'tnv [Token<'tn>],
    keywords: &'kv [&'k [u8]],
) -> TokenDeclarations<'kv, 'k, 'tnv, 'tn> {
    TokenDeclarations {
        tokens,
        keywords,
        finished: false,
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TextNodeDeclaration<'tnv, 'tn> {
    option: &'tnv Token<'tn>,
    args: &'tnv [Token<'tn>],
}

impl<'tnv, 'tn> TextNodeDeclaration<'tnv, 'tn> {
    pub fn from_text_nodes(value: &'tnv [Token<'tn>]) -> Option<Self> {
        value
            .split_first()
            .map(|(option, args)| Self { option, args })
    }

    pub fn option(&self) -> &Token<'tn> {
        self.option
    }

    pub fn args(&self) -> &[Token<'tn>] {
        self.args
    }
}

impl<'kv, 'k, 'tnv, 'tn> Iterator for TokenDeclarations<'kv, 'k, 'tnv, 'tn> {
    type Item = TextNodeDeclaration<'tnv, 'tn>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        let mut text_nodes = self.tokens.iter();

        let start = text_nodes.position(|tn| self.keywords.iter().any(|&k| tn.as_bytes() == k));

        let Some(start) = start else {
            self.finished = true;
            return TextNodeDeclaration::from_text_nodes(self.tokens);
        };

        if start != 0 {
            self.finished = true;
            return TextNodeDeclaration::from_text_nodes(self.tokens);
        }

        let len = self.tokens.len();

        let end = text_nodes
            .position(|tn| self.keywords.iter().any(|&k| tn.as_bytes() == k))
            .map(|end| start + end + 1)
            .unwrap_or(len);

        if end >= len {
            self.finished = true;
        }

        let ret = TextNodeDeclaration::from_text_nodes(&self.tokens[start..end]);
        self.tokens = &self.tokens[end..];
        ret
    }
}

#[cfg(test)]
mod tests {

    use super::{declarations_by_keywords, TextNodeDeclaration, Token};

    fn to_text_nodes<'tn>(tns: &[&'tn [u8]]) -> Vec<Token<'tn>> {
        tns.iter().map(|&x| Token::text_node(x, false)).collect()
    }

    #[test]
    fn check_split_by_keywords() {
        let tns: &[&[u8]] = &[b"HELLO", b"world", b"FLAG", b"FLAG", b"COMMAND", b"command"];
        let text_nodes: Vec<_> = to_text_nodes(tns);
        let mut iter = declarations_by_keywords(&text_nodes, &[b"FLAG", b"HELLO", b"COMMAND"]);
        assert_eq!(
            TextNodeDeclaration::from_text_nodes(&to_text_nodes(&[b"HELLO", b"world"])),
            iter.next()
        );
        assert_eq!(
            TextNodeDeclaration::from_text_nodes(&to_text_nodes(&[b"FLAG"])),
            iter.next()
        );
        assert_eq!(
            TextNodeDeclaration::from_text_nodes(&to_text_nodes(&[b"FLAG"])),
            iter.next()
        );
        assert_eq!(
            TextNodeDeclaration::from_text_nodes(&to_text_nodes(&[b"COMMAND", b"command"])),
            iter.next()
        );
        assert_eq!(None, iter.next());
    }
}