rw_utils/
to_write.rs

1use std::io;
2use std::io::Write;
3
4///
5/// This trait can be used by all structs that can be serialized to a Write.
6///
7/// I would not recommend using this if you have control over the serialization and
8/// only want to use this for rust<->rust serialization. Serde is better for this purpose.
9/// This is useful for use cases where precise control of how the data is written is required.
10///
11/// Example: Image Encoding, Network Packet encoding,...
12///
13pub trait ToWrite {
14    fn copy_to_write(&self, writer:  &mut dyn Write) -> io::Result<()>;
15}
16
17///
18/// This trait is automatically implemented for all ToWrite impls to allow a
19/// struct to be copied into a Vec<u8>.
20/// This trait is sealed and cannot be implemented manually.
21///
22pub trait ToVec: private::Sealed {
23    fn copy_to_vec(&self) -> io::Result<Vec<u8>>;
24}
25
26
27
28impl <T> ToVec for T where T: ToWrite {
29    fn copy_to_vec(&self) -> io::Result<Vec<u8>> {
30        let mut data = Vec::with_capacity(1024);
31        self.copy_to_write(&mut data)?;
32        return Ok(data);
33    }
34}
35
36mod private {
37    use crate::to_write::ToWrite;
38
39    impl <T> Sealed for T where T: ToWrite {}
40    pub trait Sealed {
41
42    }
43}
44
45