codeq/codec/
encode.rs

1use std::io;
2use std::io::Error;
3use std::io::Write;
4
5/// A trait that can be encoded into an [`io::Write`] stream.
6///
7/// Implementing this trait allows types to be encoded into an [`io::Write`] stream,
8/// which is useful for writing data to various destinations like files, buffers, and streams.
9///
10/// # Examples
11/// ```rust
12/// use codeq::Encode;
13///
14/// let data = "hello".to_string();
15/// let mut buf = Vec::new();
16/// data.encode(&mut buf).unwrap();
17/// assert_eq!(buf, b"\x00\x00\x00\x05hello");
18/// ```
19pub trait Encode: Sized {
20    fn encode<W: io::Write>(&self, w: W) -> Result<usize, io::Error>;
21
22    /// Encodes the value into a new `Vec<u8>`.
23    ///
24    /// This method is sealed and cannot be implemented outside of the crate.
25    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}