data_stream/
bool.rs

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
use crate::{FromStream, ToStream};

use std::io::{Error, ErrorKind, Read, Result, Write};

impl<S> ToStream<S> for bool {
    fn to_stream<W: Write>(&self, stream: &mut W) -> Result<()> {
        let bytes = [*self as u8];
        stream.write_all(&bytes)?;
        Ok(())
    }
}

impl<S> FromStream<S> for bool {
    fn from_stream<R: Read>(stream: &mut R) -> Result<Self> {
        let mut bytes = [0; 1];

        stream.read_exact(&mut bytes)?;

        match bytes[0] {
            0 => Ok(false),
            1 => Ok(true),
            _ => Err(Error::new(
                ErrorKind::InvalidData,
                "Invalid byte representation",
            )),
        }
    }
}