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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use alloc::borrow::Cow;
use alloc::vec::Vec;
use core::slice;
use nom::bytes::streaming::{tag, take_while, take};
use nom::combinator::{peek, opt};
use nom::branch::alt;
use nom::IResult;

pub const START_OF_HEADING: u8 = 0x01;
pub const START_OF_TEXT: u8 = 0x02;
pub const END_OF_TEXT: u8 = 0x03;
pub const ESCAPE: u8 = 0x1B;
pub const RECORD_SEPARATOR: u8 = 0x1E;
pub const UNIT_SEPARATOR: u8 = 0x1F;

#[derive(Debug)]
pub enum EndType {
    EndOfHeader,
    EndOfRecord,
    EndOfDocument,
}

#[derive(Debug)]
pub struct Unit<'a>(pub Cow<'a, [u8]>);

#[derive(Debug)]
pub struct Units<'a>{
    pub end_type: EndType,
    pub units: Vec<Unit<'a>>,
}

#[derive(Debug)]
pub struct Heading<'a>(pub Units<'a>);

#[derive(Debug)]
pub struct Document<'a>{
    pub heading: Option<Heading<'a>>,
    pub records: Vec<Units<'a>>,
}

pub fn is_control(input: u8) -> bool {
    matches!(
        input,
        START_OF_HEADING | START_OF_TEXT | END_OF_TEXT | ESCAPE | RECORD_SEPARATOR | UNIT_SEPARATOR
    )
}

/** Parse input into a unit, which may or may not be owned.
 * 
 * Will process escapes, but any and all other control characters are left unprocessed, expected to
 * be handled at another stage.  When successful, will always leave one non-escape control
 * character in the stream.
 */
pub fn parse_unit(input: &[u8]) -> IResult<&[u8], Unit<'_>> {
    let (input, unit) = take_while(|byte| !is_control(byte))(input)?;
    let (input, mut control) = peek(take(1u8))(input)?;
    if control[0] != ESCAPE {
        return Ok((input, Unit(unit.into())));
    }
    let mut unit: Vec<u8> = Vec::from(unit);
    let mut input = input;
    while control[0] == ESCAPE {
        // We peeked, so we know that input has at least 1 character at this point.
        input = &input[1..];
        let ret = take(1u8)(input)?;
        input = ret.0;
        unit.push(ret.1[0]);

        let ret = take_while(|byte| !is_control(byte))(input)?;
        input = ret.0;
        unit.extend(ret.1);

        control = peek(take(1u8))(input)?.1;
    }
    return Ok((input, Unit(unit.into())));
}

/** Parse input into a set of units, each of which may or may not be owned.
 * 
 * Will process escapes and unit separators, but any and all other control characters are left
 * unprocessed, expected to be handled at another stage.
 *
 * When successful, will always leave one non-escape control character in the stream.
 */
pub fn parse_units(mut input: &[u8]) -> IResult<&[u8], Units<'_>> {
    let mut output = Vec::new();
    loop {
        let (inner_input, unit) = parse_unit(input)?;
        output.push(unit);
        match inner_input[0] {
            RECORD_SEPARATOR => return Ok((inner_input, Units {
                units: output,
                end_type: EndType::EndOfRecord,
            })),
            START_OF_TEXT => return Ok((inner_input, Units {
                units: output,
                end_type: EndType::EndOfHeader,
            })),
            END_OF_TEXT => return Ok((inner_input, Units {
                units: output,
                end_type: EndType::EndOfDocument,
            })),
            _ => (),
        }
        // Strip out the UNIT_SEPARATOR
        input = &inner_input[1..];
    }
}

pub fn parse_heading(input: &[u8]) -> IResult<&[u8], Heading<'_>> {
    let (input, _) = tag(slice::from_ref(&START_OF_HEADING))(input)?;
    let (input, units) = parse_units(input)?;
    return Ok((input, Heading(units)));
}

/** Parse a body of records from a document.
 *
 * Used in service of parse_document.  This will not parse a header, but will parse the entire body
 * of a body document.
 */
pub fn parse_records(input: &[u8]) -> IResult<&[u8], Vec<Units<'_>>> {
    let (mut input, _) = tag(slice::from_ref(&START_OF_TEXT))(input)?;
    let mut records = Vec::new();
    loop {
        let (inner_input, units) = parse_units(input)?;
        records.push(units);
        let (inner_input, control) = alt((
                tag(slice::from_ref(&RECORD_SEPARATOR)),
                tag(slice::from_ref(&END_OF_TEXT)),
        ))(inner_input)?;
        if control[0] == END_OF_TEXT {
            return Ok((inner_input, records));
        }
        input = inner_input;
    }
}

/** Parse an entire document.
 *
 * Useful if you already have the entire document in memory or if you know it will all fit in
 * memory, otherwise stream the heading and all the records.
 */
