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;
#[derive(Debug, Clone)]
pub struct Msgpack {
signature: Signature,
}
impl Default for Msgpack {
fn default() -> Self {
Self::new()
}
}
impl Msgpack {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self { signature }
}
}
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)
}
}
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> {
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()
}
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"),
),
(
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(_)))
);
}
#[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! {
#[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));
}
}
}
}