1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

#![allow(clippy::empty_loop)]
use core::marker::PhantomData;
use core::mem;
use dusk_varint::VarInt;

use crate::{Canon, CanonError, Sink, Source};

impl Canon for u8 {
    fn encode(&self, sink: &mut Sink) {
        sink.copy_bytes(&self.to_be_bytes())
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        let mut bytes = [0u8; 1];
        bytes.copy_from_slice(source.read_bytes(1));
        Ok(u8::from_be_bytes(bytes))
    }

    fn encoded_len(&self) -> usize {
        1
    }
}

macro_rules! varint {
    ($varint:ty) => {
        impl Canon for $varint {
            fn encode(&self, sink: &mut Sink) {
                // Varint uses 7 bits per byte to encode a value.
                // So, to encode for example a `u64`, we would need:
                // 64 / 7 = 9.14 bytes
                // ==> For `u64` we need a buffer of 10 bytes.
                const BUFSIZE: usize = mem::size_of::<$varint>() * 8 / 7 + 1;
                let mut buf = [0u8; BUFSIZE];
                let len = self.encoded_len();
                self.encode_var(&mut buf);
                sink.copy_bytes(&buf[..len]);
            }

            fn decode(source: &mut Source) -> Result<Self, $crate::CanonError> {
                const MSB: u8 = 0b1000_0000;
                let varint_len = source.bytes[source.offset..]
                    .iter()
                    .take_while(|b| *b & MSB != 0)
                    .count()
                    + 1;
                VarInt::decode_var(source.read_bytes(varint_len))
                    .map_or(Err(CanonError::InvalidEncoding), |(number, _)| {
                        Ok(number)
                    })
            }

            fn encoded_len(&self) -> usize {
                self.required_space()
            }
        }
    };
}

varint!(u16);
varint!(i16);

varint!(u32);
varint!(i32);

varint!(u64);
varint!(i64);

impl Canon for u128 {
    fn encode(&self, sink: &mut Sink) {
        let high: u64 = (self >> 64) as u64;
        let low: u64 = *self as u64;

        high.encode(sink);
        low.encode(sink);
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        let high = u64::decode(source)?;
        let low = u64::decode(source)?;

        Ok((low as u128) + ((high as u128) << 64))
    }

    fn encoded_len(&self) -> usize {
        let high: u64 = (self >> 64) as u64;
        let low: u64 = *self as u64;
        high.encoded_len() + low.encoded_len()
    }
}

#[inline]
fn zigzag_encode(from: i128) -> u128 {
    ((from << 1) ^ (from >> 127)) as u128
}

#[inline]
fn zigzag_decode(from: u128) -> i128 {
    ((from >> 1) ^ (-((from & 1) as i128)) as u128) as i128
}

impl Canon for i128 {
    fn encode(&self, sink: &mut Sink) {
        zigzag_encode(*self).encode(sink)
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        Ok(zigzag_decode(u128::decode(source)?))
    }

    fn encoded_len(&self) -> usize {
        zigzag_encode(*self).encoded_len()
    }
}

impl Canon for bool {
    fn encode(&self, sink: &mut Sink) {
        match self {
            true => sink.copy_bytes(&[1]),
            false => sink.copy_bytes(&[0]),
        }
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        match source.read_bytes(1) {
            [0] => Ok(false),
            [1] => Ok(true),
            _ => Err(CanonError::InvalidEncoding),
        }
    }

    fn encoded_len(&self) -> usize {
        1
    }
}

impl<T> Canon for Option<T>
where
    T: Canon,
{
    fn encode(&self, sink: &mut Sink) {
        match self {
            None => sink.copy_bytes(&[0]),
            Some(t) => {
                sink.copy_bytes(&[1]);
                t.encode(sink);
            }
        }
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        match source.read_bytes(1) {
            [0] => Ok(None),
            [1] => Ok(Some(T::decode(source)?)),
            _ => Err(CanonError::InvalidEncoding),
        }
    }

    fn encoded_len(&self) -> usize {
        match self {
            Some(t) => 1 + t.encoded_len(),
            None => 1,
        }
    }
}

impl<T, E> Canon for Result<T, E>
where
    T: Canon,
    E: Canon,
{
    fn encode(&self, sink: &mut Sink) {
        match self {
            Ok(t) => {
                sink.copy_bytes(&[0]);
                t.encode(sink)
            }
            Err(e) => {
                sink.copy_bytes(&[1]);
                e.encode(sink)
            }
        }
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        match source.read_bytes(1) {
            [0] => Ok(Ok(T::decode(source)?)),
            [1] => Ok(Err(E::decode(source)?)),
            _ => Err(CanonError::InvalidEncoding),
        }
    }

    fn encoded_len(&self) -> usize {
        match self {
            Ok(t) => 1 + t.encoded_len(),
            Err(e) => 1 + e.encoded_len(),
        }
    }
}

