Skip to main content

typwire/
any.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::fmt;
4
5use serde::de::value::MapAccessDeserializer;
6use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9#[cfg(feature = "decimal")]
10use crate::Decimal;
11#[cfg(feature = "regex")]
12use crate::Regex;
13use crate::{
14    Alignment, Angle, Arguments, Auto, Bytes, Color, DateTime, Duration, Gradient, Label, Length,
15    Path, Ratio, Stroke, Symbol, Type, Typwire, Version,
16    tag::{TAG_KEY, WithTag},
17};
18
19/// A dynamic value supported by the Typwire protocol.
20#[derive(Clone, Debug)]
21pub enum Any {
22    /// Typst `none`.
23    None,
24    /// Typst `auto`.
25    Auto,
26    /// A Typst `bool`.
27    Bool(bool),
28    /// A Typst `int`.
29    Integer(i64),
30    /// A Typst `float`.
31    Float(f64),
32    /// A Typst `str`.
33    String(String),
34    /// Typst `bytes`.
35    Bytes(Bytes),
36    /// A Typst `array` of dynamic values.
37    Array(Vec<Self>),
38    /// A Typst `dictionary` with string keys.
39    Dictionary(BTreeMap<String, Self>),
40    /// A Typst `angle`.
41    Angle(Angle),
42    /// A Typst `length`.
43    Length(Length),
44    /// A Typst `ratio`.
45    Ratio(Ratio),
46    /// A Typst `color`, in any of its color spaces.
47    Color(Color),
48    /// A Typst `gradient`.
49    Gradient(Gradient),
50    /// A Typst `datetime`.
51    DateTime(DateTime),
52    /// A Typst `duration`.
53    Duration(Duration),
54    /// A Typst `version`.
55    Version(Version),
56    /// A Typst `type`.
57    Type(Type),
58    /// A Typst `path`.
59    Path(Path),
60    /// A Typst `symbol`, including its modifier variants.
61    Symbol(Symbol),
62    /// Typst `arguments`.
63    Arguments(Arguments),
64    /// A Typst `label`.
65    Label(Label),
66    /// A Typst `alignment`.
67    Alignment(Alignment),
68    /// A Typst `stroke`.
69    Stroke(Stroke),
70    #[cfg(feature = "regex")]
71    /// A Typst `regex`.
72    Regex(Regex),
73    #[cfg(feature = "decimal")]
74    /// A Typst `decimal`.
75    Decimal(Decimal),
76}
77
78impl Serialize for Any {
79    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
80    where
81        S: Serializer,
82    {
83        match self {
84            Self::None => serializer.serialize_none(),
85            Self::Auto => Auto.serialize(serializer),
86            Self::Bool(value) => value.serialize(serializer),
87            Self::Integer(value) => value.serialize(serializer),
88            Self::Float(value) => value.serialize(serializer),
89            Self::String(value) => value.serialize(serializer),
90            Self::Bytes(value) => value.serialize(serializer),
91            Self::Array(value) => value.serialize(serializer),
92            Self::Dictionary(value) => value.serialize(serializer),
93            Self::Angle(value) => value.serialize(serializer),
94            Self::Length(value) => value.serialize(serializer),
95            Self::Ratio(value) => value.serialize(serializer),
96            Self::Color(value) => value.serialize(serializer),
97            Self::Gradient(value) => value.serialize(serializer),
98            Self::DateTime(value) => value.serialize(serializer),
99            Self::Duration(value) => value.serialize(serializer),
100            Self::Version(value) => value.serialize(serializer),
101            Self::Type(value) => value.serialize(serializer),
102            Self::Path(value) => value.serialize(serializer),
103            Self::Symbol(value) => value.serialize(serializer),
104            Self::Arguments(value) => value.serialize(serializer),
105            Self::Label(value) => value.serialize(serializer),
106            Self::Alignment(value) => value.serialize(serializer),
107            Self::Stroke(value) => value.serialize(serializer),
108            #[cfg(feature = "regex")]
109            Self::Regex(value) => value.serialize(serializer),
110            #[cfg(feature = "decimal")]
111            Self::Decimal(value) => value.serialize(serializer),
112        }
113    }
114}
115
116impl<'de> Deserialize<'de> for Any {
117    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118    where
119        D: Deserializer<'de>,
120    {
121        deserializer.deserialize_any(AnyVisitor)
122    }
123}
124
125impl Typwire for Any {}
126
127/// Builds an `Any` straight from the decoder's own callbacks, in one pass
128/// -- no intermediate `cbor4ii::core::Value` tree to build first and walk
129/// a second time. A map whose first key is `typwire-type` is handed to the
130/// native type its tag names (see `crate::tag::next_tag` for why the tag
131/// has to come first); any other map is a plain dictionary.
132struct AnyVisitor;
133
134const OUT_OF_RANGE: &str = "integer is outside Typst's signed 64-bit range";
135
136impl<'de> Visitor<'de> for AnyVisitor {
137    type Value = Any;
138
139    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
140        formatter.write_str("a Typwire value")
141    }
142
143    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Any, E> {
144        Ok(Any::Bool(value))
145    }
146
147    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Any, E> {
148        Ok(Any::Integer(value))
149    }
150
151    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Any, E> {
152        i64::try_from(value)
153            .map(Any::Integer)
154            .map_err(|_| E::custom(OUT_OF_RANGE))
155    }
156
157    fn visit_i128<E: de::Error>(self, value: i128) -> Result<Any, E> {
158        i64::try_from(value)
159            .map(Any::Integer)
160            .map_err(|_| E::custom(OUT_OF_RANGE))
161    }
162
163    fn visit_u128<E: de::Error>(self, value: u128) -> Result<Any, E> {
164        i64::try_from(value)
165            .map(Any::Integer)
166            .map_err(|_| E::custom(OUT_OF_RANGE))
167    }
168
169    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Any, E> {
170        Ok(Any::Float(value))
171    }
172
173    fn visit_str<E: de::Error>(self, value: &str) -> Result<Any, E> {
174        Ok(Any::String(value.to_owned()))
175    }
176
177    fn visit_string<E: de::Error>(self, value: String) -> Result<Any, E> {
178        Ok(Any::String(value))
179    }
180
181    fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Any, E> {
182        Ok(Any::Bytes(Bytes::new(value.to_vec())))
183    }
184
185    fn visit_byte_buf<E: de::Error>(self, value: Vec<u8>) -> Result<Any, E> {
186        Ok(Any::Bytes(Bytes::new(value)))
187    }
188
189    // CBOR's `null` arrives as `visit_none`, `format/value.rs`'s (JSON's)
190    // as `visit_unit`.
191    fn visit_none<E: de::Error>(self) -> Result<Any, E> {
192        Ok(Any::None)
193    }
194
195    fn visit_unit<E: de::Error>(self) -> Result<Any, E> {
196        Ok(Any::None)
197    }
198
199    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Any, D::Error> {
200        Any::deserialize(deserializer)
201    }
202
203    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Any, A::Error> {
204        // Capped, since the hint comes straight from the (untrusted) input.
205        let mut values = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(4096));
206        while let Some(value) = seq.next_element()? {
207            values.push(value);
208        }
209        Ok(Any::Array(values))
210    }
211
212    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Any, A::Error> {
213        let Some(first) = map.next_key_seed(StrSeed)? else {
214            return Ok(Any::Dictionary(BTreeMap::new()));
215        };
216
217        if first == TAG_KEY {
218            let tag = map.next_value_seed(StrSeed)?;
219            return native(&tag, map);
220        }
221
222        let mut entries = BTreeMap::new();
223        entries.insert(first.into_owned(), map.next_value()?);
224        while let Some((key, value)) = map.next_entry()? {
225            entries.insert(key, value);
226        }
227        Ok(Any::Dictionary(entries))
228    }
229}
230
231/// Decode the rest of a tagged map (its tag already read) as the native type
232/// `tag` names.
233fn native<'de, A: MapAccess<'de>>(tag: &str, map: A) -> Result<Any, A::Error> {
234    fn read<'de, T: Deserialize<'de>, A: MapAccess<'de>>(tag: &str, map: A) -> Result<T, A::Error> {
235        T::deserialize(MapAccessDeserializer::new(WithTag::new(tag, map)))
236    }
237
238    match tag {
239        "angle" => read(tag, map).map(Any::Angle),
240        "length" => read(tag, map).map(Any::Length),
241        "ratio" => read(tag, map).map(Any::Ratio),
242        "color-luma" | "color-oklab" | "color-oklch" | "color-linear-rgb" | "color-rgb"
243        | "color-cmyk" | "color-hsl" | "color-hsv" => read(tag, map).map(Any::Color),
244        "gradient-linear" | "gradient-radial" | "gradient-conic" => {
245            read(tag, map).map(Any::Gradient)
246        }
247        "auto" => read::<Auto, _>(tag, map).map(|_| Any::Auto),
248        "datetime" => read(tag, map).map(Any::DateTime),
249        "duration" => read(tag, map).map(Any::Duration),
250        "version" => read(tag, map).map(Any::Version),
251        "type" => read(tag, map).map(Any::Type),
252        "path" => read(tag, map).map(Any::Path),
253        "symbol" => read(tag, map).map(Any::Symbol),
254        "arguments" => read(tag, map).map(Any::Arguments),
255        "label" => read(tag, map).map(Any::Label),
256        "alignment" => read(tag, map).map(Any::Alignment),
257        "stroke" => read(tag, map).map(Any::Stroke),
258        #[cfg(feature = "regex")]
259        "regex" => read(tag, map).map(Any::Regex),
260        #[cfg(feature = "decimal")]
261        "decimal" => read(tag, map).map(Any::Decimal),
262        other => Err(de::Error::custom(format_args!(
263            "unknown typwire-type tag `{other}`"
264        ))),
265    }
266}
267
268/// A string, borrowed from the input when the decoder can (CBOR from a
269/// slice always can) -- so comparing a map key against `typwire-type`, or
270/// reading a tag, allocates nothing.
271struct StrSeed;
272
273impl<'de> DeserializeSeed<'de> for StrSeed {
274    type Value = Cow<'de, str>;
275
276    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
277        deserializer.deserialize_str(self)
278    }
279}
280
281impl<'de> Visitor<'de> for StrSeed {
282    type Value = Cow<'de, str>;
283
284    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
285        formatter.write_str("a string")
286    }
287
288    fn visit_borrowed_str<E: de::Error>(self, value: &'de str) -> Result<Self::Value, E> {
289        Ok(Cow::Borrowed(value))
290    }
291
292    fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
293        Ok(Cow::Owned(value.to_owned()))
294    }
295
296    fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
297        Ok(Cow::Owned(value))
298    }
299}
300
301impl From<bool> for Any {
302    fn from(value: bool) -> Self {
303        Self::Bool(value)
304    }
305}
306
307impl From<i64> for Any {
308    fn from(value: i64) -> Self {
309        Self::Integer(value)
310    }
311}
312
313impl From<f64> for Any {
314    fn from(value: f64) -> Self {
315        Self::Float(value)
316    }
317}
318
319impl From<String> for Any {
320    fn from(value: String) -> Self {
321        Self::String(value)
322    }
323}
324
325impl From<&str> for Any {
326    fn from(value: &str) -> Self {
327        Self::String(value.to_owned())
328    }
329}
330
331impl From<Bytes> for Any {
332    fn from(value: Bytes) -> Self {
333        Self::Bytes(value)
334    }
335}
336
337impl From<Vec<Any>> for Any {
338    fn from(value: Vec<Any>) -> Self {
339        Self::Array(value)
340    }
341}
342
343impl From<BTreeMap<String, Any>> for Any {
344    fn from(value: BTreeMap<String, Any>) -> Self {
345        Self::Dictionary(value)
346    }
347}
348
349impl From<Auto> for Any {
350    fn from(_: Auto) -> Self {
351        Self::Auto
352    }
353}
354
355macro_rules! native_conversions {
356    ($(($ty:ty, $variant:ident)),+ $(,)?) => {
357        $(
358            impl From<$ty> for Any {
359                fn from(value: $ty) -> Self {
360                    Self::$variant(value)
361                }
362            }
363        )+
364    };
365}
366
367native_conversions!(
368    (Angle, Angle),
369    (Length, Length),
370    (Ratio, Ratio),
371    (Color, Color),
372    (Gradient, Gradient),
373    (DateTime, DateTime),
374    (Duration, Duration),
375    (Version, Version),
376    (Type, Type),
377    (Path, Path),
378    (Symbol, Symbol),
379    (Arguments, Arguments),
380    (Label, Label),
381    (Alignment, Alignment),
382    (Stroke, Stroke),
383);
384
385#[cfg(feature = "regex")]
386impl From<Regex> for Any {
387    fn from(value: Regex) -> Self {
388        Self::Regex(value)
389    }
390}
391
392#[cfg(feature = "decimal")]
393impl From<Decimal> for Any {
394    fn from(value: Decimal) -> Self {
395        Self::Decimal(value)
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use crate::{decode, encode};
402
403    use super::*;
404
405    #[test]
406    fn tagged_values_are_native_before_dictionary() {
407        let bytes = encode(&Length::new(12.0)).unwrap();
408        let value: Any = decode(&bytes).unwrap();
409        assert!(matches!(value, Any::Length(length) if length.pt() == 12.0));
410    }
411
412    #[test]
413    fn only_a_leading_tag_makes_a_native_value() {
414        // `encode` writes a `BTreeMap`'s keys sorted, so `"a"` lands before
415        // the tag -- an ordinary dictionary that happens to contain one.
416        let value = BTreeMap::from([
417            ("a".to_owned(), Any::from(1_i64)),
418            ("typwire-type".to_owned(), Any::from("length")),
419            ("points".to_owned(), Any::from(1.0)),
420        ]);
421        let bytes = encode(&Any::Dictionary(value)).unwrap();
422        assert!(matches!(decode::<Any>(&bytes).unwrap(), Any::Dictionary(_)));
423    }
424
425    #[test]
426    fn narrow_width_float_inside_a_nested_native_type_round_trips() {
427        // `Any` decodes through `deserialize_any`, which `LenientDeserializer`
428        // has to wrap like every other recursion point for the typed `f64`
429        // inside the `Length` it dispatches to to accept Typst's F16 `0.0`.
430        let bytes: &[u8] = &[
431            0x81, // array(1)
432            0xA2, // map(2)
433            0x6C, b't', b'y', b'p', b'w', b'i', b'r', b'e', b'-', b't', b'y', b'p', b'e', 0x66,
434            b'l', b'e', b'n', b'g', b't', b'h', // "length"
435            0x66, b'p', b'o', b'i', b'n', b't', b's', // "points"
436            0xF9, 0x00, 0x00, // float16(0.0)
437        ];
438        let value: Any = decode(bytes).unwrap();
439        assert!(
440            matches!(&value, Any::Array(items) if matches!(&items[..], [Any::Length(length)] if length.pt() == 0.0))
441        );
442    }
443
444    #[test]
445    fn unknown_typwire_tag_is_rejected() {
446        let value = BTreeMap::from([
447            ("typwire-type".to_owned(), Any::from("future")),
448            ("value".to_owned(), Any::from(1_i64)),
449        ]);
450        let bytes = encode(&Any::Dictionary(value)).unwrap();
451        assert!(
452            decode::<Any>(&bytes)
453                .unwrap_err()
454                .to_string()
455                .contains("unknown typwire-type tag")
456        );
457    }
458}