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
//! [`Encode`] trait implementation

use core::{fmt::Debug};

use num_traits::FromPrimitive;

use crate::Error;

/// Encode trait implemented for binary encodable objects
pub trait Encode: Debug {
    /// Error type returned on parse error
    type Error: From<Error> + Debug;

    /// Calculate expected encoded length for an object
    fn encode_len(&self) -> Result<usize, Self::Error>;

    /// Encode method writes object data to the provided writer
    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error>;
}

/// Encode trait extensions
pub trait EncodeExt<'a>: Encode + Sized + 'a {
    /// Helper to encode iterables
    fn encode_iter(items: impl Iterator<Item=&'a Self>, buff: &mut [u8]) -> Result<usize, Self::Error> {
        let mut index = 0;
        for i in items {
            index += i.encode(&mut buff[index..])?;
        }
        Ok(index)
    }

    /// Helper to encode to a fixed size buffer
    fn encode_buff<const N: usize>(&self) -> Result<([u8; N], usize), Self::Error> {
        let mut b = [0u8; N];
        let n = self.encode(&mut b)?;
        Ok((b, n))
    }
}

impl <'a, T: Encode + 'a> EncodeExt<'a> for T { }

/// Blanket encode for references to encodable types
impl <T: Encode> Encode for &T {
    type Error = <T as Encode>::Error;

    fn encode_len(&self) -> Result<usize, Self::Error> {
        <T as Encode>::encode_len(self)
    }

    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        <T as Encode>::encode(self, buff)
    }
}

/// Blanket [`Encode`] impl for slices of encodable types
impl <T> Encode for &[T] 
where
    T: Encode,
    <T as Encode>::Error: From<Error> + Debug,
{
    type Error = <T as Encode>::Error;

    fn encode_len(&self) -> Result<usize, Self::Error> {
        let mut index = 0;
        for i in 0..self.len() {
            index += self[i].encode_len()?;
        }
        Ok(index)
    }

    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        if buff.len() < self.encode_len()? {
            return Err(Error::BufferOverrun.into());
        }

        let mut index = 0;        
        for i in 0..self.len() {
            index += self[i].encode(&mut buff[index..])?
        }

        Ok(index)
    }

}

/// Blanket [`Encode`] impl for arrays of encodable types
impl <T, const N: usize> Encode for [T; N] 
where
    T: Encode,
    <T as Encode>::Error: From<Error> + Debug,
{
    type Error = <T as Encode>::Error;

    fn encode_len(&self) -> Result<usize, Self::Error> {
        let mut index = 0;
        for i in 0..N {
            index += self[i].encode_len()?;
        }
        Ok(index)
    }

    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        if buff.len() < self.encode_len()? {
            return Err(Error::BufferOverrun.into());
        }

        let mut index = 0;        
        for i in 0..N {
            index += self[i].encode(&mut buff[index..])?
        }

        Ok(index)
    }
}

/// [`Encode`] implementation for [`str`]
impl Encode for &str {
    type Error = Error;

    fn encode_len(&self) -> Result<usize, Self::Error> {
        Ok(self.as_bytes().len())
    }

    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        let d = self.as_bytes();
        if buff.len() < d.encode_len()? {
            return Err(Error::BufferOverrun.into());
        }

        buff[..d.len()].copy_from_slice(d);

        Ok(d.len())
    }
}


#[cfg(feature = "alloc")]
impl <T> Encode for alloc::vec::Vec<T> 
where
    T: Encode,
    <T as Encode>::Error: From<Error> + Debug,
{
    type Error = <T as Encode>::Error;

    #[inline]
    fn encode_len(&self) -> Result<usize, Self::Error> {
        let b: &[T] = self.as_ref();
        b.encode_len()
    }

    #[inline]
    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        let b: &[T] = self.as_ref();
        b.encode(buff)
    }
}


/// Encode for fields with prefixed lengths
pub trait EncodePrefixed<P: Encode> {
    /// Error type returned on parse error
    type Error: From<Error> + Debug;

    /// Parse method consumes a slice and returns an object
    fn encode_prefixed(&self, buff: &mut [u8]) -> Result<usize, Self::Error>;
}

impl <'a, T, P> EncodePrefixed<P> for T 
where
    T: Encode,
    P: Encode<Error=Error> + FromPrimitive,
    <T as Encode>::Error: From<Error>,
{
    type Error = <T as Encode>::Error;

    fn encode_prefixed(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
        let mut index = 0;

        // Compute encoded length and write prefix
        let len = P::from_usize(self.encode_len()?).unwrap();
        index += len.encode(buff)?;

        // Encode object
        index += self.encode(&mut buff[index..])?;

        Ok(index)
    }
}