impl Canon for () {
    fn encode(&self, _: &mut Sink) {}

    fn decode(_: &mut Source) -> Result<Self, CanonError> {
        Ok(())
    }

    fn encoded_len(&self) -> usize {
        0
    }
}

impl Canon for ! {
    fn encode(&self, _: &mut Sink) {}

    fn decode(_: &mut Source) -> Result<Self, CanonError> {
        loop {}
    }

    fn encoded_len(&self) -> usize {
        loop {}
    }
}

impl<T> Canon for PhantomData<T> {
    fn encode(&self, _: &mut Sink) {}

    fn decode(_: &mut Source) -> Result<Self, CanonError> {
        Ok(PhantomData)
    }

    fn encoded_len(&self) -> usize {
        0
    }
}

macro_rules! tuple {
    ( $($name:ident)+) => (
        #[allow(non_snake_case)]
        impl<$($name,)+> Canon for ($($name,)+) where $($name: Canon,)+ {
            fn encode(&self, sink: &mut Sink) {
                let ($(ref $name,)+) = *self;
                $($name.encode(sink);)+
            }

            fn decode(source: &mut Source) -> Result<Self, CanonError> {
                Ok(($($name::decode(source)?,)+))
            }

            fn encoded_len(&self) -> usize {
                let ($(ref $name,)+) = *self;
                0 $(+ $name.encoded_len())*
            }

        }
    );
}

tuple! { A B }
tuple! { A B C }
tuple! { A B C D }
tuple! { A B C D E }
tuple! { A B C D E F }
tuple! { A B C D E F G }
tuple! { A B C D E F G H }
tuple! { A B C D E F G H I }
tuple! { A B C D E F G H I J }
tuple! { A B C D E F G H I J K }
tuple! { A B C D E F G H I J K L }
tuple! { A B C D E F G H I J K L M }
tuple! { A B C D E F G H I J K L M N }
tuple! { A B C D E F G H I J K L M N O }
tuple! { A B C D E F G H I J K L M N O P }

impl<T, const N: usize> Canon for [T; N]
where
    T: Canon + Sized,
{
    fn encode(&self, sink: &mut Sink) {
        self.iter().for_each(|item| item.encode(sink));
    }

    fn decode(source: &mut Source) -> Result<Self, CanonError> {
        array_init::try_array_init(|_| T::decode(source))
    }

    fn encoded_len(&self) -> usize {
        self.iter().fold(0, |len, item| len + item.encoded_len())
    }
}

mod alloc_impls {
    use super::*;

    extern crate alloc;

    use alloc::rc::Rc;
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec::Vec;

    impl<T: Canon> Canon for Vec<T> {
        fn encode(&self, sink: &mut Sink) {
            let len = self.len() as u64;
            len.encode(sink);
            for t in self.iter() {
                t.encode(sink);
            }
        }

        fn decode(source: &mut Source) -> Result<Self, CanonError> {
            let mut vec = Vec::new();
            let len = u64::decode(source)?;
            for _ in 0..len {
                vec.push(T::decode(source)?);
            }
            Ok(vec)
        }

        fn encoded_len(&self) -> usize {
            // length of length
            let mut len = (self.len() as u64).encoded_len();
            for t in self.iter() {
                len += t.encoded_len()
            }
            len
        }
    }

    impl Canon for String {
        fn encode(&self, sink: &mut Sink) {
            let bytes = self.as_bytes();
            let len = bytes.len() as u64;
            len.encode(sink);
            sink.copy_bytes(bytes);
        }

        fn decode(source: &mut Source) -> Result<Self, CanonError> {
            let len = u64::decode(source)?;
            let vec: Vec<u8> = source.read_bytes(len as usize).into();
            String::from_utf8(vec).map_err(|_| CanonError::InvalidEncoding)
        }

        fn encoded_len(&self) -> usize {
            let len = self.len() as u64;
            len.encoded_len() + self.as_bytes().len()
        }
    }

    impl<T> Canon for Rc<T>
    where
        T: Canon,
    {
        fn encode(&self, sink: &mut Sink) {
            (**self).encode(sink)
        }

        fn decode(source: &mut Source) -> Result<Self, CanonError> {
            T::decode(source).map(Rc::new)
        }

        fn encoded_len(&self) -> usize {
            (**self).encoded_len()
        }
    }

    impl<T> Canon for Arc<T>
    where
        T: Canon,
    {
        fn encode(&self, sink: &mut Sink) {
            (**self).encode(sink)
        }

        fn decode(source: &mut Source) -> Result<Self, CanonError> {
            T::decode(source).map(Arc::new)
        }

        fn encoded_len(&self) -> usize {
            (**self).encoded_len()
        }
    }
}