Skip to main content

typst_template/
value.rs

1//! Conversion from Rust data into Typst values.
2
3use std::borrow::Cow;
4use std::collections::{BTreeMap, HashMap};
5
6use typst::foundations::{Bytes, Datetime, Decimal, Dict, Str, Value};
7
8/// Converts a Rust value into a Typst [`Value`].
9///
10/// This is the leaf conversion used by [`ToDict`] and by the
11/// [`ToDict`](macro@crate::ToDict) derive. It is implemented for the common
12/// scalar, collection, and Typst value types; enable cargo features for
13/// `chrono`, `rust_decimal`, `serde_json`, and `uuid` to convert those too.
14///
15/// ```
16/// use typst_template::{ToValue, Value};
17///
18/// assert_eq!(42_i64.into_value(), Value::Int(42));
19/// assert_eq!(Some("hi").into_value(), Value::Str("hi".into()));
20/// assert_eq!(Option::<i64>::None.into_value(), Value::None);
21/// ```
22pub trait ToValue {
23    /// Consumes `self` and produces the Typst value.
24    fn into_value(self) -> Value;
25}
26
27/// Converts a Rust struct into a Typst [`Dict`].
28///
29/// Derive it with `#[derive(ToDict)]` (see the
30/// [`ToDict`](macro@crate::ToDict) macro), which also implements [`ToValue`] by
31/// wrapping the dict, so derived types can nest.
32///
33/// ```
34/// use typst_template::{ToDict, ToValue, Value};
35///
36/// #[derive(ToDict)]
37/// struct Point {
38///     x: i64,
39///     y: i64,
40/// }
41///
42/// let dict = Point { x: 1, y: 2 }.into_dict();
43/// assert_eq!(dict.get("x").unwrap(), &Value::Int(1));
44/// ```
45pub trait ToDict {
46    /// Consumes `self` and produces the Typst dictionary.
47    fn into_dict(self) -> Dict;
48}
49
50// ── Pass-through Typst types ────────────────────────────────────────────────
51
52impl ToValue for Value {
53    fn into_value(self) -> Value {
54        self
55    }
56}
57
58impl ToValue for Str {
59    fn into_value(self) -> Value {
60        Value::Str(self)
61    }
62}
63
64impl ToValue for Bytes {
65    fn into_value(self) -> Value {
66        Value::Bytes(self)
67    }
68}
69
70impl ToValue for Datetime {
71    fn into_value(self) -> Value {
72        Value::Datetime(self)
73    }
74}
75
76impl ToValue for Decimal {
77    fn into_value(self) -> Value {
78        Value::Decimal(self)
79    }
80}
81
82impl ToDict for Dict {
83    fn into_dict(self) -> Dict {
84        self
85    }
86}
87
88/// Inserts every entry of `source` into `target`. Used by the `flatten`
89/// attribute of the [`ToDict`](macro@crate::ToDict) derive.
90#[doc(hidden)]
91pub fn merge_dict(target: &mut Dict, source: Dict) {
92    for (key, value) in source {
93        target.insert(key, value);
94    }
95}
96
97impl ToValue for Dict {
98    fn into_value(self) -> Value {
99        Value::Dict(self)
100    }
101}
102
103// ── Scalars ─────────────────────────────────────────────────────────────────
104
105impl ToValue for () {
106    fn into_value(self) -> Value {
107        Value::None
108    }
109}
110
111impl ToValue for bool {
112    fn into_value(self) -> Value {
113        Value::Bool(self)
114    }
115}
116
117/// Integers map to Typst `int` (`i64`), falling back to `float` when they don't
118/// fit.
119macro_rules! impl_into_value_int {
120    ($($ty:ty),*) => {$(
121        impl ToValue for $ty {
122            fn into_value(self) -> Value {
123                match i64::try_from(self) {
124                    Ok(int) => Value::Int(int),
125                    Err(_) => Value::Float(self as f64),
126                }
127            }
128        }
129    )*};
130}
131
132impl_into_value_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, i128, u128);
133
134impl ToValue for f32 {
135    fn into_value(self) -> Value {
136        Value::Float(self.into())
137    }
138}
139
140impl ToValue for f64 {
141    fn into_value(self) -> Value {
142        Value::Float(self)
143    }
144}
145
146impl ToValue for String {
147    fn into_value(self) -> Value {
148        Value::Str(self.into())
149    }
150}
151
152impl ToValue for &str {
153    fn into_value(self) -> Value {
154        Value::Str(self.into())
155    }
156}
157
158impl ToValue for Cow<'_, str> {
159    fn into_value(self) -> Value {
160        Value::Str(self.into_owned().into())
161    }
162}
163
164impl ToValue for char {
165    fn into_value(self) -> Value {
166        Value::Str(self.to_string().into())
167    }
168}
169
170// ── Containers ──────────────────────────────────────────────────────────────
171
172impl<T: ToValue> ToValue for Option<T> {
173    fn into_value(self) -> Value {
174        match self {
175            Some(value) => value.into_value(),
176            None => Value::None,
177        }
178    }
179}
180
181impl<T: ToValue> ToValue for Vec<T> {
182    fn into_value(self) -> Value {
183        Value::Array(self.into_iter().map(ToValue::into_value).collect())
184    }
185}
186
187impl<T: ToValue, const N: usize> ToValue for [T; N] {
188    fn into_value(self) -> Value {
189        Value::Array(self.into_iter().map(ToValue::into_value).collect())
190    }
191}
192
193/// String-keyed maps map to a Typst dict.
194macro_rules! impl_into_dict_map {
195    ($ty:ident $(, $bound:ident)?) => {
196        impl<K: Into<Str>, V: ToValue $(, $bound)?> ToDict for $ty<K, V $(, $bound)?> {
197            fn into_dict(self) -> Dict {
198                let mut dict = Dict::new();
199                for (key, value) in self {
200                    dict.insert(key.into(), value.into_value());
201                }
202                dict
203            }
204        }
205
206        impl<K: Into<Str>, V: ToValue $(, $bound)?> ToValue for $ty<K, V $(, $bound)?> {
207            fn into_value(self) -> Value {
208                Value::Dict(self.into_dict())
209            }
210        }
211    };
212}
213
214impl_into_dict_map!(BTreeMap);
215impl_into_dict_map!(HashMap, S);