grippo 0.2.3

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
// Project:   grippo
// File:      src/format/msgpack.rs
// Purpose:   The MessagePack parser: one map an input into fields
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One `MessagePack` map an input, its fields named as `ndjson` names a JSON
//! record's: a nested key joins its parents with `.`, an array writes each
//! element under its key, and `nil` writes nothing.
//!
//! `MessagePack` is binary, so it goes through rmpv rather than a walker of
//! grippo's own. A string or binary value is borrowed from the input, and a string that
//! isn't UTF-8 is copied as its bytes. A key
//! that is a number or a boolean is written as its text, and an extension
//! value as its data bytes. An input that isn't a map is no match, and bytes
//! after the map are `Malformed`. Nesting past 64 containers, the root
//! counted, is `ParseError::Limit`.

use std::borrow::Cow;

use rmpv::ValueRef;
use rmpv::decode::{Error, read_value_ref_with_max_depth};

use super::tree::{MAX_DEPTH, Tree};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The `MessagePack` parser, registered as `msgpack`.
#[derive(Debug, Clone)]
pub struct Msgpack {
    signature: Signature,
}

impl Default for Msgpack {
    fn default() -> Self {
        Self::new()
    }
}

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

/// A float as decimal text in its shortest form, or an infinity or NaN as
/// text.
fn float(f: f64) -> FieldValue<'static> {
    if f.is_finite() {
        FieldValue::owned(format!("{f:?}").into_bytes(), Hint::Float)
    } else {
        FieldValue::owned(f.to_string().into_bytes(), Hint::Text)
    }
}

/// A scalar key's text.
fn key<'a>(k: &ValueRef<'a>) -> Result<Cow<'a, str>, ParseError> {
    let text = match k {
        ValueRef::String(s) => {
            return (*s)
                .into_str()
                .map(Cow::Borrowed)
                .ok_or(ParseError::Malformed {
                    offset: 0,
                    reason: "a `MessagePack` key that isn't UTF-8",
                });
        }
        ValueRef::Integer(n) => n.to_string(),
        ValueRef::Boolean(b) => b.to_string(),
        ValueRef::F32(f) => format!("{f:?}"),
        ValueRef::F64(f) => format!("{f:?}"),
        _ => {
            return Err(ParseError::Malformed {
                offset: 0,
                reason: "a `MessagePack` key that isn't a string, number or boolean",
            });
        }
    };
    Ok(Cow::Owned(text))
}

fn walk<'a>(tree: &mut Tree<'_, 'a>, value: ValueRef<'a>) -> Result<(), ParseError> {
    match value {
        ValueRef::Nil => tree.skip(),
        ValueRef::Boolean(b) => {
            let text: &'static [u8] = if b { b"true" } else { b"false" };
            tree.scalar(FieldValue::borrowed(text, Hint::Bool))?;
        }
        ValueRef::Integer(n) => {
            tree.scalar(FieldValue::owned(n.to_string().into_bytes(), Hint::Int))?;
        }
        ValueRef::F32(f) => tree.scalar(float(f64::from(f)))?,
        ValueRef::F64(f) => tree.scalar(float(f))?,
        ValueRef::String(s) => {
            let value = s.into_str().map_or_else(
                || FieldValue::owned(s.into_bytes(), Hint::Text),
                |text| FieldValue::borrowed(text.as_bytes(), Hint::Text),
            );
            tree.scalar(value)?;
        }
        ValueRef::Binary(b) | ValueRef::Ext(_, b) => {
            tree.scalar(FieldValue::borrowed(b, Hint::Text))?;
        }
        ValueRef::Array(items) => {
            tree.open_list()?;
            for item in items {
                walk(tree, item)?;
            }
            tree.close();
        }
        ValueRef::Map(entries) => {
            tree.open_map()?;
            for (k, v) in entries {
                tree.key(key(&k)?);
                walk(tree, v)?;
            }
            tree.close();
        }
    }
    Ok(())
}

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

    fn name(&self) -> &'static str {
        "msgpack"
    }

    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> {
        // fixmap, map 16 and map 32.
        if !matches!(input.first(), Some(0x80..=0x8f | 0xde | 0xdf)) {
            return Ok(Parsed::NoMatch);
        }
        let mut rest = input;
        let value = read_value_ref_with_max_depth(&mut rest, MAX_DEPTH).map_err(|e| match e {
            Error::DepthLimitExceeded => ParseError::Limit {
                what: "`MessagePack` nested deeper than 64 levels",
            },
            _ => ParseError::Malformed {
                offset: input.len() - rest.len(),
                reason: "`MessagePack` that ends early or holds a reserved byte",
            },
        })?;
        if !rest.is_empty() {
            return Err(ParseError::Malformed {
                offset: input.len() - rest.len(),
                reason: "bytes after the `MessagePack` map",
            });
        }
        let mut tree = Tree::new(out, input.len());
        let walked = walk(&mut tree, value);
        tree.finish(walked)?;
        Ok(Parsed::Done)
    }
}

