Skip to main content

microrti_encoding/fom/
serde_impl.rs

1//! `Serialize` and `Deserialize` of [`Value`]: natural shapes in human-readable formats, a tagged enum
2//! in binary formats (which cannot tell the shapes apart).
3
4use std::cell::Cell;
5use std::fmt;
6
7use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
8use serde::ser::{SerializeMap, Serializer};
9use serde::{Deserialize, Serialize};
10
11use super::value::{Enumerator, Value, VariantValue};
12
13const TAG_OCTET: &str = "$octet";
14const TAG_CHAR: &str = "$char";
15const TAG_FLOAT: &str = "$float";
16const TAG_BYTES: &str = "$bytes";
17const TAG_HANDLE: &str = "$handle";
18const TAG_RAW: &str = "$raw";
19const TAG_ENUM: &str = "$enum";
20const TAG_VARIANT: &str = "$variant";
21const TAGS: &[&str] =
22    &[TAG_OCTET, TAG_CHAR, TAG_FLOAT, TAG_BYTES, TAG_HANDLE, TAG_RAW, TAG_ENUM, TAG_VARIANT];
23
24/// Elements reserved ahead of time while reading a sequence or map of unknown honesty.
25const PREALLOCATION_LIMIT: usize = 1024;
26
27/// Deepest nesting of values that is deserialized. Values decoded from HLA data nest at most as deep as
28/// the data types (64 levels); the limit keeps hostile input of formats without a limit of their own
29/// from exhausting the stack.
30const MAX_DEPTH: usize = 128;
31
32thread_local! {
33    /// Nesting of the `Value` being deserialized on this thread.
34    static DEPTH: Cell<usize> = const { Cell::new(0) };
35}
36
37/// Counts one level of nesting for as long as it lives.
38struct DepthGuard;
39
40impl DepthGuard {
41    fn enter<E: de::Error>() -> Result<Self, E> {
42        DEPTH.with(|depth| {
43            if depth.get() >= MAX_DEPTH {
44                return Err(E::custom(format_args!("values nest deeper than {MAX_DEPTH} levels")));
45            }
46            depth.set(depth.get() + 1);
47            Ok(DepthGuard)
48        })
49    }
50}
51
52impl Drop for DepthGuard {
53    fn drop(&mut self) {
54        DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
55    }
56}
57
58/// The binary form, borrowing from a [`Value`]. Variant order and names match [`WireOwned`].
59#[derive(Serialize)]
60#[serde(rename = "Value")]
61enum WireRef<'a> {
62    Bool(bool),
63    Integer(i128),
64    Float(f64),
65    Octet(u8),
66    Char(char),
67    String(&'a str),
68    Bytes(&'a [u8]),
69    Enum(&'a Enumerator),
70    Array(&'a [Value]),
71    Record(&'a [(String, Value)]),
72    Variant(&'a VariantValue),
73    Handle(&'a [u8]),
74    Raw(&'a [u8]),
75}
76
77/// The binary form, owned.
78#[derive(Deserialize)]
79#[serde(rename = "Value")]
80enum WireOwned {
81    Bool(bool),
82    Integer(i128),
83    Float(f64),
84    Octet(u8),
85    Char(char),
86    String(String),
87    Bytes(Vec<u8>),
88    Enum(Box<Enumerator>),
89    Array(Vec<Value>),
90    Record(Vec<(String, Value)>),
91    Variant(Box<VariantValue>),
92    Handle(Vec<u8>),
93    Raw(Vec<u8>),
94}
95
96impl<'a> From<&'a Value> for WireRef<'a> {
97    fn from(value: &'a Value) -> Self {
98        match value {
99            Value::Bool(value) => WireRef::Bool(*value),
100            Value::Integer(value) => WireRef::Integer(*value),
101            Value::Float(value) => WireRef::Float(*value),
102            Value::Octet(value) => WireRef::Octet(*value),
103            Value::Char(value) => WireRef::Char(*value),
104            Value::String(text) => WireRef::String(text),
105            Value::Bytes(octets) => WireRef::Bytes(octets),
106            Value::Enum(enumerator) => WireRef::Enum(enumerator),
107            Value::Array(items) => WireRef::Array(items),
108            Value::Record(fields) => WireRef::Record(fields),
109            Value::Variant(variant) => WireRef::Variant(variant),
110            Value::Handle(octets) => WireRef::Handle(octets),
111            Value::Raw(octets) => WireRef::Raw(octets),
112        }
113    }
114}
115
116impl From<WireOwned> for Value {
117    fn from(wire: WireOwned) -> Self {
118        match wire {
119            WireOwned::Bool(value) => Value::Bool(value),
120            WireOwned::Integer(value) => Value::Integer(value),
121            WireOwned::Float(value) => Value::Float(value),
122            WireOwned::Octet(value) => Value::Octet(value),
123            WireOwned::Char(value) => Value::Char(value),
124            WireOwned::String(text) => Value::String(text),
125            WireOwned::Bytes(octets) => Value::Bytes(octets),
126            WireOwned::Enum(enumerator) => Value::Enum(enumerator),
127            WireOwned::Array(items) => Value::Array(items),
128            WireOwned::Record(fields) => Value::Record(fields),
129            WireOwned::Variant(variant) => Value::Variant(variant),
130            WireOwned::Handle(octets) => Value::Handle(octets),
131            WireOwned::Raw(octets) => Value::Raw(octets),
132        }
133    }
134}
135
136fn to_hex(octets: &[u8]) -> String {
137    const DIGITS: &[u8; 16] = b"0123456789abcdef";
138    let mut text = String::with_capacity(octets.len() * 2);
139    for octet in octets {
140        text.push(char::from(DIGITS[usize::from(octet >> 4)]));
141        text.push(char::from(DIGITS[usize::from(octet & 0x0f)]));
142    }
143    text
144}
145
146fn from_hex(text: &str) -> Option<Vec<u8>> {
147    let digit = |character: u8| char::from(character).to_digit(16).and_then(|value| u8::try_from(value).ok());
148    let (pairs, rest) = text.as_bytes().as_chunks::<2>();
149    if !rest.is_empty() {
150        return None;
151    }
152    pairs.iter().map(|[high, low]| Some((digit(*high)? << 4) | digit(*low)?)).collect()
153}
154
155fn non_finite_name(value: f64) -> &'static str {
156    if value.is_nan() {
157        "NaN"
158    } else if value > 0.0 {
159        "inf"
160    } else {
161        "-inf"
162    }
163}
164
165fn non_finite_value(name: &str) -> Option<f64> {
166    match name {
167        "NaN" => Some(f64::NAN),
168        "inf" => Some(f64::INFINITY),
169        "-inf" => Some(f64::NEG_INFINITY),
170        _ => None,
171    }
172}
173
174/// An object with the single key `tag`.
175fn tagged<S: Serializer, T: Serialize + ?Sized>(
176    serializer: S,
177    tag: &str,
178    payload: &T,
179) -> Result<S::Ok, S::Error> {
180    let mut map = serializer.serialize_map(Some(1))?;
181    map.serialize_entry(tag, payload)?;
182    map.end()
183}
184
185impl Serialize for Value {
186    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
187        if !serializer.is_human_readable() {
188            return WireRef::from(self).serialize(serializer);
189        }
190        match self {
191            Value::Bool(value) => serializer.serialize_bool(*value),
192            Value::Integer(value) => {
193                if let Ok(narrow) = i64::try_from(*value) {
194                    serializer.serialize_i64(narrow)
195                } else if let Ok(narrow) = u64::try_from(*value) {
196                    serializer.serialize_u64(narrow)
197                } else {
198                    serializer.serialize_i128(*value)
199                }
200            }
201            Value::Float(value) if value.is_finite() => serializer.serialize_f64(*value),
202            Value::Float(value) => tagged(serializer, TAG_FLOAT, non_finite_name(*value)),
203            Value::Octet(value) => tagged(serializer, TAG_OCTET, value),
204            Value::Char(value) => tagged(serializer, TAG_CHAR, value),
205            Value::String(text) => serializer.serialize_str(text),
206            Value::Bytes(octets) => tagged(serializer, TAG_BYTES, &to_hex(octets)),
207            Value::Enum(enumerator) => tagged(serializer, TAG_ENUM, &**enumerator),
208            Value::Array(items) => serializer.collect_seq(items),
209            Value::Record(fields) => {
210                let mut map = serializer.serialize_map(Some(fields.len()))?;
211                for (name, value) in fields {
212                    if name.starts_with('$') {
213                        map.serialize_entry(&format!("${name}"), value)?;
214                    } else {
215                        map.serialize_entry(name, value)?;
216                    }
217                }
218                map.end()
219            }
220            Value::Variant(variant) => tagged(serializer, TAG_VARIANT, &**variant),
221            Value::Handle(octets) => tagged(serializer, TAG_HANDLE, &to_hex(octets)),
222            Value::Raw(octets) => tagged(serializer, TAG_RAW, &to_hex(octets)),
223        }
224    }
225}
226
227impl<'de> Deserialize<'de> for Value {
228    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
229        let _depth = DepthGuard::enter::<D::Error>()?;
230        if deserializer.is_human_readable() {
231            // Self-describing formats only; the binary branch never asks the format what comes next.
232            deserializer.deserialize_any(ReadableVisitor)
233        } else {
234            WireOwned::deserialize(deserializer).map(Value::from)
235        }
236    }
237}
238
239struct ReadableVisitor;
240
241impl ReadableVisitor {
242    fn octets<'de, A: MapAccess<'de>>(map: &mut A) -> Result<Vec<u8>, A::Error> {
243        let text: String = map.next_value()?;
244        from_hex(&text).ok_or_else(|| {
245            de::Error::invalid_value(de::Unexpected::Str(&text), &"an even number of hex digits")
246        })
247    }
248}
249
250impl<'de> Visitor<'de> for ReadableVisitor {
251    type Value = Value;
252
253    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.write_str("an HLA value: a boolean, a number, a string, an array or an object")
255    }
256
257    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Value, E> {
258        Ok(Value::Bool(value))
259    }
260
261    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Value, E> {
262        Ok(Value::Integer(i128::from(value)))
263    }
264
265    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
266        Ok(Value::Integer(i128::from(value)))
267    }
268
269    fn visit_i128<E: de::Error>(self, value: i128) -> Result<Value, E> {
270        Ok(Value::Integer(value))
271    }
272
273    fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
274        i128::try_from(value)
275            .map(Value::Integer)
276            .map_err(|_| E::custom(format_args!("the integer {value} is too large")))
277    }
278
279    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Value, E> {
280        Ok(Value::Float(value))
281    }
282
283    fn visit_str<E: de::Error>(self, text: &str) -> Result<Value, E> {
284        Ok(Value::String(text.to_owned()))
285    }
286
287    fn visit_string<E: de::Error>(self, text: String) -> Result<Value, E> {
288        Ok(Value::String(text))
289    }
290
291    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
292        let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(PREALLOCATION_LIMIT));
293        while let Some(item) = seq.next_element()? {
294            items.push(item);
295        }
296        Ok(Value::Array(items))
297    }
298
299    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
300        let Some(first) = map.next_key::<String>()? else {
301            return Ok(Value::Record(Vec::new()));
302        };
303        if first.starts_with('$') && !first.starts_with("$$") {
304            let value = match first.as_str() {
305                TAG_OCTET => Value::Octet(map.next_value()?),
306                TAG_CHAR => Value::Char(map.next_value()?),
307                TAG_FLOAT => {
308                    let name: String = map.next_value()?;
309                    Value::Float(non_finite_value(&name).ok_or_else(|| {
310                        de::Error::invalid_value(de::Unexpected::Str(&name), &"NaN, inf or -inf")
311                    })?)
312                }
313                TAG_BYTES => Value::Bytes(Self::octets(&mut map)?),
314                TAG_HANDLE => Value::Handle(Self::octets(&mut map)?),
315                TAG_RAW => Value::Raw(Self::octets(&mut map)?),
316                TAG_ENUM => Value::Enum(Box::new(map.next_value()?)),
317                TAG_VARIANT => Value::Variant(Box::new(map.next_value()?)),
318                other => return Err(de::Error::unknown_field(other, TAGS)),
319            };
320            return match map.next_key::<String>()? {
321                None => Ok(value),
322                Some(extra) => Err(de::Error::custom(format_args!(
323                    "'{first}' must be the only key of its object, found '{extra}' too"
324                ))),
325            };
326        }
327
328        let mut fields = Vec::with_capacity(map.size_hint().unwrap_or(0).min(PREALLOCATION_LIMIT));
329        let mut next = Some(first);
330        while let Some(key) = next {
331            let name = match key.strip_prefix('$') {
332                None => key,
333                Some(escaped) if escaped.starts_with('$') => escaped.to_owned(),
334                Some(_) => {
335                    return Err(de::Error::custom(format_args!(
336                        "'{key}' cannot be mixed with record fields; a field name that starts with '$' is \
337                         written with '$$'"
338                    )));
339                }
340            };
341            fields.push((name, map.next_value()?));
342            next = map.next_key::<String>()?;
343        }
344        Ok(Value::Record(fields))
345    }
346}