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    cfg_feature_alloc! {
391        /// Reads a sized blob, a series of bytes preceded by a [`u8`] declaring the size.
392        fn read_u8_blob(&mut self) -> Result<Vec<u8>, Error> {
393            let size = self.read_u8()?;
394            self.read_exact_vec(size as usize)
395        }
396
397        /// Reads a sized blob, a series of bytes preceded by a [`u16`] declaring the size.
398        fn read_be_u16_blob(&mut self) -> Result<Vec<u8>, Error> {
399            let size = self.read_be_u16()?;
400            self.read_exact_vec(size as usize)
401        }
402
403        /// Reads a sized blob, a series of bytes preceded by a [`u16`] declaring the size.
404        fn read_le_u16_blob(&mut self) -> Result<Vec<u8>, Error> {
405            let size = self.read_le_u16()?;
406            self.read_exact_vec(size as usize)
407        }
408        /// Reads a sized blob, a series of bytes preceded by a [`u32`] declaring the size.
409        fn read_be_u32_blob(&mut self) -> Result<Vec<u8>, Error> {
410            let size = self.read_be_u32()?;
411            self.read_exact_vec(size as usize)
412        }
413        /// Reads a sized blob, a series of bytes preceded by a [`u32`] declaring the size.
414        fn read_le_u32_blob(&mut self) -> Result<Vec<u8>, Error> {
415            let size = self.read_le_u32()?;
416            self.read_exact_vec(size as usize)
417        }
418
419        /// Reads a sized blob, a series of bytes preceded by a [`u64`] declaring the size.
420        fn read_be_u64_blob(&mut self) -> Result<Vec<u8>, Error> {
421            let size = self.read_be_u64()?;
422            self.read_exact_vec(size as usize)
423        }
424        /// Reads a sized blob, a series of bytes preceded by a [`u64`] declaring the size.
425        fn read_le_u64_blob(&mut self) -> Result<Vec<u8>, Error> {
426            let size = self.read_le_u64()?;
427            self.read_exact_vec(size as usize)
428        }
429
430        /// Reads the specified amount of bytes into a [`Vec<u8>`] and returns it
431        fn read_exact_vec(&mut self, size: usize) -> Result<alloc::vec::Vec<u8>, Error> {
432            let mut buf: alloc::vec::Vec<u8> = alloc::vec::Vec::with_capacity(size);
433            self.read_exact_into(size, &mut buf)?;
434            Ok(buf)
435        }
436
437        /// Reads the entire stream into a UTF-8 String, dropping all other bytes.
438        fn read_all_str_lossy(&mut self) -> Result<alloc::string::String, Error> {
439            Ok(String::from_utf8_lossy(&self.read_all_vec()?).to_string())
440        }
441
442        /// Reads the specified amount of bytes into a UTF-8 String, dropping all other bytes.
443        fn read_str_sized_lossy(&mut self, len: usize) -> Result<String, Error> {
444            Ok(String::from_utf8_lossy(&self.read_exact_vec(len)?).to_string())
445        }
446
447        /// Reads to the end of the stream and returns the data as a [`Vec<u8>`]
448        fn read_all_vec(&mut self) -> Result<alloc::vec::Vec<u8>, Error> {
449            let mut out: alloc::vec::Vec<u8> = vec![];
450            self.read_all_into(&mut out)?;
451            Ok(out)
452        }
453
454        ///
455        /// Reads from the input stream until:
456        /// 1. The byte stream represented by 'search' has been found or
457        /// 2. The input stream returns 0 bytes read (or errors out)
458        /// It returns all bytes read in the interim
459        fn read_until(&mut self, search: &[u8]) -> Result<alloc::vec::Vec<u8>, Error> {
460            let mut ringbuf: alloc::collections::VecDeque<u8> =
461                alloc::collections::VecDeque::with_capacity(search.len());
462
463            let mut out = Vec::new();
464            loop {
465                if ringbuf.iter().eq(search) {
466                    return Ok(out);
467                }
468
469                let Some(val) = self.next_u8()? else {
470                    return Ok(out);
471                };
472
473                if ringbuf.len() == search.len() {
474                    if let Some(val) = ringbuf.pop_front() {
475                        out.push(val);
476                    }
477                }
478                ringbuf.push_back(val);
479            }
480        }
481
482        ///
483        /// Reads until the next `\n` character, ignoring any `\r` characters along
484        /// the way.
485        fn read_line_vec(&mut self) -> Result<Option<alloc::vec::Vec<u8>>, Error> {
486            let mut out = Vec::new();
487            while let Some(val) = self.next_u8()? {
488                if val == b'\r' {
489                    continue;
490                }
491                else if val == b'\n' {
492                    return Ok(Some(out));
493                }
494                out.push(val);
495            }
496            if out.is_empty() {
497                return Ok(None)
498            }
499            Ok(Some(out))
500        }
501
502        ///
503        /// Reads until the next `\n` character, then calls [`String::from_utf8_lossy`].
504        fn read_line_str_lossy(&mut self) -> Result<Option<alloc::string::String>, Error> {
505            let Some(data) = self.read_line_vec()? else {
506                return Ok(None);
507            };
508            Ok(Some(String::from_utf8_lossy(&data).to_string()))
509        }
510
511        ///
512        /// Reads until the next `\n` character, then calls [`String::from_utf8`]
513        fn read_line_str(&mut self) -> Result<Option<alloc::string::String>, Error> {
514            let Some(data) = self.read_line_vec()? else {
515                return Ok(None);
516            };
517            Ok(Some(String::from_utf8(data)?))
518        }
519
520        ///
521        /// Consumes data from the input stream until:
522        /// 1. The byte stream represented by 'search' has been found or
523        /// 2. The input reader returns 0 bytes read (or errors out)
524        ///
525        /// Note: The input stream position is left JUST AFTER the found search string.
526        fn consume_until(&mut self, search: &[u8]) -> Result<(), Error> {
527            let mut ringbuf: alloc::collections::VecDeque<u8> =
528                alloc::collections::VecDeque::with_capacity(search.len());
529            self.read_exact_into(search.len(), &mut ringbuf)?;
530
531            loop {
532                if ringbuf.iter().eq(search) {
533                    return Ok(());
534                }
535
536                let Some(val) = self.next_u8()? else {
537                    return Ok(());
538                };
539
540                ringbuf.pop_front();
541                ringbuf.push_back(val);
542            }
543        }
544
545        ///
546        /// Reads a specific sized string from the stream, a string prefixed by a
547        /// 4-byte big-endian length.
548        fn read_str_u32_blob(&mut self) -> Result<String, Error> {
549            let len = self.read_be_u32()?;
550            self.read_str_sized_lossy(len as usize)
551        }
552    }
553
554    /// Reads the specified amount of bytes into a stack-allocated array.
555    fn read_exact<const N: usize>(&mut self) -> Result<[u8; N], Error> {
556        let mut buf = [0u8; N];
557        self.read_exact_into(N, &mut buf.as_mut())?;
558        Ok(buf)
559    }
560
561    /// Reads the specified amount of bytes into the specified target.
562    fn read_exact_into<T: MutBits>(&mut self, size: usize, into: &mut T) -> Result<(), Error> {
563        for _i in 0..size {
564            into.write_u8(self.read_u8()?)?;
565        }
566        Ok(())
567    }
568
569    /// Reads to the end of the stream, and writes it into the specified target.
570    fn read_all_into<T: MutBits>(&mut self, into: &mut T) -> Result<(), Error> {
571        while let Some(val) = self.next_u8()? {
572            into.write_u8(val)?;
573        }
574        Ok(())
575    }
576
577    /// Reads some subset of the data into the specified target.
578    fn read_some_into<T: MutBits>(&mut self, buf: &mut T) -> Result<usize, Error> {
579        let mut read = 0;
580        for _ in 0..4096 {
581            let Some(val) = self.next_u8()? else {
582                return Ok(read);
583            };
584            buf.write_u8(val)?;
585            read += 1;
586        }
587        Ok(read)
588    }
589
590    /// Reads a single [`u16`] in the specified order order, 2 bytes.
591    fn read_u16(&mut self, order: ByteOrder) -> Result<u16, Error> {
592        match order {
593            ByteOrder::LittleEndian => self.read_le_u16(),
594            ByteOrder::BigEndian => self.read_be_u16(),
595        }
596    }
597    /// Reads a single [`u32`] in the specified order order, 4 bytes.
598    fn read_u32(&mut self, order: ByteOrder) -> Result<u32, Error> {
599        match order {
600            ByteOrder::LittleEndian => self.read_le_u32(),
601            ByteOrder::BigEndian => self.read_be_u32(),
602        }
603    }
604    /// Reads a single [`u64`] in the specified order order, 8 bytes.
605    fn read_u64(&mut self, order: ByteOrder) -> Result<u64, Error> {
606        match order {
607            ByteOrder::LittleEndian => self.read_le_u64(),
608            ByteOrder::BigEndian => self.read_be_u64(),
609        }
610    }
611    /// Reads a single [`u128`] in the specified order order, 16 bytes.
612    fn read_u128(&mut self, order: ByteOrder) -> Result<u128, Error> {
613        match order {
614            ByteOrder::LittleEndian => self.read_le_u128(),
615            ByteOrder::BigEndian => self.read_be_u128(),
616        }
617    }
618    /// Reads a single [`i16`] in the specified order order, 2 bytes.
619    fn read_i16(&mut self, order: ByteOrder) -> Result<i16, Error> {
620        match order {
621            ByteOrder::LittleEndian => self.read_le_i16(),
622            ByteOrder::BigEndian => self.read_be_i16(),
623        }
624    }
625    /// Reads a single [`i32`] in the specified order order, 4 bytes.
626    fn read_i32(&mut self, order: ByteOrder) -> Result<i32, Error> {
627        match order {
628            ByteOrder::LittleEndian => self.read_le_i32(),
629            ByteOrder::BigEndian => self.read_be_i32(),
630        }
631    }
632    /// Reads a single [`i64`] in the specified order order, 4 bytes.
633    fn read_i64(&mut self, order: ByteOrder) -> Result<i64, Error> {
634        match order {
635            ByteOrder::LittleEndian => self.read_le_i64(),
636            ByteOrder::BigEndian => self.read_be_i64(),
637        }
638    }
639    /// Reads a single [`i128`] in the specified order order, 16 bytes.
640    fn read_i128(&mut self, order: ByteOrder) -> Result<i128, Error> {
641        match order {
642            ByteOrder::LittleEndian => self.read_le_i128(),
643            ByteOrder::BigEndian => self.read_be_i128(),
644        }
645    }
646}
647
648#[allow(unused_macros)]
649macro_rules! absorb_eof {
650    ($self:ident, $buf:ident) => {
651        if let Err(e) = $self.read_exact(&mut $buf) {
652            if e.kind() == ErrorKind::UnexpectedEof {
653                return Ok(None);
654            }
655            return Err(e);
656        }
657    };
658}
659
660impl Bits for &[u8] {
661    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
662        let Some((first, rest)) = self.split_first() else {
663            return Ok(None);
664        };
665        *self = rest;
666        Ok(Some(*first))
667    }
668
669    fn read_some_into<T: MutBits>(&mut self, into: &mut T) -> Result<usize, Error> {
670        Ok(into.write_some_bytes(self))
671    }
672}
673
674impl Bits for &mut [u8] {
675    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
676        if let Some((first, rem)) = core::mem::take(self).split_first_mut() {
677            *self = rem;
678            return Ok(Some(*first));
679        }
680        Ok(None)
681    }
682
683    fn read_some_into<T: MutBits>(&mut self, into: &mut T) -> Result<usize, Error> {
684        Ok(into.write_some_bytes(self))
685    }
686}
687
688/// Calls [`Bits::read_be_u32()`].  Provided for type-elusion purposes.
689pub fn read_be_u32<T: Bits>(mut data: T) -> Result<u32, Error> {
690    data.read_be_u32()
691}
692/// Calls [`Bits::read_be_u64()`].  Provided for type-elusion purposes.
693pub fn read_be_u64<T: Bits>(mut data: T) -> Result<u64, Error> {
694    data.read_be_u64()
695}
696/// Calls [`Bits::read_f32()`].  Provided for type-elusion purposes.
697pub fn read_f32<T: Bits>(mut data: T) -> Result<f32, Error> {
698    data.read_be_f32()
699}
700/// Calls [`Bits::read_f64()`].  Provided for type-elusion purposes.
701pub fn read_f64<T: Bits>(mut data: T) -> Result<f64, Error> {
702    data.read_be_f64()
703}
704
705///
706/// This struct wraps a provided borrowed static array in a MutBits impl.  Operates
707/// like a slice, walking through the array filling it up.
708pub struct MutBitsArray<'a, const N: usize> {
709    arr: &'a mut [u8; N],
710    pos: usize,
711}
712impl<'a, const N: usize> MutBitsArray<'a, N> {
713    /// Wraps the provided array, providing a [`MutBits`] impl
714    pub fn new(arr: &'a mut [u8; N]) -> Self {
715        Self { arr, pos: 0 }
716    }
717    /// Returns the current length of the written data.
718    pub fn len(&self) -> usize {
719        self.pos
720    }
721    /// Has anything been written?
722    pub fn is_empty(&self) -> bool {
723        self.len() == 0
724    }
725    /// Resets the writing position to zero. Does NOT clear the data.
726    pub fn reset(&mut self) {
727        self.pos = 0;
728    }
729    /// Resets the writing position to zero and clears the data back to zeros.
730    /// Same as calling `fill(0)`
731    pub fn zero(&mut self) {
732        self.fill(0)
733    }
734    /// Fills the array with the value, resets the writing position back to zero.
735    pub fn fill(&mut self, val: u8) {
736        self.arr.fill(val);
737        self.pos = 0;
738    }
739    /// Get an Reader from this array, starts at the beginning and runs until the
740    /// high water 'pos' mark returning a view into JUST the data written.
741    pub fn reader(&'a self) -> BitsArray<'a, N> {
742        BitsArray::new_limited(self.arr, self.pos)
743    }
744}
745impl<'a, const N: usize> From<&'a mut [u8; N]> for MutBitsArray<'a, N> {
746    fn from(arr: &'a mut [u8; N]) -> Self {
747        MutBitsArray { arr, pos: 0 }
748    }
749}
750impl<const N: usize> MutBits for MutBitsArray<'_, N> {
751    fn write_u8(&mut self, val: u8) -> Result<(), Error> {
752        if let Some(v) = self.arr.get_mut(self.pos) {
753            *v = val;
754            self.pos += 1;
755            return Ok(());
756        }
757        Err(BitsErrorKind::UnexpectedEof.into())
758    }
759}
760///
761/// This struct wraps a provided borrowed static array in a MutBits impl.  Operates
762/// like a slice, walking through the array filling it up.
763pub struct BitsArray<'a, const N: usize> {
764    arr: &'a [u8; N],
765    pos: usize,
766    max_len: usize,
767}
768impl<'a, const N: usize> BitsArray<'a, N> {
769    /// A new view into the backed array, limited only by the length of the backed array
770    pub fn new(arr: &'a [u8; N]) -> Self {
771        Self {
772            max_len: arr.len(),
773            pos: 0,
774            arr,
775        }
776    }
777    /// A new view into the backed array, limited by the provided maximum length.
778    pub fn new_limited(arr: &'a [u8; N], max_len: usize) -> Self {
779        Self {
780            arr,
781            max_len,
782            pos: 0,
783        }
784    }
785    /// Resets the reading position back to the start of the array.
786    pub fn reset(&mut self) {
787        self.pos = 0;
788    }
789}
790impl<'a, const N: usize> From<&'a [u8; N]> for BitsArray<'a, N> {
791    fn from(value: &'a [u8; N]) -> Self {
792        Self::new(value)
793    }
794}
795impl<const N: usize> Bits for BitsArray<'_, N> {
796    fn next_u8(&mut self) -> Result<Option<u8>, Error> {
797        if self.pos >= self.max_len {
798            return Ok(None);
799        }
800        let v = self.arr.get(self.pos).copied();
801        self.pos += 1;
802        Ok(v)
803    }
804}