mz_ore/
serde.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Serde utilities.
17
18/// Used to serialize fields of Maps whose key type is not a native string. Annotate the field with
19/// `#[serde(serialize_with = mz_ore::serde::map_key_to_string)]`.
20pub fn map_key_to_string<'a, I, K, V, S>(map: I, serializer: S) -> Result<S::Ok, S::Error>
21where
22    I: IntoIterator<Item = (&'a K, &'a V)>,
23    K: std::fmt::Display + 'a,
24    V: serde::Serialize + 'a,
25    S: serde::Serializer,
26{
27    use serde::ser::SerializeMap;
28
29    let mut s = serializer.serialize_map(None)?;
30    for (key, value) in map {
31        s.serialize_entry(&key.to_string(), value)?;
32    }
33    s.end()
34}
35
36/// Used to deserialize fields of [`std::collections::BTreeMap`] whose key type is not a native
37/// string. Annotate the field with
38/// `#[serde(deserialize_with = "mz_ore::serde::string_key_to_btree_map")]`.
39pub fn string_key_to_btree_map<'de, K, V, D>(
40    deserializer: D,
41) -> Result<std::collections::BTreeMap<K, V>, D::Error>
42where
43    K: std::str::FromStr + Ord + std::fmt::Debug,
44    K::Err: std::fmt::Display,
45    V: serde::Deserialize<'de>,
46    D: serde::Deserializer<'de>,
47{
48    struct BTreeMapVisitor<K, V> {
49        _phantom: std::marker::PhantomData<(K, V)>,
50    }
51
52    impl<'de, K, V> serde::de::Visitor<'de> for BTreeMapVisitor<K, V>
53    where
54        K: std::str::FromStr + Ord,
55        V: serde::Deserialize<'de>,
56        K::Err: std::fmt::Display,
57    {
58        type Value = std::collections::BTreeMap<K, V>;
59
60        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
61            write!(formatter, "a map with keys that implement FromStr")
62        }
63
64        fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
65        where
66            A: serde::de::MapAccess<'de>,
67        {
68            let mut map = std::collections::BTreeMap::new();
69
70            while let Some((key, value)) = access.next_entry::<String, V>()? {
71                let key = K::from_str(&key).map_err(serde::de::Error::custom)?;
72                map.insert(key, value);
73            }
74
75            Ok(map)
76        }
77    }
78
79    deserializer.deserialize_map(BTreeMapVisitor {
80        _phantom: Default::default(),
81    })
82}