grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
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
//! Rows answered over records, against a table and a model on `serde_json`.

use std::borrow::Cow;
use std::collections::BTreeMap;

use proptest::prelude::*;
use serde_json::Value;

use super::super::paths::tests::Style;
use super::*;

fn path(text: &str) -> Path {
    Path::parse(text).unwrap()
}

fn index(rows: &[(&str, &str, Compare)]) -> LiteralIndex {
    LiteralIndex::new(rows.iter().map(|&(p, l, c)| (path(p), l, c)))
}

#[test]
fn rows_match_by_text_or_string_in_declared_order() {
    use Compare::{String as S, Text as T};
    let rows = index(&[
        ("data_stream.dataset", "system.auth", T),
        ("f", "123", T),
        ("f", "123", S),
        ("data_stream.dataset", "system.auth", T),
        ("f", "1.50", T),
        ("ok", "true", T),
        ("ok", "true", S),
        ("n", "null", T),
        ("data_stream.dataset", "nginx.access", T),
    ]);
    let cases: &[(&str, &[usize])] = &[
        (r#"{"data_stream":{"dataset":"system.auth"}}"#, &[0, 3]),
        (
            r#"{"data_stream":{"dataset":"system.auth"},"f":123}"#,
            &[0, 1, 3],
        ),
        (r#"{"f":"123"}"#, &[1, 2]),
        ("{\"f\":\"\\u0031\\u00323\"}", &[1, 2]),
        (r#"{"f":123.0}"#, &[]),
        (r#"{"f":1.50}"#, &[4]),
        (r#"{"f":1.5}"#, &[]),
        (r#"{"ok":true}"#, &[5]),
        (r#"{"ok":"true"}"#, &[5, 6]),
        (r#"{"n":null}"#, &[]),
        (r#"{"n":"null"}"#, &[7]),
        (r#"{"f":[123]}"#, &[]),
        (r#"{"f":{"x":123}}"#, &[]),
        (r#"{"data_stream":"system.auth"}"#, &[]),
        (
            r#"{"data_stream":{"dataset":"nginx.access"},"f":"123"}"#,
            &[1, 2, 8],
        ),
        (
            r#"{"data_stream":{"dataset":"system.auth"},"f":tru}"#,
            &[0, 3],
        ),
        (r#"{"f":12"#, &[]),
        (r#"{"f":123,"f":"x"}"#, &[1]),
        ("[]", &[]),
        ("", &[]),
    ];
    check(&rows, cases);
    assert_eq!(rows.len(), 9);
    assert!(!rows.is_empty());
    assert!(index(&[]).is_empty());
}

/// Each record's rows from `matching`, and the first of them from `first`,
/// and the same from `matching_values` and `first_value` on the values read.
fn check(rows: &LiteralIndex, cases: &[(&str, &[usize])]) {
    let mut slots = Slots::new();
    let mut out = Vec::new();
    for &(json, want) in cases {
        rows.matching(json.as_bytes(), &mut slots, &mut out);
        assert_eq!(out, want, "{json}");
        assert_eq!(
            rows.first(json.as_bytes(), &mut slots),
            want.first().copied(),
            "{json}"
        );
        let read: Vec<Option<(Kind, Cow<'_, str>)>> = rows
            .paths
            .read(json.as_bytes(), &mut slots)
            .iter()
            .map(|slot| {
                let raw = slot.found()?;
                match raw.kind() {
                    Kind::String => raw.to_str().map(|s| (Kind::String, s)),
                    kind => Some((kind, Cow::Borrowed(raw.text()))),
                }
            })
            .collect();
        let values = || {
            read.iter().map(|v| {
                v.as_ref().and_then(|(kind, text)| match kind {
                    Kind::String => Some(Scalar::String(text)),
                    Kind::Number => Some(Scalar::Number(text)),
                    Kind::Bool => Some(Scalar::Bool(text == "true")),
                    Kind::Object | Kind::Array | Kind::Null => None,
                })
            })
        };
        rows.matching_values(values(), &mut out);
        assert_eq!(out, want, "values of {json}");
        let mut borrowed = Vec::new();
        for (path, value) in values().enumerate() {
            if let Some(value) = value {
                rows.rows_with(path, value, |ids| borrowed.extend_from_slice(ids));
            }
        }
        borrowed.sort_unstable();
        assert_eq!(borrowed, want, "rows_with of {json}");
        assert_eq!(rows.first_value(values()), want.first().copied(), "{json}");
    }
}

/// A value the caller supplies stands in for what the record holds.
#[test]
fn a_supplied_value_replaces_the_record() {
    use Compare::{String as S, Text as T};
    let rows = index(&[("a", "x", S), ("b", "7", T), ("a", "y", T)]);
    assert_eq!(rows.paths(), [path("a"), path("b")]);
    let mut out = Vec::new();
    let values = [Some(Scalar::String("y")), Some(Scalar::Number("7"))];
    rows.matching_values(values, &mut out);
    assert_eq!(out, [1, 2]);
    assert_eq!(rows.first_value([None, Some(Scalar::Bool(true))]), None);
    // Rows that share one Compare on a path come back as one run, in order.
    let run = index(&[("a", "x", T), ("b", "x", T), ("a", "x", T), ("a", "y", T)]);
    let mut runs: Vec<Vec<usize>> = Vec::new();
    run.rows_with(0, Scalar::String("x"), |ids| runs.push(ids.to_vec()));
    assert_eq!(runs, [vec![0, 2]]);
    run.rows_with(9, Scalar::String("x"), |_| panic!("no such path"));
}

/// scalo's parity cases: each number's text, and what both of its rules
/// engine's record kinds read it as.
#[cfg(feature = "parse")]
const PRINTED: &[(&str, &str)] = &[
    ("42", "42"),
    ("1.5", "1.5"),
    ("1.50", "1.5"),
    ("1e2", "100.0"),
    ("-2.5E-3", "-0.0025"),
    ("-0", "-0.0"),
    ("0", "0"),
    ("-7", "-7"),
    ("123456789012345678", "123456789012345678"),
    ("1234567890123456789", "1234567890123456789"),
    ("18446744073709551615", "18446744073709551615"),
    ("18446744073709551616", "1.8446744073709552e+19"),
    ("-9223372036854775808", "-9223372036854775808"),
    ("1.8446744073709552e+19", "1.8446744073709552e+19"),
    ("100.0", "100.0"),
    ("15e-1", "1.5"),
];

#[cfg(feature = "parse")]
#[test]
fn a_number_prints_as_serde_json_prints_it() {
    for &(text, printed) in PRINTED {
        let value: Value = serde_json::from_str(text).unwrap();
        assert_eq!(value.to_string(), printed, "serde_json {text}");
        assert_eq!(number_form(text), printed, "{text}");
    }
    for not_a_number in [
        "abc", "1e400", " 1.5", "1.5 ", "007", "+1", "-", "", "1.", "true",
    ] {
        assert_eq!(number_form(not_a_number), not_a_number);
    }
}

#[cfg(feature = "parse")]
#[test]
fn number_rows_read_a_number_as_serde_json_prints_it() {
    use Compare::{Number as N, String as S, Text as T};
    let rows = index(&[
        ("f", "42", N),
        ("f", "1.50", N),
        ("f", "1e2", N),
        ("f", "-2.5E-3", N),
        ("f", "-0", N),
        ("f", "-7", N),
        ("f", "18446744073709551616", N),
        ("f", "true", N),
        ("f", "1.50", T),
        ("f", "1.5", S),
        ("f", "abc", N),
        ("f", "1e400", N),
        ("f", "1234567890123456789", N),
        ("f", "42", T),
    ]);
    let cases: &[(&str, &[usize])] = &[
        (r#"{"f":42}"#, &[0, 13]),
        (r#"{"f":"42"}"#, &[0, 13]),
        (r#"{"f":42.0}"#, &[]),
        (r#"{"f":1.5}"#, &[1]),
        (r#"{"f":1.50}"#, &[1, 8]),
        (r#"{"f":15e-1}"#, &[1]),
        (r#"{"f":"1.50"}"#, &[1, 8]),
        (r#"{"f":"1.5"}"#, &[9]),
        (r#"{"f":100}"#, &[]),
        (r#"{"f":1e2}"#, &[2]),
        (r#"{"f":100.0}"#, &[2]),
        (r#"{"f":1E+2}"#, &[2]),
        (r#"{"f":"100.0"}"#, &[]),
        (r#"{"f":-0.0025}"#, &[3]),
        (r#"{"f":-2.5e-3}"#, &[3]),
        (r#"{"f":-0}"#, &[4]),
        (r#"{"f":-0.0}"#, &[4]),
        (r#"{"f":"-0"}"#, &[4]),
        (r#"{"f":0}"#, &[]),
        (r#"{"f":-7}"#, &[5]),
        (r#"{"f":18446744073709551616}"#, &[6]),
        (r#"{"f":1.8446744073709552e19}"#, &[6]),
        (r#"{"f":true}"#, &[7]),
        (r#"{"f":"true"}"#, &[7]),
        (r#"{"f":false}"#, &[]),
        (r#"{"f":"abc"}"#, &[10]),
        (r#"{"f":1e400}"#, &[11]),
        (r#"{"f":1234567890123456789}"#, &[12]),
        (r#"{"f":null}"#, &[]),
        (r#"{"f":[42]}"#, &[]),
        (r#"{"f":{"x":42}}"#, &[]),
        (r#"{"f":-07}"#, &[]),
        (r#"{"f":4"#, &[]),
        (r#"{"g":42}"#, &[]),
    ];
    check(&rows, cases);
}

#[test]
fn a_thousand_rows_on_one_path_are_one_lookup() {
    let rows = LiteralIndex::new((0..1_008).map(|i| {
        (
            path("data_stream.dataset"),
            format!("app{i}.log"),
            Compare::Text,
        )
    }));
    let mut slots = Slots::new();
    let mut out = Vec::new();
    rows.matching(
        br#"{"data_stream":{"dataset":"app1007.log"}}"#,
        &mut slots,
        &mut out,
    );
    assert_eq!(out, [1_007]);
    assert_eq!(rows.by_path.len(), 1);
}

/// A record's field: a value written by [`Style`], or a number's text written
/// as is.
#[derive(Debug, Clone)]
enum Field {
    Value(Value),
    Number(&'static str),
}

/// Each row true on `record`, from `serde_json`'s tree of it: a string, a
/// bool's word, a number's text as written for `Text`, or as `serde_json`
/// prints it for `Number`, with the literal printed the same way.
fn model(
    rows: &[(String, String, Compare)],
    fields: &BTreeMap<&str, Field>,
    record: &Value,
) -> Vec<usize> {
    rows.iter()
        .enumerate()
        .filter(
            |(_, (key, literal, compare))| match (record.get(key), compare) {
                (Some(Value::String(s)), _) => s == literal,
                (Some(Value::Bool(b)), Compare::Text) => &b.to_string() == literal,
                (Some(Value::Number(n)), Compare::Text) => match &fields[key.as_str()] {
                    Field::Number(text) => text == literal,
                    Field::Value(_) => &n.to_string() == literal,
                },
                #[cfg(feature = "parse")]
                (Some(Value::Bool(b)), Compare::Number) => &b.to_string() == literal,
                #[cfg(feature = "parse")]
                (Some(Value::Number(n)), Compare::Number) => {
                    n.to_string()
                        == literal
                            .parse::<serde_json::Number>()
                            .map_or_else(|_| literal.clone(), |l| l.to_string())
                }
                _ => false,
            },
        )
        .map(|(i, _)| i)
        .collect()
}

const FIELDS: &[&str] = &["a", "b", "a.b", "\u{e9}"];
const LITERALS: &[&str] = &[
    "1",
    "-2",
    "1.5",
    "1.50",
    "1e2",
    "100.0",
    "-0",
    "-0.0",
    "0",
    "1234567890123456789",
    "18446744073709551616",
    "1.8446744073709552e+19",
    "true",
    "false",
    "x",
    "x y",
    "\u{e9}\"\\",
    "",
];
/// Numbers in forms `serde_json` prints differently, or past the plain
/// integer bound.
const NUMBER_TEXTS: &[&str] = &[
    "1",
    "1.5",
    "1.50",
    "15e-1",
    "1e2",
    "1E+2",
    "100.0",
    "100",
    "-0",
    "-0.0",
    "0",
    "0e0",
    "123456789012345678",
    "1234567890123456789",
    "18446744073709551616",
    "-9223372036854775809",
];

fn literal_value() -> impl Strategy<Value = Value> {
    prop_oneof![
        prop::sample::select(LITERALS).prop_map(|s| Value::String(s.to_owned())),
        prop::sample::select(&[1_i64, -2, 7][..]).prop_map(Value::from),
        Just(Value::from(1.5)),
        any::<bool>().prop_map(Value::Bool),
        Just(Value::Null),
        Just(serde_json::json!([1])),
        Just(serde_json::json!({"x": "1"})),
    ]
}

fn field() -> impl Strategy<Value = Field> {
    prop_oneof![
        3 => literal_value().prop_map(Field::Value),
        1 => prop::sample::select(NUMBER_TEXTS).prop_map(Field::Number),
    ]
}

#[cfg(feature = "parse")]
const COMPARES: &[Compare] = &[Compare::Text, Compare::String, Compare::Number];
#[cfg(not(feature = "parse"))]
const COMPARES: &[Compare] = &[Compare::Text, Compare::String];

proptest! {
    #![proptest_config(ProptestConfig::with_cases(512))]

    #[test]
    fn matching_agrees_with_a_model_on_serde_json(
        rows in prop::collection::vec(
            (prop::sample::select(FIELDS), prop::sample::select(LITERALS), prop::sample::select(COMPARES)),
            0..24,
        ),
        fields in prop::collection::btree_map(prop::sample::select(FIELDS), field(), 0..4),
        seed in any::<u64>(),
        spaces in any::<bool>(),
        escapes in any::<bool>(),
    ) {
        let rows: Vec<(String, String, Compare)> = rows
            .into_iter()
            .map(|(k, l, c)| (k.to_owned(), l.to_owned(), c))
            .collect();
        let index = LiteralIndex::new(rows.iter().map(|(k, l, c)| {
            (Path::from_keys([k.as_str()]).unwrap(), l.as_str(), *c)
        }));
        let mut style = Style { seed: seed | 1, spaces, escapes };
        let mut json = String::from("{");
        for (i, (key, field)) in fields.iter().enumerate() {
            if i > 0 {
                style.space(&mut json);
                json.push(',');
            }
            style.space(&mut json);
            style.string(key, &mut json);
            style.space(&mut json);
            json.push(':');
            style.space(&mut json);
            match field {
                Field::Value(value) => style.write(value, &mut json),
                Field::Number(text) => json.push_str(text),
            }
        }
        style.space(&mut json);
        json.push('}');
        let record: Value = serde_json::from_str(&json).unwrap();
        let mut slots = Slots::new();
        let mut out = Vec::new();
        index.matching(json.as_bytes(), &mut slots, &mut out);
        let want = model(&rows, &fields, &record);
        prop_assert_eq!(&out, &want, "{}", json);
        prop_assert_eq!(index.first(json.as_bytes(), &mut slots), want.first().copied());
    }
}