microrti-encoding 0.3.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! `Serialize` and `Deserialize` of [`Value`]: natural shapes in human-readable formats, a tagged enum
//! in binary formats (which cannot tell the shapes apart).

use std::cell::Cell;
use std::fmt;

use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, Serializer};
use serde::{Deserialize, Serialize};

use super::value::{Enumerator, Value, VariantValue};

const TAG_OCTET: &str = "$octet";
const TAG_CHAR: &str = "$char";
const TAG_FLOAT: &str = "$float";
const TAG_BYTES: &str = "$bytes";
const TAG_HANDLE: &str = "$handle";
const TAG_RAW: &str = "$raw";
const TAG_ENUM: &str = "$enum";
const TAG_VARIANT: &str = "$variant";
const TAGS: &[&str] =
    &[TAG_OCTET, TAG_CHAR, TAG_FLOAT, TAG_BYTES, TAG_HANDLE, TAG_RAW, TAG_ENUM, TAG_VARIANT];

/// Elements reserved ahead of time while reading a sequence or map of unknown honesty.
const PREALLOCATION_LIMIT: usize = 1024;

/// Deepest nesting of values that is deserialized. Values decoded from HLA data nest at most as deep as
/// the data types (64 levels); the limit keeps hostile input of formats without a limit of their own
/// from exhausting the stack.
const MAX_DEPTH: usize = 128;

thread_local! {
    /// Nesting of the `Value` being deserialized on this thread.
    static DEPTH: Cell<usize> = const { Cell::new(0) };
}

/// Counts one level of nesting for as long as it lives.
struct DepthGuard;

impl DepthGuard {
    fn enter<E: de::Error>() -> Result<Self, E> {
        DEPTH.with(|depth| {
            if depth.get() >= MAX_DEPTH {
                return Err(E::custom(format_args!("values nest deeper than {MAX_DEPTH} levels")));
            }
            depth.set(depth.get() + 1);
            Ok(DepthGuard)
        })
    }
}

impl Drop for DepthGuard {
    fn drop(&mut self) {
        DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
    }
}

