grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Project:   grippo
// File:      src/format/ini.rs
// Purpose:   INI files, Java .properties and .env files, one document an input
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The INI family: INI, Java `.properties` and `.env`, one file an input.
//!
//! These are config files, read once, so they don't need grippo's speed: INI
//! goes through configparser, and `.properties` and `.env` are short line
//! scans no maintained crate does safely.
//!
//! - `ini`: a key under `[section]` writes `section.key`, a key before any
//!   section writes `key`. Keys keep their case, `=` or `:` splits a pair, and
//!   `;` or `#` opens a comment line. A key with no value writes nothing.
//! - `properties`: Java's `Properties.load` reading. `=`, `:` or white space
//!   ends a key, `#` or `!` opens a comment line, a trailing `\` joins the next
//!   line, and `\t`, `\n`, `\r`, `\f` and `\uXXXX` are undone.
//! - `dotenv`: `KEY=value` lines, `export` allowed in front. A value is
//!   single-quoted and kept as written, double-quoted with `\n`, `\r`, `\t`,
//!   `\\`, `\"` and `\$` undone, or bare up to a ` #` comment. `$NAME` is kept
//!   as written: nothing reads the host's environment.
//!
//! A key holding `.`, `[`, `]` or `"` is written quoted, as
//! [`crate::path`] reads it. A value is borrowed unless an escape was undone.
//! A document that fails anywhere writes nothing.

use std::borrow::Cow;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// Which file format a [`Ini`] reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Dialect {
    /// INI with `[section]` headers, registered as `ini`.
    Ini,
    /// Java `.properties`, registered as `properties`.
    Properties,
    /// `.env` files, registered as `dotenv`.
    Dotenv,
}

/// A parser for one [`Dialect`] of the INI family.
#[derive(Debug, Clone)]
pub struct Ini {
    dialect: Dialect,
    signature: Signature,
}

impl Ini {
    /// A parser for `dialect`.
    ///
    /// # Panics
    ///
    /// Never: an empty signature always builds.
    #[must_use]
    pub fn new(dialect: Dialect) -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self { dialect, signature }
    }

    /// The dialect it reads.
    #[must_use]
    pub const fn dialect(&self) -> Dialect {
        self.dialect
    }
}

/// The section name configparser holds keys before any header under. A
/// header can't hold a line end, so no file names it.
const NO_SECTION: &str = "\n";

impl Parser for Ini {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str {
        match self.dialect {
            Dialect::Ini => "ini",
            Dialect::Properties => "properties",
            Dialect::Dotenv => "dotenv",
        }
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let text = std::str::from_utf8(input).map_err(|e| ParseError::Malformed {
            offset: e.valid_up_to(),
            reason: "text that isn't UTF-8",
        })?;
        let mark = out.mark();
        let read = match self.dialect {
            Dialect::Ini => ini(text, out),
            Dialect::Properties => properties(text, out),
            Dialect::Dotenv => dotenv(text, out),
        };
        if read.is_err() {
            out.rollback(mark);
        }
        read.map(|()| Parsed::Done)
    }
}

fn ini(text: &str, out: &mut dyn FieldSink<'_>) -> Result<(), ParseError> {
    let mut reader = configparser::ini::Ini::new_cs();
    reader.set_default_section(NO_SECTION);
    let sections = reader
        .read(text.to_owned())
        .map_err(|_| ParseError::Malformed {
            offset: 0,
            reason: "an INI section header or key that doesn't parse",
        })?;
    for (section, pairs) in sections {
        let prefix = (section != NO_SECTION).then(|| key_part(Cow::Borrowed(&section)));
        if let Some(prefix) = &prefix {
            out.push_prefix(prefix);
            out.push_prefix(".");
        }
        for (key, value) in pairs {
            if let Some(value) = value {
                let value = FieldValue::owned(value.into_bytes(), Hint::Text);
                out.field(&key_part(Cow::Borrowed(&key)), value);
            }
        }
        if prefix.is_some() {
            out.pop_prefix();
            out.pop_prefix();
        }
    }
    Ok(())
}

/// Java's white space between a key and its value.
const fn java_space(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\x0c')
}

/// A `.properties` logical line: its text, borrowed when it is one natural
/// line, and the byte offset it starts at.
fn logical_lines(text: &str) -> impl Iterator<Item = (Cow<'_, str>, usize)> {
    let mut rest = text;
    let mut at = 0_usize;
    std::iter::from_fn(move || {
        loop {
            if rest.is_empty() {
                return None;
            }
            let (line, next) = split_line(rest);
            let start = at;
            at += rest.len() - next.len();
            rest = next;
            let body = line.trim_start_matches(java_space);
            if body.is_empty() || body.starts_with(['#', '!']) {
                continue;
            }
            if !continues(body) {
                return Some((Cow::Borrowed(body), start));
            }
            let mut joined = body[..body.len() - 1].to_owned();
            while !rest.is_empty() {
                let (line, next) = split_line(rest);
                at += rest.len() - next.len();
                rest = next;
                let line = line.trim_start_matches(java_space);
                if continues(line) {
                    joined.push_str(&line[..line.len() - 1]);
                } else {
                    joined.push_str(line);
                    break;
                }
            }
            return Some((Cow::Owned(joined), start));
        }
    })
}

