canonical/
canon.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
7use crate::store::{Sink, Source};
8
9use alloc::vec::Vec;
10
11/// The possible errors when fetching/decoding values from a store
12#[derive(Debug, Clone)]
13pub enum CanonError {
14    /// The byte sequence is not a valid representation of the type decoded
15    InvalidEncoding,
16    /// The instance could not be found in storage
17    NotFound,
18}
19
20impl Canon for CanonError {
21    fn encode(&self, sink: &mut Sink) {
22        let byte = match self {
23            CanonError::InvalidEncoding => 0,
24            CanonError::NotFound => 1,
25        };
26        sink.copy_bytes(&[byte])
27    }
28
29    fn decode(source: &mut Source) -> Result<Self, CanonError> {
30        match u8::decode(source)? {
31            0 => Ok(CanonError::InvalidEncoding),
32            1 => Ok(CanonError::NotFound),
33            _ => Err(CanonError::InvalidEncoding),
34        }
35    }
36
37    fn encoded_len(&self) -> usize {
38        1
39    }
40}
41
42/// Helper trait to encode Canon types into byte vectors
43pub trait EncodeToVec {
44    /// Encode `Self` into a buffer
45    fn encode_to_vec(&self) -> Vec<u8>;
46}
47
48impl<T> EncodeToVec for T
49where
50    T: Canon,
51{
52    fn encode_to_vec(&self) -> Vec<u8> {
53        let len = self.encoded_len();
54        let mut vec = Vec::with_capacity(len);
55        vec.resize_with(len, || 0);
56        let mut sink = Sink::new(&mut vec);
57        self.encode(&mut sink);
58        vec
59    }
60}
61
62/// Trait to read/write values as bytes
63pub trait Canon: Sized + Clone {
64    /// Write the encoded value as bytes to a `Sink`
65    fn encode(&self, sink: &mut Sink);
66    /// Return the decoded value from bytes in a `Source`
67    fn decode(source: &mut Source) -> Result<Self, CanonError>;
68    /// Returns the number of bytes needed to encode this value
69    fn encoded_len(&self) -> usize;
70}