#[cfg(test)]
mod tests {
    use rmpv::Value;

    use super::*;
    use crate::parse::Fields;

    fn encode(value: &Value) -> Vec<u8> {
        let mut buf = Vec::new();
        rmpv::encode::write_value(&mut buf, value).unwrap();
        buf
    }

    fn map(entries: Vec<(&str, Value)>) -> Value {
        Value::Map(
            entries
                .into_iter()
                .map(|(k, v)| (Value::from(k), v))
                .collect(),
        )
    }

    type Row = (String, Vec<u8>, Hint);

    fn rows(out: &Fields<'_>) -> Vec<Row> {
        out.as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), v.bytes.to_vec(), v.hint))
            .collect()
    }

    /// The fields an input writes, or the error it gives.
    type Want<'a> = Result<Vec<(&'a str, &'a [u8], Hint)>, &'a str>;

    #[test]
    fn maps_read_into_fields_or_fail_whole() {
        use Hint::{Bool, Float, Int, Text};
        let nested = map(vec![
            (
                "host",
                map(vec![
                    ("name", "web01".into()),
                    (
                        "ip",
                        Value::Array(vec!["10.0.0.1".into(), Value::Nil, 7.into()]),
                    ),
                ]),
            ),
            ("n", Value::F64(1.5)),
            ("f", Value::F32(0.25)),
            ("big", Value::from(u64::MAX)),
            ("neg", Value::from(-3)),
            ("ok", true.into()),
            ("gone", Value::Nil),
            ("a.b", Value::Binary(vec![0, 1])),
            ("x", Value::Ext(5, b"ext".to_vec())),
            (
                "l",
                Value::Array(vec![
                    map(vec![("k", "v".into())]),
                    Value::Array(vec![1.into()]),
                ]),
            ),
        ]);
        let odd_keys = Value::Map(vec![(1.into(), "one".into()), (true.into(), "t".into())]);
        let mut trailing = encode(&map(vec![("a", 1.into())]));
        trailing.push(0xc0);
        let deep = (0..70).fold(Value::from(1), |v, _| map(vec![("a", v)]));
        let cases: Vec<(Vec<u8>, Want<'_>)> = vec![
            (
                encode(&nested),
                Ok(vec![
                    ("host.name", b"web01", Text),
                    ("host.ip", b"10.0.0.1", Text),
                    ("host.ip", b"7", Int),
                    ("n", b"1.5", Float),
                    ("f", b"0.25", Float),
                    ("big", b"18446744073709551615", Int),
                    ("neg", b"-3", Int),
                    ("ok", b"true", Bool),
                    ("[\"a.b\"]", &[0, 1], Text),
                    ("x", b"ext", Text),
                    ("l.k", b"v", Text),
                    ("l", b"1", Int),
                ]),
            ),
            (
                encode(&odd_keys),
                Ok(vec![("1", b"one", Text), ("true", b"t", Text)]),
            ),
            (encode(&Value::Map(vec![])), Ok(vec![])),
            (encode(&Value::Array(vec![1.into()])), Err("no match")),
            (encode(&Value::from("text")), Err("no match")),
            (Vec::new(), Err("no match")),
            (
                encode(&map(vec![("a", "long string".into())]))[..6].to_vec(),
                Err("malformed"),
            ),
            (trailing, Err("malformed")),
            (vec![0x81, 0xc1, 0x01], Err("malformed")),
            (
                encode(&Value::Map(vec![(Value::Array(vec![]), 1.into())])),
                Err("malformed"),
            ),
            (
                // A one-entry map whose key is the string `\xff`.
                vec![0x81, 0xa1, 0xff, 0x01],
                Err("malformed"),
            ),
            (encode(&deep), Err("limit")),
        ];
        for (input, want) in cases {
            let mut out = Fields::new();
            out.push_prefix("outer.");
            let got = Msgpack::new().parse(&input, &mut out);
            out.pop_prefix();
            out.field("after", FieldValue::borrowed(b"1", Hint::Int));
            let mut got_rows = rows(&out);
            assert_eq!(
                got_rows.pop().map(|r| r.0),
                Some("after".to_owned()),
                "{input:x?}"
            );
            match (got, want) {
                (Ok(Parsed::Done), Ok(want)) => {
                    let want: Vec<Row> = want
                        .into_iter()
                        .map(|(n, v, h)| {
                            (
                                format!("outer.{n}").replace("outer.[", "outer["),
                                v.to_vec(),
                                h,
                            )
                        })
                        .collect();
                    assert_eq!(got_rows, want, "{input:x?}");
                }
                (Ok(Parsed::NoMatch), Err("no match"))
                | (Err(ParseError::Malformed { .. }), Err("malformed"))
                | (Err(ParseError::Limit { .. }), Err("limit")) => {
                    assert!(got_rows.is_empty(), "{input:x?} wrote {got_rows:?}");
                }
                (got, want) => panic!("{input:x?}: {got:?}, want {want:?}"),
            }
        }
    }

    #[test]
    fn strings_are_borrowed() {
        let input = encode(&map(vec![
            ("s", "text".into()),
            ("b", Value::Binary(vec![1])),
        ]));
        let mut out = Fields::new();
        Msgpack::new().parse(&input, &mut out).unwrap();
        assert!(
            out.as_slice()
                .iter()
                .all(|(_, v)| matches!(v.bytes, Cow::Borrowed(_)))
        );
    }

    /// A JSON value as `MessagePack`, numbers whole or `f64`.
    #[cfg(feature = "parse-ndjson")]
    fn to_msgpack(json: &serde_json::Value) -> Value {
        match json {
            serde_json::Value::Null => Value::Nil,
            serde_json::Value::Bool(b) => Value::Boolean(*b),
            serde_json::Value::Number(n) => n
                .as_i64()
                .map(Value::from)
                .or_else(|| n.as_u64().map(Value::from))
                .unwrap_or_else(|| Value::F64(n.as_f64().unwrap())),
            serde_json::Value::String(s) => Value::from(s.as_str()),
            serde_json::Value::Array(items) => Value::Array(items.iter().map(to_msgpack).collect()),
            serde_json::Value::Object(map) => Value::Map(
                map.iter()
                    .map(|(k, v)| (Value::from(k.as_str()), to_msgpack(v)))
                    .collect(),
            ),
        }
    }

    #[cfg(feature = "parse-ndjson")]
    mod generated {
        use proptest::prelude::*;

        use super::*;
        use crate::format::ndjson::Ndjson;

        fn value() -> impl Strategy<Value = serde_json::Value> {
            let leaf = prop_oneof![
                Just(serde_json::Value::Null),
                any::<bool>().prop_map(serde_json::Value::from),
                any::<i64>().prop_map(serde_json::Value::from),
                "[a-z0-9 .:\u{e9}\"]{0,12}".prop_map(serde_json::Value::from),
            ];
            leaf.prop_recursive(4, 40, 5, |inner| {
                prop_oneof![
                    prop::collection::vec(inner.clone(), 0..5).prop_map(serde_json::Value::from),
                    prop::collection::btree_map("[a-z.]{1,6}", inner, 0..5)
                        .prop_map(|m| serde_json::Value::Object(m.into_iter().collect())),
                ]
            })
        }

        proptest! {
            /// The same record as JSON through `ndjson` and as `MessagePack`
            /// through `msgpack` writes the same fields.
            #[test]
            fn msgpack_writes_what_ndjson_writes(
                entries in prop::collection::btree_map("[a-z.]{1,6}", value(), 0..6),
            ) {
                let json = serde_json::Value::Object(entries.into_iter().collect());
                let text = serde_json::to_vec(&json).unwrap();
                let packed = encode(&to_msgpack(&json));
                let mut want = Fields::new();
                Ndjson::new().parse(&text, &mut want).unwrap();
                let mut got = Fields::new();
                Msgpack::new().parse(&packed, &mut got).unwrap();
                prop_assert_eq!(rows(&got), rows(&want));
            }
        }
    }
}