/// The first natural line of `text`, and what follows its line end.
fn split_line(text: &str) -> (&str, &str) {
    text.find(['\n', '\r']).map_or((text, ""), |end| {
        let next = if text[end..].starts_with("\r\n") {
            end + 2
        } else {
            end + 1
        };
        (&text[..end], &text[next..])
    })
}

/// Whether a line ends in an odd run of `\`, which joins the next line.
fn continues(line: &str) -> bool {
    line.bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1
}

fn properties<'a>(text: &'a str, out: &mut dyn FieldSink<'a>) -> Result<(), ParseError> {
    for (line, at) in logical_lines(text) {
        let key_end = escaped_end(&line, |c| c == '=' || c == ':' || java_space(c));
        let after = line[key_end..].trim_start_matches(java_space);
        let value = after
            .strip_prefix(['=', ':'])
            .map_or(after, |v| v.trim_start_matches(java_space));
        let value_at = line.len() - value.len();
        let key = unescape_java(&line, 0..key_end, at)?;
        let value = unescape_java(&line, value_at..line.len(), at)?;
        out.field(
            &key_part(key),
            FieldValue {
                bytes: value_bytes(value),
                hint: Hint::Text,
            },
        );
    }
    Ok(())
}

/// The end of the text before the first unescaped char `stop` accepts.
fn escaped_end(line: &str, stop: impl Fn(char) -> bool) -> usize {
    let mut chars = line.char_indices();
    while let Some((i, c)) = chars.next() {
        if c == '\\' {
            chars.next();
        } else if stop(c) {
            return i;
        }
    }
    line.len()
}

/// `line[range]` with Java's escapes undone, borrowed from the input when
/// `line` is and holds none.
fn unescape_java<'a>(
    line: &Cow<'a, str>,
    range: std::ops::Range<usize>,
    at: usize,
) -> Result<Cow<'a, str>, ParseError> {
    let part = &line[range.clone()];
    if !part.contains('\\') {
        return Ok(match line {
            Cow::Borrowed(whole) => Cow::Borrowed(&whole[range]),
            Cow::Owned(_) => Cow::Owned(part.to_owned()),
        });
    }
    let bad = || ParseError::Malformed {
        offset: at,
        reason: "a `\\u` escape that isn't four hex digits",
    };
    let mut text = String::with_capacity(part.len());
    let mut chars = part.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            text.push(c);
            continue;
        }
        match chars.next() {
            Some('t') => text.push('\t'),
            Some('n') => text.push('\n'),
            Some('r') => text.push('\r'),
            Some('f') => text.push('\x0c'),
            Some('u') => {
                let hex: String = chars.by_ref().take(4).collect();
                let unit = (hex.len() == 4)
                    .then(|| u32::from_str_radix(&hex, 16).ok())
                    .flatten()
                    .ok_or_else(bad)?;
                if (0xd800..0xdc00).contains(&unit) && chars.as_str().starts_with("\\u") {
                    let low = chars
                        .as_str()
                        .get(2..6)
                        .and_then(|h| u32::from_str_radix(h, 16).ok());
                    if let Some(low @ 0xdc00..0xe000) = low {
                        chars.nth(5);
                        let pair = 0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00);
                        text.push(char::from_u32(pair).unwrap_or(char::REPLACEMENT_CHARACTER));
                        continue;
                    }
                }
                text.push(char::from_u32(unit).unwrap_or(char::REPLACEMENT_CHARACTER));
            }
            Some(other) => text.push(other),
            None => {}
        }
    }
    Ok(Cow::Owned(text))
}

