1use crate::store::{Sink, Source};
8
9use alloc::vec::Vec;
10
11#[derive(Debug, Clone)]
13pub enum CanonError {
14 InvalidEncoding,
16 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
42pub trait EncodeToVec {
44 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
62pub trait Canon: Sized + Clone {
64 fn encode(&self, sink: &mut Sink);
66 fn decode(source: &mut Source) -> Result<Self, CanonError>;
68 fn encoded_len(&self) -> usize;
70}