Skip to main content

irox_bits/
stdwrappers.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5use crate::{Error, Seek, SeekFrom};
6use core::ops::{Deref, DerefMut};
7
8///
9/// Wraps a borrowed value and provides implementations of [`Bits`] and [`MutBits`] where applicable.
10pub enum BitsWrapper<'a, T> {
11    Owned(T),
12    Borrowed(&'a mut T),
13}
14impl<B> Deref for BitsWrapper<'_, B> {
15    type Target = B;
16
17    fn deref(&self) -> &Self::Target {
18        match self {
19            BitsWrapper::Borrowed(v) => v,
20            BitsWrapper::Owned(v) => v,
21        }
22    }
23}
24impl<B> DerefMut for BitsWrapper<'_, B> {
25    fn deref_mut(&mut self) -> &mut Self::Target {
26        match self {
27            BitsWrapper::Borrowed(v) => v,
28            BitsWrapper::Owned(v) => v,
29        }
30    }
31}
32impl<B: Seek> Seek for BitsWrapper<'_, B> {
33    fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
34        match self {
35            BitsWrapper::Borrowed(v) => v.seek(pos),
36            BitsWrapper::Owned(v) => v.seek(pos),
37        }
38    }
39
40    fn position(&mut self) -> Result<u64, Error> {
41        match self {
42            BitsWrapper::Borrowed(v) => v.position(),
43            BitsWrapper::Owned(v) => v.position(),
44        }
45    }
46}
47#[cfg(feature = "std")]
48mod stds {
49    use crate::{Bits, BitsWrapper, Error, MutBits};
50
51    impl<T> Bits for BitsWrapper<'_, T>
52    where
53        T: std::io::Read,
54    {
55        fn next_u8(&mut self) -> Result<Option<u8>, Error> {
56            let mut byte: u8 = 0;
57            let read = self.read(core::slice::from_mut(&mut byte))?;
58            if read < 1 {
59                return Ok(None);
60            }
61            Ok(Some(byte))
62        }
63
64        fn read_some_into<R: MutBits>(&mut self, buf: &mut R) -> Result<usize, Error> {
65            let mut b = [0u8; 4096];
66            let read = self.read(&mut b)?;
67            buf.write_all_bytes(b.get(0..read).unwrap_or_default())?;
68            Ok(read)
69        }
70    }
71
72    impl<T> MutBits for BitsWrapper<'_, T>
73    where
74        T: std::io::Write,
75    {
76        fn write_u8(&mut self, val: u8) -> Result<(), Error> {
77            Ok(self.write_all(&[val])?)
78        }
79
80        fn write_all_bytes(&mut self, val: &[u8]) -> Result<(), Error> {
81            Ok(self.write_all(val)?)
82        }
83    }
84
85    impl<T> std::io::Read for BitsWrapper<'_, T>
86    where
87        T: Bits,
88    {
89        fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result<usize> {
90            Ok(match self {
91                BitsWrapper::Owned(o) => Bits::read_some_into(o, &mut buf)?,
92                BitsWrapper::Borrowed(b) => Bits::read_some_into(*b, &mut buf)?,
93            })
94        }
95    }
96}