fn value_bytes(value: Cow<'_, str>) -> Cow<'_, [u8]> {
    match value {
        Cow::Borrowed(v) => Cow::Borrowed(v.as_bytes()),
        Cow::Owned(v) => Cow::Owned(v.into_bytes()),
    }
}

/// Whether `key` is a `.env` key: letters, digits, `_` and `.`.
fn dotenv_key(key: &str) -> bool {
    !key.is_empty()
        && key
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.')
}

fn dotenv<'a>(text: &'a str, out: &mut dyn FieldSink<'a>) -> Result<(), ParseError> {
    let malformed = |offset, reason| ParseError::Malformed { offset, reason };
    let mut rest = text;
    while !rest.is_empty() {
        let at = text.len() - rest.len();
        let (line, next) = split_line(rest);
        let body = line.trim_start();
        if body.is_empty() || body.starts_with('#') {
            rest = next;
            continue;
        }
        let body = body
            .strip_prefix("export")
            .filter(|b| b.starts_with([' ', '\t']))
            .map_or(body, str::trim_start);
        let Some((key, value)) = body.split_once('=') else {
            return Err(malformed(at, "a `.env` line with no `=`"));
        };
        let key = key.trim_end();
        if !dotenv_key(key) {
            return Err(malformed(
                at,
                "a `.env` key of other than letters, digits, `_` and `.`",
            ));
        }
        let value = value.trim_start_matches([' ', '\t']);
        let value_at = text.len() - rest.len() + (line.len() - value.len());
        let (value, after) = if let Some(&quote @ (b'\'' | b'"')) = value.as_bytes().first() {
            quoted(text, value_at, quote)?
        } else {
            let bare = value
                .find(" #")
                .or_else(|| value.find("\t#"))
                .map_or(value, |end| &value[..end]);
            (Cow::Borrowed(bare.trim_end()), next)
        };
        out.field(
            &key_part(Cow::Borrowed(key)),
            FieldValue {
                bytes: value_bytes(value),
                hint: Hint::Text,
            },
        );
        rest = after;
    }
    Ok(())
}

/// The quoted `.env` value that opens at `at`, and the text after its line.
fn quoted(text: &str, at: usize, quote: u8) -> Result<(Cow<'_, str>, &str), ParseError> {
    let malformed = |reason| ParseError::Malformed { offset: at, reason };
    let open = &text[at + 1..];
    let close =
        closing(open, quote).ok_or_else(|| malformed("a `.env` quote that isn't closed"))?;
    let inner = &open[..close];
    let value = if quote == b'"' && inner.contains('\\') {
        Cow::Owned(unescape_dotenv(inner))
    } else {
        Cow::Borrowed(inner)
    };
    let (tail, next) = split_line(&open[close + 1..]);
    let tail = tail.trim_start();
    if !(tail.is_empty() || tail.starts_with('#')) {
        return Err(malformed("text after a closing quote in a `.env` value"));
    }
    Ok((value, next))
}

/// The offset of the quote that closes a value opened by `quote`, a `\`
/// escaping the next byte inside double quotes.
const fn closing(text: &str, quote: u8) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' if quote == b'"' => i += 2,
            b if b == quote => return Some(i),
            _ => i += 1,
        }
    }
    None
}

