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
use core::fmt::Debug;
use num_traits::FromPrimitive;
use crate::Error;
use super::Encode;
pub trait EncodePrefixed<P: Encode> {
type Error: From<Error> + Debug;
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;
let len = P::from_usize(self.encode_len()?).unwrap();
index += len.encode(buff)?;
index += self.encode(&mut buff[index..])?;
Ok(index)
}
}