pub(in crate::data::executor) fn encode<T: zerompk::ToMessagePack>(
value: &T,
) -> crate::Result<Vec<u8>> {
zerompk::to_msgpack_vec(value).map_err(|e| crate::Error::Codec {
detail: format!("response serialization: {e}"),
})
}
pub(in crate::data::executor) fn encode_json(value: &serde_json::Value) -> crate::Result<Vec<u8>> {
nodedb_types::json_to_msgpack(value).map_err(|e| crate::Error::Codec {
detail: format!("response serialization: {e}"),
})
}
pub(in crate::data::executor) fn encode_serde<T: serde::Serialize>(
value: &T,
) -> crate::Result<Vec<u8>> {
let json_value = serde_json::to_value(value).map_err(|e| crate::Error::Codec {
detail: format!("serde serialization: {e}"),
})?;
encode_json(&json_value)
}
pub(in crate::data::executor) fn encode_json_vec(
values: &[serde_json::Value],
) -> crate::Result<Vec<u8>> {
let wrapped: Vec<nodedb_types::JsonValue> = values
.iter()
.map(|v| nodedb_types::JsonValue(v.clone()))
.collect();
zerompk::to_msgpack_vec(&wrapped).map_err(|e| crate::Error::Codec {
detail: format!("response serialization: {e}"),
})
}
pub(in crate::data::executor) fn encode_value_vec(
values: &[nodedb_types::Value],
) -> crate::Result<Vec<u8>> {
let mut buf = Vec::with_capacity(values.len() * 64);
let n = values.len();
if n <= 15 {
buf.push(0x90 | n as u8);
} else if n <= 0xFFFF {
buf.push(0xDC);
buf.extend_from_slice(&(n as u16).to_be_bytes());
} else {
buf.push(0xDD);
buf.extend_from_slice(&(n as u32).to_be_bytes());
}
for val in values {
let encoded = nodedb_types::value_to_msgpack(val).map_err(|e| crate::Error::Codec {
detail: format!("value serialization: {e}"),
})?;
buf.extend_from_slice(&encoded);
}
Ok(buf)
}
pub(in crate::data::executor) fn encode_count(key: &str, count: usize) -> crate::Result<Vec<u8>> {
let mut map = std::collections::BTreeMap::new();
map.insert(key, count);
zerompk::to_msgpack_vec(&map).map_err(|e| crate::Error::Codec {
detail: format!("count response serialization: {e}"),
})
}
pub fn decode_payload_to_json(payload: &[u8]) -> String {
if payload.is_empty() {
return String::new();
}
let first = payload[0];
let is_likely_json = first == b'['
|| first == b'{'
|| first == b'"'
|| first.is_ascii_digit()
|| first == b't'
|| first == b'f'
|| first == b'n';
if is_likely_json {
return String::from_utf8_lossy(payload).into_owned();
}
nodedb_types::msgpack_to_json_string(payload)
.unwrap_or_else(|_| String::from_utf8_lossy(payload).into_owned())
}