pub fn parse_document(input: &[u8]) -> IResult<&[u8], Document<'_>> {
    let (input, heading) = opt(parse_heading)(input)?;
    let (input, records) = parse_records(input)?;
    return Ok((input, Document {
        heading,
        records,
    }));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unit() {
        let (input, parsed) = parse_unit(b"test_unit\x1F").unwrap();
        assert_eq!(input, b"\x1F");
        assert_eq!(parsed.0, &b"test_unit"[..]);
        assert!(matches!(parsed, Unit(Cow::Borrowed(_))), "borrowed when no escapes");

        let (input, parsed) = parse_unit(b"test_unit\x1B\x1Frest_of_unit\x1F").unwrap();
        assert_eq!(input, b"\x1F");
        assert_eq!(parsed.0, &b"test_unit\x1Frest_of_unit"[..]);
        assert!(matches!(parsed, Unit(Cow::Owned(_))), "owned when escapes");
    }

    #[test]
    fn units() {
        let (input, parsed) = parse_units(b"test_unit\x1Fsecond_test_unit\x1Fowned\x1B\x1Btext\x02").unwrap();
        assert_eq!(input, b"\x02");
        assert_eq!(parsed.units.len(), 3);
        assert_eq!(parsed.units[0].0, &b"test_unit"[..]);
        assert!(matches!(parsed.units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.units[1].0, &b"second_test_unit"[..]);
        assert!(matches!(parsed.units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.units[2].0, &b"owned\x1Btext"[..]);
        assert!(matches!(parsed.units[2].0, Cow::Owned(_)));
    }

    #[test]
    fn heading() {
        let (input, parsed) = parse_heading(b"\x01test_unit\x1Fsecond_test_unit\x1Fowned\x1B\x1Btext\x02").unwrap();
        assert_eq!(input, b"\x02");
        assert_eq!(parsed.0.units.len(), 3);
        assert_eq!(parsed.0.units[0].0, &b"test_unit"[..]);
        assert!(matches!(parsed.0.units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.0.units[1].0, &b"second_test_unit"[..]);
        assert!(matches!(parsed.0.units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.0.units[2].0, &b"owned\x1Btext"[..]);
        assert!(matches!(parsed.0.units[2].0, Cow::Owned(_)));
    }

    #[test]
    fn records() {
        let (input, parsed) = parse_records(b"\x02test_unit\x1Fsecond_test_unit\x1Fowned\x1B\x1Btext\x1Erecord_2_unit\x1F2_second_test_unit\x1Fowned\x1B\x1Btext_2\x03").unwrap();
        assert_eq!(input, b"");
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].units.len(), 3);
        assert_eq!(parsed[0].units[0].0, &b"test_unit"[..]);
        assert!(matches!(parsed[0].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed[0].units[1].0, &b"second_test_unit"[..]);
        assert!(matches!(parsed[0].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed[0].units[2].0, &b"owned\x1Btext"[..]);
        assert!(matches!(parsed[0].units[2].0, Cow::Owned(_)));
        assert_eq!(parsed[1].units.len(), 3);
        assert_eq!(parsed[1].units[0].0, &b"record_2_unit"[..]);
        assert!(matches!(parsed[1].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed[1].units[1].0, &b"2_second_test_unit"[..]);
        assert!(matches!(parsed[1].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed[1].units[2].0, &b"owned\x1Btext_2"[..]);
        assert!(matches!(parsed[1].units[2].0, Cow::Owned(_)));
    }

    #[test]
    fn document_headingless() {
        let (input, parsed) = parse_document(b"\x02test_unit\x1Fsecond_test_unit\x1Fowned\x1B\x1Btext\x1Erecord_2_unit\x1F2_second_test_unit\x1Fowned\x1B\x1Btext_2\x03").unwrap();
        assert_eq!(input, b"");
        assert!(matches!(parsed.heading, None));
        assert_eq!(parsed.records.len(), 2);
        assert_eq!(parsed.records[0].units.len(), 3);
        assert_eq!(parsed.records[0].units[0].0, &b"test_unit"[..]);
        assert!(matches!(parsed.records[0].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[0].units[1].0, &b"second_test_unit"[..]);
        assert!(matches!(parsed.records[0].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[0].units[2].0, &b"owned\x1Btext"[..]);
        assert!(matches!(parsed.records[0].units[2].0, Cow::Owned(_)));
        assert_eq!(parsed.records[1].units.len(), 3);
        assert_eq!(parsed.records[1].units[0].0, &b"record_2_unit"[..]);
        assert!(matches!(parsed.records[1].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[1].units[1].0, &b"2_second_test_unit"[..]);
        assert!(matches!(parsed.records[1].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[1].units[2].0, &b"owned\x1Btext_2"[..]);
        assert!(matches!(parsed.records[1].units[2].0, Cow::Owned(_)));
    }

    #[test]
    fn document() {
        let (input, parsed) = parse_document(b"\x01alpha\x1Fbeta\x1Fgamma\x02test_unit\x1Fsecond_test_unit\x1Fowned\x1B\x1Btext\x1Erecord_2_unit\x1F\x1F\x03").unwrap();
        assert_eq!(input, b"");
        let heading = parsed.heading.unwrap();
        assert!(matches!(heading.0.units[0], Unit(Cow::Borrowed(b"alpha"))));
        assert!(matches!(heading.0.units[1], Unit(Cow::Borrowed(b"beta"))));
        assert!(matches!(heading.0.units[2], Unit(Cow::Borrowed(b"gamma"))));
        assert_eq!(parsed.records.len(), 2);
        assert_eq!(parsed.records[0].units.len(), 3);
        assert_eq!(parsed.records[0].units[0].0, &b"test_unit"[..]);
        assert!(matches!(parsed.records[0].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[0].units[1].0, &b"second_test_unit"[..]);
        assert!(matches!(parsed.records[0].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[0].units[2].0, &b"owned\x1Btext"[..]);
        assert!(matches!(parsed.records[0].units[2].0, Cow::Owned(_)));
        assert_eq!(parsed.records[1].units.len(), 3);
        assert_eq!(parsed.records[1].units[0].0, &b"record_2_unit"[..]);
        assert!(matches!(parsed.records[1].units[0].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[1].units[1].0, &b""[..]);
        assert!(matches!(parsed.records[1].units[1].0, Cow::Borrowed(_)));
        assert_eq!(parsed.records[1].units[2].0, &b""[..]);
        assert!(matches!(parsed.records[1].units[2].0, Cow::Borrowed(_)));
    }
}