/// The binary form, borrowing from a [`Value`]. Variant order and names match [`WireOwned`].
#[derive(Serialize)]
#[serde(rename = "Value")]
enum WireRef<'a> {
    Bool(bool),
    Integer(i128),
    Float(f64),
    Octet(u8),
    Char(char),
    String(&'a str),
    Bytes(&'a [u8]),
    Enum(&'a Enumerator),
    Array(&'a [Value]),
    Record(&'a [(String, Value)]),
    Variant(&'a VariantValue),
    Handle(&'a [u8]),
    Raw(&'a [u8]),
}

/// The binary form, owned.
#[derive(Deserialize)]
#[serde(rename = "Value")]
enum WireOwned {
    Bool(bool),
    Integer(i128),
    Float(f64),
    Octet(u8),
    Char(char),
    String(String),
    Bytes(Vec<u8>),
    Enum(Box<Enumerator>),
    Array(Vec<Value>),
    Record(Vec<(String, Value)>),
    Variant(Box<VariantValue>),
    Handle(Vec<u8>),
    Raw(Vec<u8>),
}

impl<'a> From<&'a Value> for WireRef<'a> {
    fn from(value: &'a Value) -> Self {
        match value {
            Value::Bool(value) => WireRef::Bool(*value),
            Value::Integer(value) => WireRef::Integer(*value),
            Value::Float(value) => WireRef::Float(*value),
            Value::Octet(value) => WireRef::Octet(*value),
            Value::Char(value) => WireRef::Char(*value),
            Value::String(text) => WireRef::String(text),
            Value::Bytes(octets) => WireRef::Bytes(octets),
            Value::Enum(enumerator) => WireRef::Enum(enumerator),
            Value::Array(items) => WireRef::Array(items),
            Value::Record(fields) => WireRef::Record(fields),
            Value::Variant(variant) => WireRef::Variant(variant),
            Value::Handle(octets) => WireRef::Handle(octets),
            Value::Raw(octets) => WireRef::Raw(octets),
        }
    }
}

impl From<WireOwned> for Value {
    fn from(wire: WireOwned) -> Self {
        match wire {
            WireOwned::Bool(value) => Value::Bool(value),
            WireOwned::Integer(value) => Value::Integer(value),
            WireOwned::Float(value) => Value::Float(value),
            WireOwned::Octet(value) => Value::Octet(value),
            WireOwned::Char(value) => Value::Char(value),
            WireOwned::String(text) => Value::String(text),
            WireOwned::Bytes(octets) => Value::Bytes(octets),
            WireOwned::Enum(enumerator) => Value::Enum(enumerator),
            WireOwned::Array(items) => Value::Array(items),
            WireOwned::Record(fields) => Value::Record(fields),
            WireOwned::Variant(variant) => Value::Variant(variant),
            WireOwned::Handle(octets) => Value::Handle(octets),
            WireOwned::Raw(octets) => Value::Raw(octets),
        }
    }
}

fn to_hex(octets: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut text = String::with_capacity(octets.len() * 2);
    for octet in octets {
        text.push(char::from(DIGITS[usize::from(octet >> 4)]));
        text.push(char::from(DIGITS[usize::from(octet & 0x0f)]));
    }
    text
}

fn from_hex(text: &str) -> Option<Vec<u8>> {
    let digit = |character: u8| char::from(character).to_digit(16).and_then(|value| u8::try_from(value).ok());
    let (pairs, rest) = text.as_bytes().as_chunks::<2>();
    if !rest.is_empty() {
        return None;
    }
    pairs.iter().map(|[high, low]| Some((digit(*high)? << 4) | digit(*low)?)).collect()
}

fn non_finite_name(value: f64) -> &'static str {
    if value.is_nan() {
        "NaN"
    } else if value > 0.0 {
        "inf"
    } else {
        "-inf"
    }
}

fn non_finite_value(name: &str) -> Option<f64> {
    match name {
        "NaN" => Some(f64::NAN),
        "inf" => Some(f64::INFINITY),
        "-inf" => Some(f64::NEG_INFINITY),
        _ => None,
    }
}

/// An object with the single key `tag`.
fn tagged<S: Serializer, T: Serialize + ?Sized>(
    serializer: S,
    tag: &str,
    payload: &T,
) -> Result<S::Ok, S::Error> {
    let mut map = serializer.serialize_map(Some(1))?;
    map.serialize_entry(tag, payload)?;
    map.end()
}

impl Serialize for Value {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if !serializer.is_human_readable() {
            return WireRef::from(self).serialize(serializer);
        }
        match self {
            Value::Bool(value) => serializer.serialize_bool(*value),
            Value::Integer(value) => {
                if let Ok(narrow) = i64::try_from(*value) {
                    serializer.serialize_i64(narrow)
                } else if let Ok(narrow) = u64::try_from(*value) {
                    serializer.serialize_u64(narrow)
                } else {
                    serializer.serialize_i128(*value)
                }
            }
            Value::Float(value) if value.is_finite() => serializer.serialize_f64(*value),
            Value::Float(value) => tagged(serializer, TAG_FLOAT, non_finite_name(*value)),
            Value::Octet(value) => tagged(serializer, TAG_OCTET, value),
            Value::Char(value) => tagged(serializer, TAG_CHAR, value),
            Value::String(text) => serializer.serialize_str(text),
            Value::Bytes(octets) => tagged(serializer, TAG_BYTES, &to_hex(octets)),
            Value::Enum(enumerator) => tagged(serializer, TAG_ENUM, &**enumerator),
            Value::Array(items) => serializer.collect_seq(items),
            Value::Record(fields) => {
                let mut map = serializer.serialize_map(Some(fields.len()))?;
                for (name, value) in fields {
                    if name.starts_with('$') {
                        map.serialize_entry(&format!("${name}"), value)?;
                    } else {
                        map.serialize_entry(name, value)?;
                    }
                }
                map.end()
            }
            Value::Variant(variant) => tagged(serializer, TAG_VARIANT, &**variant),
            Value::Handle(octets) => tagged(serializer, TAG_HANDLE, &to_hex(octets)),
            Value::Raw(octets) => tagged(serializer, TAG_RAW, &to_hex(octets)),
        }
    }
}

impl<'de> Deserialize<'de> for Value {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let _depth = DepthGuard::enter::<D::Error>()?;
        if deserializer.is_human_readable() {
            // Self-describing formats only; the binary branch never asks the format what comes next.
            deserializer.deserialize_any(ReadableVisitor)
        } else {
            WireOwned::deserialize(deserializer).map(Value::from)
        }
    }
}

struct ReadableVisitor;

impl ReadableVisitor {
    fn octets<'de, A: MapAccess<'de>>(map: &mut A) -> Result<Vec<u8>, A::Error> {
        let text: String = map.next_value()?;
        from_hex(&text).ok_or_else(|| {
            de::Error::invalid_value(de::Unexpected::Str(&text), &"an even number of hex digits")
        })
    }
}

impl<'de> Visitor<'de> for ReadableVisitor {
    type Value = Value;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an HLA value: a boolean, a number, a string, an array or an object")
    }

    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Value, E> {
        Ok(Value::Bool(value))
    }

    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Value, E> {
        Ok(Value::Integer(i128::from(value)))
    }

    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
        Ok(Value::Integer(i128::from(value)))
    }

    fn visit_i128<E: de::Error>(self, value: i128) -> Result<Value, E> {
        Ok(Value::Integer(value))
    }

    fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
        i128::try_from(value)
            .map(Value::Integer)
            .map_err(|_| E::custom(format_args!("the integer {value} is too large")))
    }

    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Value, E> {
        Ok(Value::Float(value))
    }

    fn visit_str<E: de::Error>(self, text: &str) -> Result<Value, E> {
        Ok(Value::String(text.to_owned()))
    }

    fn visit_string<E: de::Error>(self, text: String) -> Result<Value, E> {
        Ok(Value::String(text))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
        let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(PREALLOCATION_LIMIT));
        while let Some(item) = seq.next_element()? {
            items.push(item);
        }
        Ok(Value::Array(items))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
        let Some(first) = map.next_key::<String>()? else {
            return Ok(Value::Record(Vec::new()));
        };
        if first.starts_with('$') && !first.starts_with("$$") {
            let value = match first.as_str() {
                TAG_OCTET => Value::Octet(map.next_value()?),
                TAG_CHAR => Value::Char(map.next_value()?),
                TAG_FLOAT => {
                    let name: String = map.next_value()?;
                    Value::Float(non_finite_value(&name).ok_or_else(|| {
                        de::Error::invalid_value(de::Unexpected::Str(&name), &"NaN, inf or -inf")
                    })?)
                }
                TAG_BYTES => Value::Bytes(Self::octets(&mut map)?),
                TAG_HANDLE => Value::Handle(Self::octets(&mut map)?),
                TAG_RAW => Value::Raw(Self::octets(&mut map)?),
                TAG_ENUM => Value::Enum(Box::new(map.next_value()?)),
                TAG_VARIANT => Value::Variant(Box::new(map.next_value()?)),
                other => return Err(de::Error::unknown_field(other, TAGS)),
            };
            return match map.next_key::<String>()? {
                None => Ok(value),
                Some(extra) => Err(de::Error::custom(format_args!(
                    "'{first}' must be the only key of its object, found '{extra}' too"
                ))),
            };
        }

        let mut fields = Vec::with_capacity(map.size_hint().unwrap_or(0).min(PREALLOCATION_LIMIT));
        let mut next = Some(first);
        while let Some(key) = next {
            let name = match key.strip_prefix('$') {
                None => key,
                Some(escaped) if escaped.starts_with('$') => escaped.to_owned(),
                Some(_) => {
                    return Err(de::Error::custom(format_args!(
                        "'{key}' cannot be mixed with record fields; a field name that starts with '$' is \
                         written with '$$'"
                    )));
                }
            };
            fields.push((name, map.next_value()?));
            next = map.next_key::<String>()?;
        }
        Ok(Value::Record(fields))
    }
}