use std::io;
use std::io::Error;
use std::io::Write;
pub trait Encode: Sized {
fn encode<W: io::Write>(&self, w: W) -> Result<usize, io::Error>;
fn type_id(&self) -> Option<u32> {
None
}
fn encode_to_vec(&self) -> Result<Vec<u8>, Error>
where Self: crate::sealed::Sealed {
let mut buf = Vec::new();
self.encode(&mut buf)?;
Ok(buf)
}
}
impl<T: Encode> Encode for &T {
fn encode<W: Write>(&self, w: W) -> Result<usize, Error> {
(*self).encode(w)
}
fn type_id(&self) -> Option<u32> {
(*self).type_id()
}
}
#[cfg(test)]
mod tests {
use std::io::Error;
use std::io::Write;
use crate::codec::Encode;
struct Foo;
impl Encode for Foo {
fn encode<W: Write>(&self, _w: W) -> Result<usize, Error> {
Ok(3)
}
fn type_id(&self) -> Option<u32> {
Some(7)
}
}
#[test]
fn test_encode_ref() {
let foo = Foo;
let n = Encode::encode(&foo, Vec::new()).unwrap();
assert_eq!(n, 3);
let n = Encode::encode(&&foo, Vec::new()).unwrap();
assert_eq!(n, 3);
}
#[test]
fn test_encode_to_vec() {
let buf = 258u32.encode_to_vec().unwrap();
assert_eq!(buf, vec![0, 0, 1, 2]);
}
#[test]
fn test_type_id_default_none() {
assert_eq!(None, 1u32.type_id());
}
#[test]
fn test_type_id_ref() {
let foo = Foo;
let foo_ref = &foo;
assert_eq!(Some(7), foo.type_id());
assert_eq!(Some(7), foo_ref.type_id());
}
}