canonical/
implementations.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7#![allow(clippy::empty_loop)]
8use core::marker::PhantomData;
9use core::mem;
10use dusk_varint::VarInt;
11
12use crate::{Canon, CanonError, Sink, Source};
13
14impl Canon for u8 {
15    fn encode(&self, sink: &mut Sink) {
16        sink.copy_bytes(&self.to_be_bytes())
17    }
18
19    fn decode(source: &mut Source) -> Result<Self, CanonError> {
20        let mut bytes = [0u8; 1];
21        bytes.copy_from_slice(source.read_bytes(1));
22        Ok(u8::from_be_bytes(bytes))
23    }
24
25    fn encoded_len(&self) -> usize {
26        1
27    }
28}
29
30macro_rules! varint {
31    ($varint:ty) => {
32        impl Canon for $varint {
33            fn encode(&self, sink: &mut Sink) {
34                // Varint uses 7 bits per byte to encode a value.
35                // So, to encode for example a `u64`, we would need:
36                // 64 / 7 = 9.14 bytes
37                // ==> For `u64` we need a buffer of 10 bytes.
38                const BUFSIZE: usize = mem::size_of::<$varint>() * 8 / 7 + 1;
39                let mut buf = [0u8; BUFSIZE];
40                let len = self.encoded_len();
41                self.encode_var(&mut buf);
42                sink.copy_bytes(&buf[..len]);
43            }
44
45            fn decode(source: &mut Source) -> Result<Self, $crate::CanonError> {
46                const MSB: u8 = 0b1000_0000;
47                let varint_len = source.bytes[source.offset..]
48                    .iter()
49                    .take_while(|b| *b & MSB != 0)
50                    .count()
51                    + 1;
52                VarInt::decode_var(source.read_bytes(varint_len))
53                    .map_or(Err(CanonError::InvalidEncoding), |(number, _)| {
54                        Ok(number)
55                    })
56            }
57
58            fn encoded_len(&self) -> usize {
59                self.required_space()
60            }
61        }
62    };
63}
64
65varint!(u16);
66varint!(i16);
67
68varint!(u32);
69varint!(i32);
70
71varint!(u64);
72varint!(i64);
73
74impl Canon for u128 {
75    fn encode(&self, sink: &mut Sink) {
76        let high: u64 = (self >> 64) as u64;
77        let low: u64 = *self as u64;
78
79        high.encode(sink);
80        low.encode(sink);
81    }
82
83    fn decode(source: &mut Source) -> Result<Self, CanonError> {
84        let high = u64::decode(source)?;
85        let low = u64::decode(source)?;
86
87        Ok((low as u128) + ((high as u128) << 64))
88    }
89
90    fn encoded_len(&self) -> usize {
91        let high: u64 = (self >> 64) as u64;
92        let low: u64 = *self as u64;
93        high.encoded_len() + low.encoded_len()
94    }
95}
96
97#[inline]
98fn zigzag_encode(from: i128) -> u128 {
99    ((from << 1) ^ (from >> 127)) as u128
100}
101
102#[inline]
103fn zigzag_decode(from: u128) -> i128 {
104    ((from >> 1) ^ (-((from & 1) as i128)) as u128) as i128
105}
106
107impl Canon for i128 {
108    fn encode(&self, sink: &mut Sink) {
109        zigzag_encode(*self).encode(sink)
110    }
111
112    fn decode(source: &mut Source) -> Result<Self, CanonError> {
113        Ok(zigzag_decode(u128::decode(source)?))
114    }
115
116    fn encoded_len(&self) -> usize {
117        zigzag_encode(*self).encoded_len()
118    }
119}
120
121impl Canon for bool {
122    fn encode(&self, sink: &mut Sink) {
123        match self {
124            true => sink.copy_bytes(&[1]),
125            false => sink.copy_bytes(&[0]),
126        }
127    }
128
129    fn decode(source: &mut Source) -> Result<Self, CanonError> {
130        match source.read_bytes(1) {
131            [0] => Ok(false),
132            [1] => Ok(true),
133            _ => Err(CanonError::InvalidEncoding),
134        }
135    }
136
137    fn encoded_len(&self) -> usize {
138        1
139    }
140}
141
142impl<T> Canon for Option<T>
143where
144    T: Canon,
145{
146    fn encode(&self, sink: &mut Sink) {
147        match self {
148            None => sink.copy_bytes(&[0]),
149            Some(t) => {
150                sink.copy_bytes(&[1]);
151                t.encode(sink);
152            }
153        }
154    }
155
156    fn decode(source: &mut Source) -> Result<Self, CanonError> {
157        match source.read_bytes(1) {
158            [0] => Ok(None),
159            [1] => Ok(Some(T::decode(source)?)),
160            _ => Err(CanonError::InvalidEncoding),
161        }
162    }
163
164    fn encoded_len(&self) -> usize {
165        match self {
166            Some(t) => 1 + t.encoded_len(),
167            None => 1,
168        }
169    }
170}
171
172impl<T, E> Canon for Result<T, E>
173where
174    T: Canon,
175    E: Canon,
176{
177    fn encode(&self, sink: &mut Sink) {
178        match self {
179            Ok(t) => {
180                sink.copy_bytes(&[0]);
181                t.encode(sink)
182            }
183            Err(e) => {
184                sink.copy_bytes(&[1]);
185                e.encode(sink)
186            }
187        }
188    }
189
190    fn decode(source: &mut Source) -> Result<Self, CanonError> {
191        match source.read_bytes(1) {
192            [0] => Ok(Ok(T::decode(source)?)),
193            [1] => Ok(Err(E::decode(source)?)),
194            _ => Err(CanonError::InvalidEncoding),
195        }
196    }
197
198    fn encoded_len(&self) -> usize {
199        match self {
200            Ok(t) => 1 + t.encoded_len(),
201            Err(e) => 1 + e.encoded_len(),
202        }
203    }
204}
205
206impl Canon for () {
207    fn encode(&self, _: &mut Sink) {}
208
209    fn decode(_: &mut Source) -> Result<Self, CanonError> {
210        Ok(())
211    }
212
213    fn encoded_len(&self) -> usize {
214        0
215    }
216}
217
218impl Canon for ! {
219    fn encode(&self, _: &mut Sink) {}
220
221    fn decode(_: &mut Source) -> Result<Self, CanonError> {
222        loop {}
223    }
224
225    fn encoded_len(&self) -> usize {
226        loop {}
227    }
228}
229
230impl<T> Canon for PhantomData<T> {
231    fn encode(&self, _: &mut Sink) {}
232
233    fn decode(_: &mut Source) -> Result<Self, CanonError> {
234        Ok(PhantomData)
235    }
236
237    fn encoded_len(&self) -> usize {
238        0
239    }
240}
241
242macro_rules! tuple {
243    ( $($name:ident)+) => (
244        #[allow(non_snake_case)]
245        impl<$($name,)+> Canon for ($($name,)+) where $($name: Canon,)+ {
246            fn encode(&self, sink: &mut Sink) {
247                let ($(ref $name,)+) = *self;
248                $($name.encode(sink);)+
249            }
250
251            fn decode(source: &mut Source) -> Result<Self, CanonError> {
252                Ok(($($name::decode(source)?,)+))
253            }
254
255            fn encoded_len(&self) -> usize {
256                let ($(ref $name,)+) = *self;
257                0 $(+ $name.encoded_len())*
258            }
259
260        }
261    );
262}
263
264tuple! { A B }
265tuple! { A B C }
266tuple! { A B C D }
267tuple! { A B C D E }
268tuple! { A B C D E F }
269tuple! { A B C D E F G }
270tuple! { A B C D E F G H }
271tuple! { A B C D E F G H I }
272tuple! { A B C D E F G H I J }
273tuple! { A B C D E F G H I J K }
274tuple! { A B C D E F G H I J K L }
275tuple! { A B C D E F G H I J K L M }
276tuple! { A B C D E F G H I J K L M N }
277tuple! { A B C D E F G H I J K L M N O }
278tuple! { A B C D E F G H I J K L M N O P }
279
280impl<T, const N: usize> Canon for [T; N]
281where
282    T: Canon + Sized,
283{
284    fn encode(&self, sink: &mut Sink) {
285        self.iter().for_each(|item| item.encode(sink));
286    }
287
288    fn decode(source: &mut Source) -> Result<Self, CanonError> {
289        array_init::try_array_init(|_| T::decode(source))
290    }
291
292    fn encoded_len(&self) -> usize {
293        self.iter().fold(0, |len, item| len + item.encoded_len())
294    }
295}
296
297mod alloc_impls {
298    use super::*;
299
300    extern crate alloc;
301
302    use alloc::collections::{BTreeMap, BTreeSet};
303    use alloc::rc::Rc;
304    use alloc::string::String;
305    use alloc::sync::Arc;
306    use alloc::vec::Vec;
307
308    impl<T: Canon> Canon for Vec<T> {
309        fn encode(&self, sink: &mut Sink) {
310            let len = self.len() as u64;
311            len.encode(sink);
312            for t in self.iter() {
313                t.encode(sink);
314            }
315        }
316
317        fn decode(source: &mut Source) -> Result<Self, CanonError> {
318            let mut vec = Vec::new();
319            let len = u64::decode(source)?;
320            for _ in 0..len {
321                vec.push(T::decode(source)?);
322            }
323            Ok(vec)
324        }
325
326        fn encoded_len(&self) -> usize {
327            // length of length
328            let mut len = (self.len() as u64).encoded_len();
329            for t in self.iter() {
330                len += t.encoded_len()
331            }
332            len
333        }
334    }
335
336    impl<T: Ord + Canon> Canon for BTreeSet<T> {
337        fn encode(&self, sink: &mut Sink) {
338            let len = self.len() as u64;
339            len.encode(sink);
340            self.iter().for_each(|item| item.encode(sink));
341        }
342
343        fn decode(source: &mut Source) -> Result<Self, CanonError> {
344            let len = u64::decode(source)?;
345            let mut set = BTreeSet::new();
346            for _ in 0..len {
347                set.insert(T::decode(source)?);
348            }
349            Ok(set)
350        }
351
352        fn encoded_len(&self) -> usize {
353            let len = (self.len() as u64).encoded_len();
354            self.iter().fold(len, |len, item| len + item.encoded_len())
355        }
356    }
357
358    impl<K, V> Canon for BTreeMap<K, V>
359    where
360        K: Ord + Canon,
361        V: Canon,
362    {
363        fn encode(&self, sink: &mut Sink) {
364            let len = self.len() as u64;
365            len.encode(sink);
366            self.iter().for_each(|(k, v)| {
367                k.encode(sink);
368                v.encode(sink);
369            });
370        }
371
372        fn decode(source: &mut Source) -> Result<Self, CanonError> {
373            let len = u64::decode(source)?;
374            let mut map = BTreeMap::new();
375            for _ in 0..len {
376                let key = K::decode(source)?;
377                let value = V::decode(source)?;
378                map.insert(key, value);
379            }
380            Ok(map)
381        }
382
383        fn encoded_len(&self) -> usize {
384            let len = (self.len() as u64).encoded_len();
385            self.iter().fold(len, |len, (k, v)| {
386                len + k.encoded_len() + v.encoded_len()
387            })
388        }
389    }
390
391    impl Canon for String {
392        fn encode(&self, sink: &mut Sink) {
393            let bytes = self.as_bytes();
394            let len = bytes.len() as u64;
395            len.encode(sink);
396            sink.copy_bytes(bytes);
397        }
398
399        fn decode(source: &mut Source) -> Result<Self, CanonError> {
400            let len = u64::decode(source)?;
401            let vec: Vec<u8> = source.read_bytes(len as usize).into();
402            String::from_utf8(vec).map_err(|_| CanonError::InvalidEncoding)
403        }
404
405        fn encoded_len(&self) -> usize {
406            let len = self.len() as u64;
407            len.encoded_len() + self.as_bytes().len()
408        }
409    }
410
411    impl<T> Canon for Rc<T>
412    where
413        T: Canon,
414    {
415        fn encode(&self, sink: &mut Sink) {
416            (**self).encode(sink)
417        }
418
419        fn decode(source: &mut Source) -> Result<Self, CanonError> {
420            T::decode(source).map(Rc::new)
421        }
422
423        fn encoded_len(&self) -> usize {
424            (**self).encoded_len()
425        }
426    }
427
428    impl<T> Canon for Arc<T>
429    where
430        T: Canon,
431    {
432        fn encode(&self, sink: &mut Sink) {
433            (**self).encode(sink)
434        }
435
436        fn decode(source: &mut Source) -> Result<Self, CanonError> {
437            T::decode(source).map(Arc::new)
438        }
439
440        fn encoded_len(&self) -> usize {
441            (**self).encoded_len()
442        }
443    }
444}