Skip to main content

data_stream/
wrappers.rs

1use crate::{FromStream, ToStream, from_stream, to_stream};
2
3use std::io::{Read, Result as IOResult, Write};
4
5impl<S, T: ToStream<S> + ?Sized> ToStream<S> for Box<T> {
6    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
7        (**self).to_stream(stream)
8    }
9}
10
11impl<S, T: FromStream<S>> FromStream<S> for Box<T> {
12    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
13        Ok(Self::new(from_stream(stream)?))
14    }
15}
16
17impl<S: crate::collections::SizeSettings> FromStream<S> for Box<str> {
18    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
19        let s: String = from_stream::<S, String, R>(stream)?;
20        Ok(s.into())
21    }
22}
23
24impl<S: crate::collections::SizeSettings, T: FromStream<S>> FromStream<S> for Box<[T]> {
25    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
26        let v: Vec<T> = from_stream(stream)?;
27        Ok(v.into_boxed_slice())
28    }
29}
30
31impl<S, T: ToStream<S>> ToStream<S> for Option<T> {
32    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
33        match self {
34            None => to_stream::<S, _, _>(&false, stream),
35            Some(value) => {
36                to_stream::<S, _, _>(&true, stream)?;
37                value.to_stream(stream)
38            }
39        }
40    }
41}
42
43impl<S, T: FromStream<S>> FromStream<S> for Option<T> {
44    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
45        Ok(if from_stream::<S, bool, _>(stream)? {
46            Some(from_stream(stream)?)
47        } else {
48            None
49        })
50    }
51}
52
53impl<S, T: ToStream<S>, E: ToStream<S>> ToStream<S> for Result<T, E> {
54    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
55        match self {
56            Ok(value) => {
57                to_stream::<S, _, _>(&true, stream)?;
58                value.to_stream(stream)
59            }
60            Err(err) => {
61                to_stream::<S, _, _>(&false, stream)?;
62                err.to_stream(stream)
63            }
64        }
65    }
66}
67
68impl<S, T: FromStream<S>, E: FromStream<S>> FromStream<S> for Result<T, E> {
69    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
70        Ok(if from_stream::<S, bool, _>(stream)? {
71            Ok(from_stream(stream)?)
72        } else {
73            Err(from_stream(stream)?)
74        })
75    }
76}