Skip to main content

irox_bits/
bits.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5//!
6//! Basic Bit Buffer interface
7//!
8
9use crate::error::{Error, ErrorKind};
10use crate::mutbits::MutBits;
11use crate::BitsErrorKind;
12
13cfg_feature_alloc! {
14    extern crate alloc;
15    use alloc::string::{String, ToString as _};
16    use alloc::vec::Vec;
17    use alloc::vec;
18}
19
20macro_rules! maybe_next_u8 {
21    ($self:ident,$prev:expr) => {{
22        let Some(b) = $self.next_u8()? else {
23            return Ok(Some($prev));
24        };
25        b
26    }};
27}
28macro_rules! next_and_shift {
29    ($self:ident,$ty:ty,$prev:expr) => {{
30        let a = maybe_next_u8!($self, $prev);
31        $prev <<= 8;
32        $prev |= a as $ty;
33    }};
34}
35
36#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
37pub enum ByteOrder {
38    LittleEndian,
39    #[default]
40    BigEndian,
41}
42
43///
44/// Read methods for the primitive types
45///
46pub trait Bits {
47    /// Reads a single [`u8`]
48    fn read_u8(&mut self) -> Result<u8, Error> {
49        let Some(val) = self.next_u8()? else {
50            return Err(Error::from(ErrorKind::UnexpectedEof));
51        };
52        Ok(val)
53    }
54
55    /// Optionally returns a single [`u8`]
56    fn next_u8(&mut self) -> Result<Option<u8>, Error>;
57
58    /// Reads a single [`i8`]
59    fn read_i8(&mut self) -> Result<i8, Error> {
60        Ok(self.read_u8()? as i8)
61    }
62    /// Optionally returns a single [`i8`]
63    fn next_i8(&mut self) -> Result<Option<i8>, Error> {
64        Ok(self.next_u8()?.map(|v| v as i8))
65    }
66
67    /// Reads a single bool (u8), returning true if 1, false if 0, or InvalidInput if anything else.
68    fn read_bool(&mut self) -> Result<bool, Error> {
69        let Some(val) = self.next_bool()? else {
70            return Err(Error::from(ErrorKind::UnexpectedEof));
71        };
72        Ok(val)
73    }
74
75    /// Reads a single bool (u8), returning true if 1, false if 0, or InvalidInput if anything else.
76    fn next_bool(&mut self) -> Result<Option<bool>, Error> {
77        let val = self.next_u8()?;
78        let Some(val) = val else { return Ok(None) };
79        if val == 0 {
80            Ok(Some(false))
81        } else if val == 1 {
82            Ok(Some(true))
83        } else {
84            Err(ErrorKind::InvalidInput.into())
85        }
86    }
87
88    /// Reads 1, 2, 3, or 4 bytes to construct a UTF-8 charpoint.
89    fn read_be_utf8_char(&mut self) -> Result<char, Error> {
90        Ok(crate::utf::read_be_utf8_char(self)?.0)
91    }
92
93    /// Reads a single [`u16`] in big-endian order, 2 bytes, MSB first.
94    fn read_be_u16(&mut self) -> Result<u16, Error> {
95        let Some(ret) = self.next_be_u16()? else {
96            return Err(Error::from(ErrorKind::UnexpectedEof));
97        };
98        Ok(ret)
99    }
100
101    /// Reads a single [`u16`] in little-endian order, 2 bytes, LSB first.
102    fn read_le_u16(&mut self) -> Result<u16, Error> {
103        Ok(self.read_be_u16()?.swap_bytes())
104    }
105
106    /// Optionally reads a single [`u16`] in big-endian order, 2 bytes, MSB first.
107    fn next_be_u16(&mut self) -> Result<Option<u16>, Error> {
108        let Some(a) = self.next_u8()? else {
109            return Ok(None);
110        };
111        let Some(b) = self.next_u8()? else {
112            return Ok(Some(a as u16));
113        };
114        let out = ((a as u16) << 8) | (b as u16);
115        Ok(Some(out))
116    }
117
118    /// Optionally reads a single [`u16`] in little-endian order, 2 bytes, LSB first.
119    fn next_le_u16(&mut self) -> Result<Option<u16>, Error> {
120        Ok(self.next_be_u16()?.map(u16::swap_bytes))
121    }
122
123    /// Reads a single [`u32`] in big-endian order, 4 bytes, MSB first.
124    fn read_be_u32(&mut self) -> Result<u32, Error> {
125        let Some(ret) = self.next_be_u32()? else {
126            return Err(Error::from(ErrorKind::UnexpectedEof));
127        };
128        Ok(ret)
129    }
130
131    /// Reads a single [`u32`] in little-endian order, 4 bytes, LSB first.
132    fn read_le_u32(&mut self) -> Result<u32, Error> {
133        Ok(self.read_be_u32()?.swap_bytes())
134    }
135
136    /// Optionally reads a single [`u32`] in big-endian order, 4 bytes, MSB first.
137    fn next_be_u32(&mut self) -> Result<Option<u32>, Error> {
138        let Some(a) = self.next_u8()? else {
139            return Ok(None);
140        };
141        let mut out: u32 = ((a as u32) << 8) | maybe_next_u8!(self, a as u32) as u32;
142        next_and_shift!(self, u32, out);
143        next_and_shift!(self, u32, out);
144
145        Ok(Some(out))
146    }
147
148    /// Optionally reads a single [`u32`] in little-endian order, 4 bytes, LSB first.
149    fn next_le_u32(&mut self) -> Result<Option<u32>, Error> {
150        Ok(self.next_be_u32()?.map(u32::swap_bytes))
151    }
152
153    /// Reads a single [`u64`] in big-endian order, 8 bytes, MSB first.
154    fn read_be_u64(&mut self) -> Result<u64, Error> {
155        let Some(ret) = self.next_be_u64()? else {
156            return Err(Error::from(ErrorKind::UnexpectedEof));
157        };
158        Ok(ret)
159    }
160
161    /// Reads a single [`u64`] in big-endian order, 8 bytes, MSB first.
162    fn read_le_u64(&mut self) -> Result<u64, Error> {
163        let Some(ret) = self.next_be_u64()? else {
164            return Err(Error::from(ErrorKind::UnexpectedEof));
165        };
166        Ok(ret.swap_bytes())
167    }
168
169    /// Optionally reads a single [`u64`] in big-endian order, 8 bytes, MSB first.
170    fn next_be_u64(&mut self) -> Result<Option<u64>, Error> {
171        let Some(a) = self.next_u8()? else {
172            return Ok(None);
173        };
174        let mut out: u64 = ((a as u64) << 8) | maybe_next_u8!(self, a as u64) as u64;
175        next_and_shift!(self, u64, out);
176        next_and_shift!(self, u64, out);
177        next_and_shift!(self, u64, out);
178        next_and_shift!(self, u64, out);
179        next_and_shift!(self, u64, out);
180        next_and_shift!(self, u64, out);
181
182        Ok(Some(out))
183    }
184
185    /// Optionally reads a single [`u64`] in little-endian order, 4 bytes, LSB first.
186    fn next_le_u64(&mut self) -> Result<Option<u64>, Error> {
187        Ok(self.next_be_u64()?.map(u64::swap_bytes))
188    }
189
190    /// Reads a single [`u128`] in big-endian order, 16 bytes, MSB first.
191    fn read_be_u128(&mut self) -> Result<u128, Error> {
192        let Some(ret) = self.next_be_u128()? else {
193            return Err(Error::from(ErrorKind::UnexpectedEof));
194        };
195        Ok(ret)
196    }
197
198    /// Optionally reads a single [`u128`] in big-endian order, 16 bytes, MSB first.
199    fn next_be_u128(&mut self) -> Result<Option<u128>, Error> {
200        let Some(a) = self.next_u8()? else {
201            return Ok(None);
202        };
203        let mut out: u128 = ((a as u128) << 8) | maybe_next_u8!(self, a as u128) as u128;
204        next_and_shift!(self, u128, out);
205        next_and_shift!(self, u128, out);
206        next_and_shift!(self, u128, out);
207        next_and_shift!(self, u128, out);
208        next_and_shift!(self, u128, out);
209        next_and_shift!(self, u128, out);
210        next_and_shift!(self, u128, out);
211        next_and_shift!(self, u128, out);
212        next_and_shift!(self, u128, out);
213        next_and_shift!(self, u128, out);
214        next_and_shift!(self, u128, out);
215        next_and_shift!(self, u128, out);
216        next_and_shift!(self, u128, out);
217        next_and_shift!(self, u128, out);
218
219        Ok(Some(out))
220    }
221
222    /// Reads a single [`i128`] in big-endian order, 16 bytes, MSB first.
223    fn read_be_i128(&mut self) -> Result<i128, Error> {
224        Ok(self.read_be_u128()? as i128)
225    }
226    /// Optionally reads a single [`i128`] in big-endian order, 16 bytes, MSB first.
227    fn next_be_i128(&mut self) -> Result<Option<i128>, Error> {
228        let Some(val) = self.next_be_u128()? else {
229            return Ok(None);
230        };
231        Ok(Some(val as i128))
232    }
233
234    /// Reads a single [`f32`], 4 bytes.  Standard IEEE754 encoding
235    fn read_be_f32(&mut self) -> Result<f32, Error> {
236        Ok(f32::from_bits(self.read_be_u32()?))
237    }
238
239    /// Reads a single [`f32`], 4 bytes.  Reversed IEEE754 encoding
240    fn read_le_f32(&mut self) -> Result<f32, Error> {
241        Ok(f32::from_bits(self.read_le_u32()?))
242    }
243
244    /// Reads a single [`f32`], 4 bytes.  Specified byte ordering.
245    fn read_f32(&mut self, order: ByteOrder) -> Result<f32, Error> {
246        Ok(f32::from_bits(self.read_u32(order)?))
247    }
248
249    /// Optionally reads a single [`f32`], 4 bytes.  Standard IEEE754 encoding
250    fn next_be_f32(&mut self) -> Result<Option<f32>, Error> {
251        Ok(self.next_be_u32()?.map(f32::from_bits))
252    }
253
254    /// Optionally reads a single [`f32`], 4 bytes.  Reversed IEEE754 encoding
255    fn next_le_f32(&mut self) -> Result<Option<f32>, Error> {
256        Ok(self.next_le_u32()?.map(f32::from_bits))
257    }
258
259    /// Reads a single [`f64`], 8 bytes.  Standard IEEE754 encoding
260    fn read_be_f64(&mut self) -> Result<f64, Error> {
261        Ok(f64::from_bits(self.read_be_u64()?))
262    }
263
264    /// Reads a single [`f64`], 8 bytes.  Reversed IEEE754 encoding
265    fn read_le_f64(&mut self) -> Result<f64, Error> {
266        Ok(f64::from_bits(self.read_le_u64()?))
267    }
268
269    /// Optionally reads a single [`f64`], 8 bytes.  Standard IEEE754 encoding
270    fn next_be_f64(&mut self) -> Result<Option<f64>, Error> {
271        Ok(self.next_be_u64()?.map(f64::from_bits))
272    }
273
274    /// Optionally reads a single [`f64`], 8 bytes.  Reversed IEEE754 encoding
275    fn next_le_f64(&mut self) -> Result<Option<f64>, Error> {
276        Ok(self.next_le_u64()?.map(f64::from_bits))
277    }
278
279    /// Reads a single [`f64`], 8 bytes.  Specified byte ordering.
280    fn read_f64(&mut self, order: ByteOrder) -> Result<f64, Error> {
281        Ok(f64::from_bits(self.read_u64(order)?))
282    }
283
284    /// Reads a single [`i16`] in big-endian order, 2 bytes, MSB first.
285    fn read_be_i16(&mut self) -> Result<i16, Error> {
286        Ok(self.read_be_u16()? as i16)
287    }
288
289    /// Reads a single [`i16`] in little-endian order, 2 bytes, LSB first.
290    fn read_le_i16(&mut self) -> Result<i16, Error> {
291        Ok(self.read_be_u16()?.swap_bytes() as i16)
292    }
293
294    /// Optionally reads a single [`i16`] in big-endian order, 2 bytes, MSB first.
295    fn next_be_i16(&mut self) -> Result<Option<i16>, Error> {
296        Ok(self.next_be_u16()?.map(|v| v as i16))
297    }
298
299    /// Optionally reads a single [`i16`] in little-endian order, 2 bytes, LSB first.
300    fn next_le_i16(&mut self) -> Result<Option<i16>, Error> {
301        Ok(self.next_be_u16()?.map(|v| v.swap_bytes() as i16))
302    }
303
304    /// Reads a single [`i32`] in big-endian order, 4 bytes, MSB first.
305    fn read_be_i32(&mut self) -> Result<i32, Error> {
306        Ok(self.read_be_u32()? as i32)
307    }
308
309    /// Reads a single [`i32`] in little-endian order, 4 bytes, LSB first.
310    fn read_le_i32(&mut self) -> Result<i32, Error> {
311        Ok(self.read_be_u32()?.swap_bytes() as i32)
312    }
313
314    /// Optionally reads a single [`i32`] in big-endian order, 4 bytes, MSB first.
315    fn next_be_i32(&mut self) -> Result<Option<i32>, Error> {
316        Ok(self.next_be_u32()?.map(|v| v as i32))
317    }
318
319    /// Optionally reads a single [`i32`] in little-endian order, 4 bytes,LSB first.
320    fn next_le_i32(&mut self) -> Result<Option<i32>, Error> {
321        Ok(self.next_be_u32()?.map(|v| v.swap_bytes() as i32))
322    }
323
324    /// Reads a single [`i64`] in big-endian order, 8 bytes, MSB first.
325    fn read_be_i64(&mut self) -> Result<i64, Error> {
326        Ok(self.read_be_u64()? as i64)
327    }
328
329    /// Reads a single [`i64`] in little-endian order, 8 bytes, LSB first.
330    fn read_le_i64(&mut self) -> Result<i64, Error> {
331        Ok(self.read_be_u64()?.swap_bytes() as i64)
332    }
333
334    /// Optionally reads a single [`i64`] in big-endian order, 8 bytes, MSB first.
335    fn next_be_i64(&mut self) -> Result<Option<i64>, Error> {
336        Ok(self.next_be_u64()?.map(|v| v as i64))
337    }
338
339    /// Optionally reads a single [`i64`] in little-endian order, 8 bytes, LSB first.
340    fn next_le_i64(&mut self) -> Result<Option<i64>, Error> {
341        Ok(self.next_be_u64()?.map(|v| v.swap_bytes() as i64))
342    }
343
344    /// Reads a single [`i128`] in little-endian order, 8 bytes, LSB first.
345    fn read_le_i128(&mut self) -> Result<i128, Error> {
346        Ok(self.read_be_i128()?.swap_bytes())
347    }
348
349    /// Optionally reads a single [`i64`] in little-endian order, 8 bytes, LSB first.
350    fn next_le_i128(&mut self) -> Result<Option<i128>, Error> {
351        Ok(self.next_be_u128()?.map(|v| v.swap_bytes() as i128))
352    }
353
354    /// Reads a single [`u128`] in little-endian order, 8 bytes, LSB first.
355    fn read_le_u128(&mut self) -> Result<u128, Error> {
356        Ok(self.read_be_u128()?.swap_bytes())
357    }
358
359    /// Optionally reads a single [`i64`] in little-endian order, 8 bytes, LSB first.
360    fn next_le_u128(&mut self) -> Result<Option<u128>, Error> {
361        Ok(self.next_be_u128()?.map(u128::swap_bytes))
362    }
363
364    /// Advances the stream by at most 'len' bytes.  The actual amount of bytes advanced may be
365    /// less, and is returned in [`Ok(usize)`]
366    fn advance(&mut self, len: usize) -> Result<usize, Error> {
367        for _ in 0..len {
368            self.read_u8()?;
369        }
370        Ok(len)
371    }
372
373    fn read_u8_blob_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
374        let size = self.read_u8()? as usize;
375        self.read_exact_into(size, into)
376    }
377    fn read_u16_blob_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
378        let size = self.read_be_u16()? as usize;
379        self.read_exact_into(size, into)
380    }
381    fn read_u32_blob_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
382        let size = self.read_be_u32()? as usize;
383        self.read_exact_into(size, into)
384    }
385    fn read_u64_blob_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
386        let size = self.read_be_u64()? as usize;
387        self.read_exact_into(size, into)
388    }
389
390    /// reads from the stream until a null (0x0) is encountered into the provided output, does NOT include null.
391    fn read_str_nul_terminated_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
392        while let Some(ch) = self.next_u8()? {
393            if ch == 0 {
394                break;
395            }
396            into.write_u8(ch)?;
397        }
398        Ok(())
399    }
400
401    cfg_feature_alloc! {
402        /// Reads a sized blob, a series of bytes preceded by a [`u8`] declaring the size.
403        fn read_u8_blob(&mut self) -> Result<Vec<u8>, Error> {
404            let size = self.read_u8()?;
405            self.read_exact_vec(size as usize)
406        }
407
408        /// Reads a sized blob, a series of bytes preceded by a [`u16`] declaring the size.
409        fn read_be_u16_blob(&mut self) -> Result<Vec<u8>, Error> {
410            let size = self.read_be_u16()?;
411            self.read_exact_vec(size as usize)
412        }
413
414        /// Reads a sized blob, a series of bytes preceded by a [`u16`] declaring the size.
415        fn read_le_u16_blob(&mut self) -> Result<Vec<u8>, Error> {
416            let size = self.read_le_u16()?;
417            self.read_exact_vec(size as usize)
418        }
419        /// Reads a sized blob, a series of bytes preceded by a [`u32`] declaring the size.
420        fn read_be_u32_blob(&mut self) -> Result<Vec<u8>, Error> {
421            let size = self.read_be_u32()?;
422            self.read_exact_vec(size as usize)
423        }
424        /// Reads a sized blob, a series of bytes preceded by a [`u32`] declaring the size.
425        fn read_le_u32_blob(&mut self) -> Result<Vec<u8>, Error> {
426            let size = self.read_le_u32()?;
427            self.read_exact_vec(size as usize)
428        }
429
430        /// Reads a sized blob, a series of bytes preceded by a [`u64`] declaring the size.
431        fn read_be_u64_blob(&mut self) -> Result<Vec<u8>, Error> {
432            let size = self.read_be_u64()?;
433            self.read_exact_vec(size as usize)
434        }
435        /// Reads a sized blob, a series of bytes preceded by a [`u64`] declaring the size.
436        fn read_le_u64_blob(&mut self) -> Result<Vec<u8>, Error> {
437            let size = self.read_le_u64()?;
438            self.read_exact_vec(size as usize)
439        }
440
441        /// Reads the specified amount of bytes into a [`Vec<u8>`] and returns it
442        fn read_exact_vec(&mut self, size: usize) -> Result<alloc::vec::Vec<u8>, Error> {
443            let mut buf: alloc::vec::Vec<u8> = alloc::vec::Vec::with_capacity(size);
444            self.read_exact_into(size, &mut buf)?;
445            Ok(buf)
446        }
447
448        /// Reads the entire stream into a UTF-8 String, dropping all other bytes.
449        fn read_all_str_lossy(&mut self) -> Result<alloc::string::String, Error> {
450            Ok(String::from_utf8_lossy(&self.read_all_vec()?).to_string())
451        }
452
453        /// Reads the specified amount of bytes into a UTF-8 String, dropping all other bytes.
454        fn read_str_sized_lossy(&mut self, len: usize) -> Result<String, Error> {
455            Ok(String::from_utf8_lossy(&self.read_exact_vec(len)?).to_string())
456        }
457
458        /// Reads a string from the stream, terminated by a null byte.  Does NOT include the null byte.
459        fn read_str_null_terminated(&mut self) -> Result<String, Error> {
460            let mut out = String::new();
461            while let Some(ch) = self.next_u8()? {
462                if ch == 0 {
463                    break;
464                }
465                out.push(ch as char);
466            }
467            Ok(out)
468        }
469
470        /// Reads to the end of the stream and returns the data as a [`Vec<u8>`]
471        fn read_all_vec(&mut self) -> Result<alloc::vec::Vec<u8>, Error> {
472            let mut out: alloc::vec::Vec<u8> = vec![];
473            self.read_all_into(&mut out)?;
474            Ok(out)
475        }
476
477        ///
478        /// Reads from the input stream until:
479        /// 1. The byte stream represented by 'search' has been found or
480        /// 2. The input stream returns 0 bytes read (or errors out)
481        /// It returns all bytes read in the interim
482        fn read_until(&mut self, search: &[u8]) -> Result<alloc::vec::Vec<u8>, Error> {
483            let mut ringbuf: alloc::collections::VecDeque<u8> =
484                alloc::collections::VecDeque::with_capacity(search.len());
485
486            let mut out = Vec::new();
487            loop {
488                if ringbuf.iter().eq(search) {
489                    return Ok(out);
490                }
491
492                let Some(val) = self.next_u8()? else {
493                    return Ok(out);
494                };
495
496                if ringbuf.len() == search.len() {
497                    if let Some(val) = ringbuf.pop_front() {
498                        out.push(val);
499                    }
500                }
501                ringbuf.push_back(val);
502            }
503        }
504
505        ///
506        /// Reads until the next `\n` character, ignoring any `\r` characters along
507        /// the way.
508        fn read_line_vec(&mut self) -> Result<Option<alloc::vec::Vec<u8>>, Error> {
509            let mut out = Vec::new();
510            while let Some(val) = self.next_u8()? {
511                if val == b'\r' {
512                    continue;
513                }
514                else if val == b'\n' {
515                    return Ok(Some(out));
516                }
517                out.push(val);
518            }
519            if out.is_empty() {
520                return Ok(None)
521            }
522            Ok(Some(out))
523        }
524
525        ///
526        /// Reads until the next `\n` character, then calls [`String::from_utf8_lossy`].
527        fn read_line_str_lossy(&mut self) -> Result<Option<alloc::string::String>, Error> {
528            let Some(data) = self.read_line_vec()? else {
529                return Ok(None);
530            };
531            Ok(Some(String::from_utf8_lossy(&data).to_string()))
532        }
533
534        ///
535        /// Reads until the next `\n` character, then calls [`String::from_utf8`]
536        fn read_line_str(&mut self) -> Result<Option<alloc::string::String>, Error> {
537            let Some(data) = self.read_line_vec()? else {
538                return Ok(None);
539            };
540            Ok(Some(String::from_utf8(data)?))
541        }
542
543        ///
544        /// Consumes data from the input stream until:
545        /// 1. The byte stream represented by 'search' has been found or
546        /// 2. The input reader returns 0 bytes read (or errors out)
547        ///
548        /// Note: The input stream position is left JUST AFTER the found search string.
549        ///
550        /// Returns true if the search was found, false otherwise.
551        fn consume_until(&mut self, search: &[u8]) -> Result<bool, Error> {
552            let mut ringbuf: alloc::collections::VecDeque<u8> =
553                alloc::collections::VecDeque::with_capacity(search.len());
554            self.read_exact_into(search.len(), &mut ringbuf)?;
555
556            loop {
557                if ringbuf.iter().eq(search) {
558                    return Ok(true);
559                }
560
561                let Some(val) = self.next_u8()? else {
562                    return Ok(false);
563                };
564
565                ringbuf.pop_front();
566                ringbuf.push_back(val);
567            }
568        }
569
570        ///
571        /// Reads a specific sized string from the stream, a string prefixed by a
572        /// 4-byte big-endian length.
573        fn read_str_u32_blob(&mut self) -> Result<String, Error> {
574            let len = self.read_be_u32()?;
575            self.read_str_sized_lossy(len as usize)
576        }
577    }
578
579    /// Reads the specified amount of bytes into a stack-allocated array.
580    fn read_exact<const N: usize>(&mut self) -> Result<[u8; N], Error> {
581        let mut buf = [0u8; N];
582        self.read_exact_into(N, &mut buf.as_mut())?;
583        Ok(buf)
584    }
585
586    /// Reads the specified amount of bytes into the specified target.
587    fn read_exact_into<T: MutBits>(&mut self, size: usize, into: &mut T) -> Result<(), Error> {
588        for _i in 0..size {
589            into.write_u8(self.read_u8()?)?;
590        }
591        Ok(())
592    }
593
594    /// Reads to the end of the stream, and writes it into the specified target.
595    fn read_all_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
596        while let Some(val) = self.next_u8()? {
597            into.write_u8(val)?;
598        }
599        Ok(())
600    }
601
602    /// Fills the provided buffer
603    fn read_filling<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
604        while let Some(val) = self.next_u8()? {
605            if let Err(_e) = into.write_u8(val) {
606                break;
607            }
608        }
609        Ok(())
610    }
611
612    /// Reads some subset of the data into the specified target.
613    fn read_some_into<T: MutBits>(&mut self, buf: &mut T) -> Result<usize, Error> {
614        let mut read = 0;
615        for _ in 0..4096 {
616            let Some(val) = self.next_u8()? else {
617                return Ok(read);
618            };
619            buf.write_u8(val)?;
620            read += 1;
621        }
622        Ok(read)
623    }
624
625    /// Reads a single [`u16`] in the specified order order, 2 bytes.
626    fn read_u16(&mut self, order: ByteOrder) -> Result<u16, Error> {
627        match order {
628            ByteOrder::LittleEndian => self.read_le_u16(),
629            ByteOrder::BigEndian => self.read_be_u16(),
630        }
631    }
632    /// Reads a single [`u32`] in the specified order order, 4 bytes.
633    fn read_u32(&mut self, order: ByteOrder) -> Result<u32, Error> {
634        match order {
635            ByteOrder::LittleEndian => self.read_le_u32(),
636            ByteOrder::BigEndian => self.read_be_u32(),
637        }
638    }
639    /// Reads a single [`u64`] in the specified order order, 8 bytes.
640    fn read_u64(&mut self, order: ByteOrder) -> Result<u64, Error> {
641        match order {
642            ByteOrder::LittleEndian => self.read_le_u64(),
643            ByteOrder::BigEndian => self.read_be_u64(),
644        }
645    }
646    /// Reads a single [`u128`] in the specified order order, 16 bytes.
647    fn read_u128(&mut self, order: ByteOrder) -> Result<u128, Error> {
648        match order {
649            ByteOrder::LittleEndian => self.read_le_u128(),
650            ByteOrder::BigEndian => self.read_be_u128(),
651        }
652    }
653    /// Reads a single [`i16`] in the specified order order, 2 bytes.
654    fn read_i16(&mut self, order: ByteOrder) -> Result<i16, Error> {
655        match order {
656            ByteOrder::LittleEndian => self.read_le_i16(),
657            ByteOrder::BigEndian => self.read_be_i16(),
658        }
659    }
660    /// Reads a single [`i32`] in the specified order order, 4 bytes.
661    fn read_i32(&mut self, order: ByteOrder) -> Result<i32, Error> {
662        match order {
663            ByteOrder::LittleEndian => self.read_le_i32(),
664            ByteOrder::BigEndian => self.read_be_i32(),
665        }
666    }
667    /// Reads a single [`i64`] in the specified order order, 4 bytes.
668    fn read_i64(&mut self, order: ByteOrder) -> Result<i64, Error> {
669        match order {
670            ByteOrder::LittleEndian => self.read_le_i64(),
671            ByteOrder::BigEndian => self.read_be_i64(),
672        }
673    }
674    /// Reads a single [`i128`] in the specified order order, 16 bytes.
675    fn read_i128(&mut self, order: ByteOrder) -> Result<i128, Error> {
676        match order {
677            ByteOrder::LittleEndian => self.read_le_i128(),
678            ByteOrder::BigEndian => self.read_be_i128(),
679        }
680    }
681
682    /// Some implementations may be able to return the size of the remaining data
683    /// in the buffer.
684    fn remaining(&self) -> Option<usize> {
685        None
686    }
687}
688
689#[allow(unused_macros)]
690macro_rules! absorb_eof {
691    ($self:ident, $buf:ident) => {
692        if let Err(e) = $self.read_exact(&mut $buf) {
693            if e.kind() == ErrorKind::UnexpectedEof {
694                return Ok(None);
695            }
696            return Err(e);
697        }
698    };
699}
700
701impl Bits for &[u8] {
702    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
703        let Some((first, rest)) = self.split_first() else {
704            return Ok(None);
705        };
706        *self = rest;
707        Ok(Some(*first))
708    }
709
710    fn read_some_into<T: MutBits>(&mut self, into: &mut T) -> Result<usize, Error> {
711        Ok(into.write_some_bytes(self))
712    }
713
714    fn remaining(&self) -> Option<usize> {
715        Some(self.len())
716    }
717}
718
719impl Bits for &mut [u8] {
720    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
721        if let Some((first, rem)) = core::mem::take(self).split_first_mut() {
722            *self = rem;
723            return Ok(Some(*first));
724        }
725        Ok(None)
726    }
727
728    fn read_some_into<T: MutBits>(&mut self, into: &mut T) -> Result<usize, Error> {
729        Ok(into.write_some_bytes(self))
730    }
731
732    fn remaining(&self) -> Option<usize> {
733        Some(self.len())
734    }
735}
736
737/// Calls [`Bits::read_be_u32()`].  Provided for type-elusion purposes.
738pub fn read_be_u32<T: Bits>(mut data: T) -> Result<u32, Error> {
739    data.read_be_u32()
740}
741/// Calls [`Bits::read_be_u64()`].  Provided for type-elusion purposes.
742pub fn read_be_u64<T: Bits>(mut data: T) -> Result<u64, Error> {
743    data.read_be_u64()
744}
745/// Calls [`Bits::read_f32()`].  Provided for type-elusion purposes.
746pub fn read_f32<T: Bits>(mut data: T) -> Result<f32, Error> {
747    data.read_be_f32()
748}
749/// Calls [`Bits::read_f64()`].  Provided for type-elusion purposes.
750pub fn read_f64<T: Bits>(mut data: T) -> Result<f64, Error> {
751    data.read_be_f64()
752}
753
754///
755/// This struct wraps a provided borrowed static array in a MutBits impl.  Operates
756/// like a slice, walking through the array filling it up.
757pub struct MutBitsArray<'a, const N: usize> {
758    arr: &'a mut [u8; N],
759    pos: usize,
760}
761impl<'a, const N: usize> MutBitsArray<'a, N> {
762    /// Wraps the provided array, providing a [`MutBits`] impl
763    pub fn new(arr: &'a mut [u8; N]) -> Self {
764        Self { arr, pos: 0 }
765    }
766    /// Returns the current length of the written data.
767    pub fn len(&self) -> usize {
768        self.pos
769    }
770    /// Has anything been written?
771    pub fn is_empty(&self) -> bool {
772        self.len() == 0
773    }
774    /// Resets the writing position to zero. Does NOT clear the data.
775    pub fn reset(&mut self) {
776        self.pos = 0;
777    }
778    /// Resets the writing position to zero and clears the data back to zeros.
779    /// Same as calling `fill(0)`
780    pub fn zero(&mut self) {
781        self.fill(0)
782    }
783    /// Fills the array with the value, resets the writing position back to zero.
784    pub fn fill(&mut self, val: u8) {
785        self.arr.fill(val);
786        self.pos = 0;
787    }
788    /// Get an Reader from this array, starts at the beginning and runs until the
789    /// high water 'pos' mark returning a view into JUST the data written.
790    pub fn reader(&'a self) -> BitsArray<'a, N> {
791        BitsArray::new_limited(self.arr, self.pos)
792    }
793}
794impl<'a, const N: usize> From<&'a mut [u8; N]> for MutBitsArray<'a, N> {
795    fn from(arr: &'a mut [u8; N]) -> Self {
796        MutBitsArray { arr, pos: 0 }
797    }
798}
799impl<const N: usize> MutBits for MutBitsArray<'_, N> {
800    fn write_u8(&mut self, val: u8) -> Result<(), Error> {
801        if let Some(v) = self.arr.get_mut(self.pos) {
802            *v = val;
803            self.pos += 1;
804            return Ok(());
805        }
806        Err(BitsErrorKind::UnexpectedEof.into())
807    }
808}
809///
810/// This struct wraps a provided borrowed static array in a MutBits impl.  Operates
811/// like a slice, walking through the array filling it up.
812pub struct BitsArray<'a, const N: usize> {
813    arr: &'a [u8; N],
814    pos: usize,
815    max_len: usize,
816}
817impl<'a, const N: usize> BitsArray<'a, N> {
818    /// A new view into the backed array, limited only by the length of the backed array
819    pub fn new(arr: &'a [u8; N]) -> Self {
820        Self {
821            max_len: arr.len(),
822            pos: 0,
823            arr,
824        }
825    }
826    /// A new view into the backed array, limited by the provided maximum length.
827    pub fn new_limited(arr: &'a [u8; N], max_len: usize) -> Self {
828        Self {
829            arr,
830            max_len,
831            pos: 0,
832        }
833    }
834    /// Resets the reading position back to the start of the array.
835    pub fn reset(&mut self) {
836        self.pos = 0;
837    }
838}
839impl<'a, const N: usize> From<&'a [u8; N]> for BitsArray<'a, N> {
840    fn from(value: &'a [u8; N]) -> Self {
841        Self::new(value)
842    }
843}
844impl<const N: usize> Bits for BitsArray<'_, N> {
845    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
846        if self.pos >= self.max_len {
847            return Ok(None);
848        }
849        let v = self.arr.get(self.pos).copied();
850        self.pos += 1;
851        Ok(v)
852    }
853
854    fn remaining(&self) -> Option<usize> {
855        Some(self.max_len.saturating_sub(self.pos))
856    }
857}