Skip to main content

azalea_codec/
rust.rs

1use std::{
2    collections::{BTreeMap, HashMap},
3    hash::Hash,
4    mem::ManuallyDrop,
5};
6
7use crate::{
8    Codec, Defaultable, Incomplete, MapCodec, MapLike, NewOk, Ops,
9    error::{ReadError, ReadResult, WriteResult},
10    impl_codec_from, impl_defaultable, impl_mapcodec, impl_mapcodec_from,
11};
12
13impl<O: Ops> Codec<O> for String {
14    fn codec_read(ops: &O) -> ReadResult<Self> {
15        ops.get_string()
16    }
17    fn codec_write(&self) -> WriteResult<O> {
18        O::create_string(self)
19    }
20}
21
22impl<O: Ops> Codec<O> for bool {
23    fn codec_read(ops: &O) -> ReadResult<Self> {
24        ops.get_boolean()
25    }
26    fn codec_write(&self) -> WriteResult<O> {
27        O::create_boolean(*self)
28    }
29}
30impl_defaultable!(bool);
31
32impl<O: Ops> Codec<O> for () {
33    fn codec_read(ops: &O) -> ReadResult<Self> {
34        if let Ok(map) = ops.get_map()
35            && map.to_values().is_empty()
36        {
37            return Ok(());
38        }
39        Err(ReadError::custom("not an empty map"))
40    }
41    fn codec_write(&self) -> WriteResult<O> {
42        O::empty_map()
43    }
44}
45
46macro_rules! impl_numbers {
47    ($($n:ident),*) => {
48        $(
49            impl<O: Ops> Codec<O> for $n {
50                fn codec_read(ops: &O, ) -> ReadResult<Self> {
51                    ops.get_number()?.try_into().map_err(Into::into)
52                }
53                fn codec_write(&self, ) -> WriteResult<O> {
54                    O::create_number( (*self).try_into()?)
55                }
56            }
57            crate::impl_defaultable!($n);
58        )*
59    }
60}
61
62#[rustfmt::skip]
63impl_numbers!(
64    u8, u16, u32, u64,
65    i8, i16, i32, i64,
66    f32, f64
67);
68
69impl<O: Ops, T: Codec<O>> Codec<O> for Vec<T> {
70    fn codec_read(ops: &O) -> ReadResult<Self> {
71        ops.get_list().and_then(|l| {
72            l.into_iter()
73                .map(|i| T::codec_read(&i))
74                .collect::<ReadResult<Vec<T>>>()
75        })
76    }
77    fn codec_write(&self) -> WriteResult<O> {
78        O::create_list(
79            &self
80                .iter()
81                .map(|i| i.codec_write())
82                .collect::<WriteResult<Box<[O]>>>()?,
83        )
84    }
85}
86crate::impl_defaultable!(<T: Codec<O>> for Vec<T>, self, self.is_empty());
87
88fn array_codec_read<const N: usize, O: Ops, T: Codec<O> + Clone>(ops: &O) -> ReadResult<[T; N]> {
89    let read = Vec::<T>::codec_read(ops)?;
90    let len = read.len();
91    read.try_into().map_err(|_| {
92        ReadError::custom(format!(
93            "wrong array length, was required to be {N} but got {len}"
94        ))
95    })
96}
97impl<const N: usize, O: Ops, T: Codec<O> + Clone> Codec<O> for [T; N] {
98    default fn codec_read(ops: &O) -> ReadResult<Self> {
99        array_codec_read(ops)
100    }
101    default fn codec_write(&self) -> WriteResult<O> {
102        self.to_vec().codec_write()
103    }
104}
105impl<const N: usize, O: Ops> Codec<O> for [i32; N] {
106    fn codec_read(ops: &O) -> ReadResult<Self> {
107        array_codec_read(ops)
108    }
109    fn codec_write(&self) -> WriteResult<O> {
110        O::create_int_list(self)
111    }
112}
113impl<const N: usize, O: Ops> Codec<O> for [i64; N] {
114    fn codec_read(ops: &O) -> ReadResult<Self> {
115        array_codec_read(ops)
116    }
117    fn codec_write(&self) -> WriteResult<O> {
118        O::create_long_list(self)
119    }
120}
121
122impl<O: Ops, A: Codec<O>, B: Codec<O>> Codec<O> for (A, B) {
123    /// Read as a list.
124    fn codec_read(ops: &O) -> ReadResult<Self> {
125        let list = Vec::<O>::codec_read(ops)?;
126        if list.len() != 2 {
127            return Err(ReadError::custom(format!(
128                "wrong array length, was required to be 2 but got {}",
129                list.len()
130            )));
131        }
132        let mut iter = list.iter();
133        Ok((
134            A::codec_read(iter.next().unwrap())?,
135            B::codec_read(iter.next().unwrap())?,
136        ))
137    }
138    /// Written as a list.
139    fn codec_write(&self) -> WriteResult<O> {
140        let list = [self.0.codec_write()?, self.1.codec_write()?];
141        list.codec_write()
142    }
143}
144
145#[derive(Clone)]
146pub struct UnorderedMap<K, V>(Vec<(K, V)>);
147impl<K, V> UnorderedMap<K, V> {
148    pub fn insert(&mut self, k: K, v: V) {
149        self.0.push((k, v));
150    }
151    pub fn iter(&self) -> impl Iterator<Item = &(K, V)> {
152        self.0.iter()
153    }
154}
155impl<O: Ops, K: Codec<O>, V: Codec<O>> Codec<O> for UnorderedMap<K, V> {
156    type Incomplete = IncompleteUnorderedMap<K, V>;
157    fn codec_read(ops: &O) -> ReadResult<Self> {
158        let map = ops.get_map()?;
159        let mut items = Vec::new();
160        map.for_each(|k_ops, v_ops| {
161            items.push(K::codec_read(k_ops).and_then(|k| {
162                V::codec_read(v_ops)
163                    .map_err(|e| {
164                        if let Ok(key_string) = String::codec_read(k_ops) {
165                            // try to attach more metadata if possible, to help
166                            // with debugging :3
167                            e.while_reading_key(key_string)
168                        } else {
169                            e
170                        }
171                    })
172                    .map(|v| (k, v))
173            }));
174        });
175
176        Ok(Self(items.into_iter().collect::<ReadResult<_>>()?))
177    }
178    fn codec_write(&self) -> WriteResult<O> {
179        let mut map = Vec::new();
180        for (k, v) in &self.0 {
181            map.push((k.codec_write()?, v.codec_write()?));
182        }
183        O::create_map(&map)
184    }
185}
186impl<K, V> Default for UnorderedMap<K, V> {
187    fn default() -> Self {
188        Self(Default::default())
189    }
190}
191impl_mapcodec!(UnorderedMap<K, V>, IncompleteUnorderedMap<K, V>, K: V);
192
193impl<K, V> From<HashMap<K, V>> for UnorderedMap<K, V> {
194    fn from(m: HashMap<K, V>) -> Self {
195        UnorderedMap(m.into_iter().collect())
196    }
197}
198impl<K: Hash + Eq, V> From<UnorderedMap<K, V>> for HashMap<K, V> {
199    fn from(m: UnorderedMap<K, V>) -> Self {
200        m.0.into_iter().collect()
201    }
202}
203impl_codec_from!(<K: Eq + Hash + Clone, V: Clone> HashMap<K, V>, UnorderedMap<K, V>, struct IncompleteHashMap);
204impl_mapcodec_from!(<K: Eq + Hash + Clone, V: Clone> HashMap<K, V>, UnorderedMap<K, V>);
205
206//
207
208impl<K, V> From<BTreeMap<K, V>> for UnorderedMap<K, V> {
209    fn from(m: BTreeMap<K, V>) -> Self {
210        UnorderedMap(m.into_iter().collect())
211    }
212}
213impl<K: Ord, V> From<UnorderedMap<K, V>> for BTreeMap<K, V> {
214    fn from(m: UnorderedMap<K, V>) -> Self {
215        m.0.into_iter().collect()
216    }
217}
218impl_codec_from!(<K: Ord + Clone, V: Clone> BTreeMap<K, V>, UnorderedMap<K, V>, struct IncompleteBTreeMap);
219impl_mapcodec_from!(<K: Ord + Clone, V: Clone> BTreeMap<K, V>, UnorderedMap<K, V>);
220
221impl<O: Ops, T: Codec<O>> Codec<O> for Option<T> {
222    fn codec_read(ops: &O) -> ReadResult<Self> {
223        T::codec_read(ops).map(Some)
224    }
225    fn codec_write(&self) -> WriteResult<O> {
226        if let Some(v) = self {
227            v.codec_write()
228        } else {
229            O::empty()
230        }
231    }
232}
233impl<T: Codec<O>, O: Ops> Defaultable<O> for Option<T> {
234    fn is_default(&self) -> bool {
235        self.is_none()
236    }
237}
238
239impl<O: Ops, T: Codec<O>> Codec<O> for Box<T> {
240    type Incomplete = T::Incomplete;
241    fn codec_read(ops: &O) -> ReadResult<Self> {
242        T::codec_read(ops).map(Box::new)
243    }
244    fn codec_write(&self) -> WriteResult<O> {
245        (**self).codec_write()
246    }
247}
248impl<O: Ops, T: MapCodec<O>> MapCodec<O> for Box<T> {
249    fn codec_read_map_item(incomplete: &mut <Self as Codec<O>>::Incomplete, k: &O, v: &O) {
250        T::codec_read_map_item(incomplete, k, v)
251    }
252    fn codec_write_to_map(&self, map: &mut Vec<(O, O)>) -> WriteResult<()> {
253        (**self).codec_write_to_map(map)
254    }
255    fn get_and_reset_result(incomplete: &mut <Self as Codec<O>>::Incomplete) -> ReadResult<()> {
256        T::get_and_reset_result(incomplete)
257    }
258}
259impl<T: Incomplete> Incomplete for Box<T> {
260    type Complete = Box<T::Complete>;
261    fn new(name: &'static str) -> Self {
262        Box::new(T::new(name))
263    }
264    fn build(self) -> ReadResult<Self::Complete> {
265        (*self).build().map(Box::new)
266    }
267}
268impl<T: Codec<O> + Defaultable<O>, O: Ops> Defaultable<O> for Box<T> {
269    fn is_default(&self) -> bool {
270        (**self).is_default()
271    }
272}
273
274impl<O: Ops, T: Codec<O>> Codec<O> for ManuallyDrop<T> {
275    type Incomplete = T::Incomplete;
276    fn codec_read(ops: &O) -> ReadResult<Self> {
277        T::codec_read(ops).map(ManuallyDrop::new)
278    }
279    fn codec_write(&self) -> WriteResult<O> {
280        (**self).codec_write()
281    }
282}
283
284impl<T: Clone> MapLike<T> for Vec<(T, T)> {
285    fn for_each(&self, mut cb: impl FnMut(&T, &T)) {
286        self.iter().for_each(|(k, v)| cb(k, v));
287    }
288}