1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use crate::{from_stream, to_stream, FromStream, ToStream};

use std::io::{Read, Result as IOResult, Write};

impl<S, T: ToStream<S>> ToStream<S> for Box<T> {
    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
        (**self).to_stream(stream)
    }
}

impl<S, T: FromStream<S>> FromStream<S> for Box<T> {
    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
        Ok(Box::new(from_stream(stream)?))
    }
}

impl<S, T: ToStream<S>> ToStream<S> for Option<T> {
    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
        match self {
            None => to_stream::<S, _, _>(&false, stream),
            Some(value) => {
                to_stream::<S, _, _>(&true, stream)?;
                value.to_stream(stream)
            }
        }
    }
}

impl<S, T: FromStream<S>> FromStream<S> for Option<T> {
    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
        Ok(match from_stream::<S, bool, _>(stream)? {
            false => None,
            true => Some(from_stream(stream)?),
        })
    }
}

impl<S, T: ToStream<S>, E: ToStream<S>> ToStream<S> for Result<T, E> {
    fn to_stream<W: Write>(&self, stream: &mut W) -> IOResult<()> {
        match self {
            Err(err) => {
                to_stream::<S, _, _>(&false, stream)?;
                err.to_stream(stream)
            }
            Ok(value) => {
                to_stream::<S, _, _>(&true, stream)?;
                value.to_stream(stream)
            }
        }
    }
}

impl<S, T: FromStream<S>, E: FromStream<S>> FromStream<S> for Result<T, E> {
    fn from_stream<R: Read>(stream: &mut R) -> IOResult<Self> {
        Ok(match from_stream::<S, bool, _>(stream)? {
            false => Err(from_stream(stream)?),
            true => Ok(from_stream(stream)?),
        })
    }
}