rw_utils/
from_read.rs

1use std::io;
2use std::io::{Cursor, Read};
3
4///
5/// This trait can be used by all structs that can be serialized to a Read.
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 read is required.
10///
11/// Example: Image Decoding, Network Packet decoding,...
12///
13pub trait FromRead {
14    fn copy_from_read(&mut self, reader: &mut dyn Read) -> io::Result<()>;
15}
16
17///
18/// Auto implemented trait to add constructors to all structs that provide a Default impl.
19/// This trait is sealed and cannot be implemented manually.
20///
21pub trait DefaultFromRead : Sized + private::Sealed {
22    fn from_io(read: &mut dyn Read) -> io::Result<Self>;
23
24    fn from_vec(vec: &Vec<u8>) -> io::Result<Self>;
25
26    fn from_slice(slice: &[u8]) -> io::Result<Self>;
27}
28
29impl <T> DefaultFromRead for T where T: FromRead + Default {
30    fn from_io(read: &mut dyn Read) -> io::Result<Self> {
31        let mut x = Self::default();
32        x.copy_from_read(read)?;
33        return Ok(x);
34    }
35    fn from_vec(vec: &Vec<u8>) -> io::Result<Self> {
36        let mut x:Cursor<&[u8]> = Cursor::new(vec.as_ref());
37        return Self::from_io(&mut x);
38    }
39    fn from_slice(slice: &[u8]) -> io::Result<Self> {
40        let mut x:Cursor<&[u8]> = Cursor::new(slice.as_ref());
41        return Self::from_io(&mut x);
42    }
43}
44
45mod private {
46    use crate::from_read::FromRead;
47
48    impl <T> Sealed for T where T: FromRead + Default {}
49    pub trait Sealed {
50
51    }
52}
53
54
55mod test {
56
57}