fn unescape_dotenv(inner: &str) -> String {
    let mut text = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            text.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => text.push('\n'),
            Some('r') => text.push('\r'),
            Some('t') => text.push('\t'),
            Some(c @ ('\\' | '"' | '$')) => text.push(c),
            Some(other) => {
                text.push('\\');
                text.push(other);
            }
            None => text.push('\\'),
        }
    }
    text
}

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

    /// A field as written: name, text, and whether it was borrowed.
    type Row = (String, String, bool);

    fn read(dialect: Dialect, text: &str) -> Result<Vec<Row>, ParseError> {
        let mut out = Fields::new();
        out.push_prefix("outer.");
        Ini::new(dialect).parse(text.as_bytes(), &mut out)?;
        out.pop_prefix();
        out.field("after", FieldValue::borrowed(b"1", Hint::Int));
        let rows: Vec<Row> = out
            .as_slice()
            .iter()
            .map(|(name, v)| {
                let borrowed = matches!(v.bytes, Cow::Borrowed(_));
                (
                    name.clone(),
                    String::from_utf8_lossy(&v.bytes).into_owned(),
                    borrowed,
                )
            })
            .collect();
        assert_eq!(
            rows.last().map(|r| r.0.as_str()),
            Some("after"),
            "prefixes popped"
        );
        Ok(rows[..rows.len() - 1].to_vec())
    }

    fn names(rows: &[Row]) -> Vec<(&str, &str)> {
        rows.iter()
            .map(|(n, v, _)| (n.as_str(), v.as_str()))
            .collect()
    }

    /// Each dialect's documents: the fields they write, or the error.
    #[test]
    fn documents_read_into_fields_or_fail_whole() {
        type Want = Result<&'static [(&'static str, &'static str)], &'static str>;
        let cases: &[(Dialect, &str, Want)] = &[
            (
                Dialect::Ini,
                "top = 1\n; note\n[server]\nHost = web01\nport: 8080\nflag\n\n[a.b]\n# c\nk=v=w\n",
                Ok(&[
                    ("outer.top", "1"),
                    ("outer.server.Host", "web01"),
                    ("outer.server.port", "8080"),
                    ("outer[\"a.b\"].k", "v=w"),
                ]),
            ),
            (Dialect::Ini, "[s]\nk = \n", Ok(&[("outer.s.k", "")])),
            (Dialect::Ini, "", Ok(&[])),
            (Dialect::Ini, "[s]\nk=1\nk=2\n", Ok(&[("outer.s.k", "2")])),
            (Dialect::Ini, "[open\nk=1\n", Err("section")),
            (Dialect::Ini, "[s]\n=1\n", Err("key")),
            (
                Dialect::Properties,
                "# c\n! c\nserver.port=8080\nname : web \\\n    01\nempty\nsp key\\ two  value\ntab\\tkey=\\u0041\\=b\nsmile=\\uD83D\\uDE00\\uD83D\n  \n",
                Ok(&[
                    ("outer[\"server.port\"]", "8080"),
                    ("outer.name", "web 01"),
                    ("outer.empty", ""),
                    ("outer.sp", "key two  value"),
                    ("outer.tab\tkey", "A=b"),
                    ("outer.smile", "\u{1F600}\u{FFFD}"),
                ]),
            ),
            (
                Dialect::Properties,
                "a=1\\\\\nb=2\r\nc=\\\r\n  3\\\n",
                Ok(&[("outer.a", "1\\"), ("outer.b", "2"), ("outer.c", "3")]),
            ),
            (Dialect::Properties, "a=\\u00zz\n", Err("\\u")),
            (Dialect::Properties, "a=\\u12\n", Err("\\u")),
            (
                Dialect::Dotenv,
                "# c\nexport HOST=web01\nPORT = 8080 # comment\nQ='$HOME \\n'\nD=\"a\\nb \\$X \\q\"\nM=\"one\ntwo\" # c\nE=\nexporter=1\nA.B=x#y\n",
                Ok(&[
                    ("outer.HOST", "web01"),
                    ("outer.PORT", "8080"),
                    ("outer.Q", "$HOME \\n"),
                    ("outer.D", "a\nb $X \\q"),
                    ("outer.M", "one\ntwo"),
                    ("outer.E", ""),
                    ("outer.exporter", "1"),
                    ("outer[\"A.B\"]", "x#y"),
                ]),
            ),
            (Dialect::Dotenv, "NOEQUALS\n", Err("no `=`")),
            (Dialect::Dotenv, "BAD KEY=1\n", Err("key")),
            (Dialect::Dotenv, "Q='open\n", Err("closed")),
            (Dialect::Dotenv, "Q=\"a\" b\n", Err("after a closing quote")),
        ];
        for &(dialect, text, want) in cases {
            let got = read(dialect, text);
            match (got, want) {
                (Ok(rows), Ok(want)) => assert_eq!(names(&rows), want, "{dialect:?} {text:?}"),
                (Err(ParseError::Malformed { reason, offset }), Err(want)) => {
                    assert!(reason.contains(want), "{dialect:?} {text:?}: {reason}");
                    assert!(offset <= text.len());
                }
                (got, want) => panic!("{dialect:?} {text:?}: {got:?}, want {want:?}"),
            }
        }
    }

    #[test]
    fn a_failed_document_writes_nothing_and_bad_bytes_fail() {
        for (dialect, text) in [
            (Dialect::Dotenv, &b"A=1\nB\n"[..]),
            (Dialect::Properties, b"a=1\nb=\\u12"),
            (Dialect::Ini, b"\xff=1"),
            (Dialect::Dotenv, b"A=\xc3"),
        ] {
            let mut out = Fields::new();
            let got = Ini::new(dialect).parse(text, &mut out);
            assert!(
                matches!(got, Err(ParseError::Malformed { .. })),
                "{dialect:?}"
            );
            assert!(out.is_empty(), "{dialect:?}");
        }
    }

    #[test]
    fn plain_values_are_borrowed_and_escaped_ones_owned() {
        let rows = read(Dialect::Properties, "a=plain\nb=x\\ty\n").unwrap();
        assert_eq!(rows.iter().map(|r| r.2).collect::<Vec<_>>(), [true, false]);
        let rows = read(Dialect::Dotenv, "A=plain\nB='q'\nC=\"x\\ny\"\n").unwrap();
        assert_eq!(
            rows.iter().map(|r| r.2).collect::<Vec<_>>(),
            [true, true, false]
        );
    }

    #[test]
    fn each_dialect_has_its_own_name() {
        let parsers = [Dialect::Ini, Dialect::Properties, Dialect::Dotenv].map(Ini::new);
        let got: Vec<&str> = parsers.iter().map(Parser::name).collect();
        assert_eq!(got, ["ini", "properties", "dotenv"]);
        for (name, p) in got.iter().zip(&parsers) {
            assert!(crate::parse::valid_parser_name(name));
            assert_eq!(Ini::new(p.dialect()).name(), *name);
        }
    }
}