irox_bits/
stdwrappers.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
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
// SPDX-License-Identifier: MIT
// Copyright 2024 IROX Contributors
//

use core::ops::{Deref, DerefMut};

///
/// Wraps a borrowed value and provides implementations of [`Bits`] and [`MutBits`] where applicable.
pub enum BitsWrapper<'a, T> {
    Owned(T),
    Borrowed(&'a mut T),
}
impl<'a, B> Deref for BitsWrapper<'a, B> {
    type Target = B;

    fn deref(&self) -> &Self::Target {
        match self {
            BitsWrapper::Borrowed(v) => v,
            BitsWrapper::Owned(v) => v,
        }
    }
}
impl<'a, B> DerefMut for BitsWrapper<'a, B> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            BitsWrapper::Borrowed(v) => v,
            BitsWrapper::Owned(v) => v,
        }
    }
}

#[cfg(feature = "std")]
mod stds {
    use crate::{Bits, BitsWrapper, Error, MutBits};

    impl<'a, T> Bits for BitsWrapper<'a, T>
    where
        T: std::io::Read,
    {
        fn next_u8(&mut self) -> Result<Option<u8>, Error> {
            let mut byte: u8 = 0;
            let read = self.read(core::slice::from_mut(&mut byte))?;
            if read < 1 {
                return Ok(None);
            }
            Ok(Some(byte))
        }
    }

    impl<'a, T> MutBits for BitsWrapper<'a, T>
    where
        T: std::io::Write,
    {
        fn write_u8(&mut self, val: u8) -> Result<(), Error> {
            Ok(self.write_all(&[val])?)
        }
    }
}