safebit 0.1.0

Safe and secure bit access into integer types
Documentation
//! `WordRead` implementations for common types in the standard library.

use crate::{
    util::{BigEndian, LittleEndian, NativeEndian},
    word::Word,
    word_read::WordRead,
};
use std::io::{self, Read};

impl<W, R> WordRead<W, io::Error, LittleEndian> for R
where
    W: Word,
    R: Read,
{
    fn read(&mut self) -> Result<W, io::Error>
    where
        W: Word,
    {
        let mut slice: W::ByteSlice = Default::default();
        self.read_exact(slice.as_mut())?;
        Ok(W::from_le_bytes(slice))
    }
}

impl<W, R> WordRead<W, io::Error, BigEndian> for R
where
    W: Word,
    R: Read,
{
    fn read(&mut self) -> Result<W, io::Error>
    where
        W: Word,
    {
        let mut slice: W::ByteSlice = Default::default();
        self.read_exact(slice.as_mut())?;
        Ok(W::from_be_bytes(slice))
    }
}

impl<W, R> WordRead<W, io::Error, NativeEndian> for R
where
    W: Word,
    R: Read,
{
    fn read(&mut self) -> Result<W, io::Error>
    where
        W: Word,
    {
        let mut slice: W::ByteSlice = Default::default();
        self.read_exact(slice.as_mut())?;
        Ok(W::from_ne_bytes(slice))
    }
}