1use std::io;
2use std::io::Error;
3use std::io::Write;
4
5pub trait Encode: Sized {
20 fn encode<W: io::Write>(&self, w: W) -> Result<usize, io::Error>;
21
22 fn encode_to_vec(&self) -> Result<Vec<u8>, Error>
26 where Self: crate::sealed::Sealed {
27 let mut buf = Vec::new();
28 self.encode(&mut buf)?;
29 Ok(buf)
30 }
31}
32
33impl<T: Encode> Encode for &T {
34 fn encode<W: Write>(&self, w: W) -> Result<usize, Error> {
35 (*self).encode(w)
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use std::io::Error;
42 use std::io::Write;
43
44 use crate::codec::Encode;
45
46 struct Foo;
47
48 impl Encode for Foo {
49 fn encode<W: Write>(&self, _w: W) -> Result<usize, Error> {
50 Ok(3)
51 }
52 }
53
54 #[test]
55 fn test_encode_ref() {
56 let foo = Foo;
57 let n = Encode::encode(&foo, Vec::new()).unwrap();
58 assert_eq!(n, 3);
59
60 let n = Encode::encode(&&foo, Vec::new()).unwrap();
61 assert_eq!(n, 3);
62 }
63
64 #[test]
65 fn test_encode_to_vec() {
66 let buf = 258u32.encode_to_vec().unwrap();
67 assert_eq!(buf, vec![0, 0, 1, 2]);
68 }
69}