byte_order/read.rs
1use std::io::{self, Read};
2use std::mem;
3
4use crate::order::ByteOrder;
5
6/// A `NumberReader` wraps a [reader] and provides methods for reading numbers.
7///
8/// Unlike many libraries, which take byte order as a parameter per operation, a
9/// `NumberReader` takes byte order as a parameter upon initialization.
10///
11/// # Examples
12///
13/// We can create a new `NumberReader` using the target endianness using
14/// [`NumberReader::new`]:
15///
16/// ```
17/// use std::io::Cursor;
18/// use byte_order::NumberReader;
19///
20/// let src = Cursor::new(vec![]);
21/// let mut reader = NumberReader::new(src);
22/// ```
23///
24/// Or, to read numbers with a certain endianness, we can create `NumberReader`
25/// structures using [`NumberReader::with_order`]:
26///
27/// ```
28/// use std::io::Cursor;
29/// use byte_order::{ByteOrder, NumberReader};
30///
31/// let src = Cursor::new(vec![]);
32/// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
33/// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
34/// let mut ne_reader = NumberReader::with_order(ByteOrder::NE, src.clone());
35/// ```
36///
37/// To read numbers from the underlying [reader], use any of the `read_*`
38/// methods that are provided:
39///
40/// ```
41/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
42/// use std::io::Cursor;
43/// use byte_order::{ByteOrder, NumberReader};
44///
45/// let src = Cursor::new(vec![0xA1, 0xB2]);
46///
47/// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
48/// assert_eq!(0xA1B2, be_reader.read_u16()?);
49///
50/// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
51/// assert_eq!(0xB2A1, le_reader.read_u16()?);
52///
53/// let mut ne_reader = NumberReader::with_order(ByteOrder::NE, src.clone());
54/// assert_eq!(
55/// if cfg!(target_endian = "big") {
56/// 0xA1B2
57/// } else {
58/// 0xB2A1
59/// },
60/// ne_reader.read_u16()?
61/// );
62/// # Ok(())
63/// # }
64/// ```
65///
66/// [reader]: https://doc.rust-lang.org/std/io/trait.Read.html
67/// [`NumberReader::new`]: NumberReader::new
68/// [`NumberReader::with_order`]: NumberReader::with_order
69pub struct NumberReader<R: Read> {
70 inner: R,
71 order: ByteOrder,
72}
73
74impl<R: Read> NumberReader<R> {
75 /// Creates a new `NumberReader` by wrapping the given [reader].
76 ///
77 /// Since the target platform's native endianness is used, portable code
78 /// should use [`with_order`], as appropriate, instead.
79 ///
80 /// **Note:** If you want to explicitly mark in your code that the target
81 /// platform's endianness is desired, consider creating the `NumberReader`
82 /// using [`with_order`] and [`ByteOrder::NE`].
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// use std::io::{self, Cursor};
88 /// use byte_order::NumberReader;
89 ///
90 /// fn main() -> io::Result<()> {
91 /// let src = Cursor::new(vec![0xA1, 0xB2]);
92 /// let mut reader = NumberReader::new(src);
93 ///
94 /// assert_eq!(
95 /// reader.read_u16()?,
96 /// if cfg!(target_endian = "big") {
97 /// 0xA1B2
98 /// } else {
99 /// 0xB2A1
100 /// }
101 /// );
102 ///
103 /// Ok(())
104 /// }
105 /// ```
106 ///
107 /// [reader]: https://doc.rust-lang.org/std/io/trait.Read.html
108 /// [`with_order`]: NumberReader::with_order
109 /// [`ByteOrder::NE`]: ByteOrder::NE
110 #[inline]
111 pub fn new(src: R) -> NumberReader<R> {
112 NumberReader::with_order(ByteOrder::NE, src)
113 }
114
115 /// Creates a new `NumberReader` by wrapping the given [reader] with the
116 /// specified byte order.
117 ///
118 /// Use either [`ByteOrder::BE`] for big-endian byte ordering,
119 /// [`ByteOrder::LE`] for little-endian byte ordering, or [`ByteOrder::NE`]
120 /// to explicitly use the target platform's endianness.
121 ///
122 /// # Examples
123 ///
124 /// ```
125 /// use std::io::{self, Cursor};
126 /// use byte_order::{ByteOrder, NumberReader};
127 ///
128 /// fn main() -> io::Result<()> {
129 /// let src = Cursor::new(vec![0xA1, 0xB2]);
130 ///
131 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
132 /// assert_eq!(0xA1B2, be_reader.read_u16()?);
133 ///
134 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
135 /// assert_eq!(0xB2A1, le_reader.read_u16()?);
136 ///
137 /// let mut ne_reader = NumberReader::with_order(ByteOrder::NE, src.clone());
138 /// assert_eq!(
139 /// if cfg!(target_endian = "big") {
140 /// 0xA1B2
141 /// } else {
142 /// 0xB2A1
143 /// },
144 /// ne_reader.read_u16()?
145 /// );
146 ///
147 /// Ok(())
148 /// }
149 /// ```
150 ///
151 /// [reader]: https://doc.rust-lang.org/std/io/trait.Read.html
152 /// [`ByteOrder::BE`]: ByteOrder::BE
153 /// [`ByteOrder::LE`]: ByteOrder::LE
154 /// [`ByteOrder::NE`]: ByteOrder::NE
155 #[inline]
156 pub fn with_order(order: ByteOrder, src: R) -> NumberReader<R> {
157 NumberReader { inner: src, order }
158 }
159
160 /// Consumes this `NumberReader`, returning the underlying value.
161 ///
162 /// # Examples
163 ///
164 /// ```
165 /// use std::io::Cursor;
166 /// use byte_order::NumberReader;
167 ///
168 /// let reader = NumberReader::new(Cursor::new(vec![]));
169 ///
170 /// let cursor = reader.into_inner();
171 /// ```
172 pub fn into_inner(self) -> R {
173 self.inner
174 }
175
176 /// Gets a reference to the underlying value in this `NumberReader`.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// use std::io::Cursor;
182 /// use byte_order::NumberReader;
183 ///
184 /// let reader = NumberReader::new(Cursor::new(vec![]));
185 ///
186 /// let reference = reader.get_ref();
187 /// ```
188 pub fn get_ref(&self) -> &R {
189 &self.inner
190 }
191
192 /// Gets a mutable reference to the underlying value in this `NumberReader`.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use std::io::Cursor;
198 /// use byte_order::NumberReader;
199 ///
200 /// let mut reader = NumberReader::new(Cursor::new(vec![]));
201 ///
202 /// let reference = reader.get_mut();
203 /// ```
204 pub fn get_mut(&mut self) -> &mut R {
205 &mut self.inner
206 }
207
208 /// Reads an unsigned 8-bit integer from the underlying reader.
209 ///
210 /// **Note:** Since this method reads a single byte, no byte order
211 /// conversions are used. It is included for completeness.
212 ///
213 /// # Errors
214 ///
215 /// This method propagates any error recieved from the internal call to
216 /// [`Read::read_exact`].
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use std::io::{self, Cursor};
222 /// use byte_order::NumberReader;
223 ///
224 /// fn main() -> io::Result<()> {
225 /// let mut reader = NumberReader::new(Cursor::new(vec![0x12]));
226 /// assert_eq!(0x12u8, reader.read_u8()?);
227 /// Ok(())
228 /// }
229 /// ```
230 ///
231 /// [`Read::read_exact`]: Read::read_exact
232 #[inline]
233 pub fn read_u8(&mut self) -> io::Result<u8> {
234 let mut buf = [0; mem::size_of::<u8>()];
235 self.inner.read_exact(&mut buf)?;
236 Ok(buf[0])
237 }
238
239 /// Reads a signed 8-bit integer from the underlying reader.
240 ///
241 /// **Note:** Since this method reads a single byte, no byte order
242 /// conversions are used. It is included for completeness.
243 ///
244 /// # Errors
245 ///
246 /// This method propagates any error recieved from the internal call to
247 /// [`Read::read_exact`].
248 ///
249 /// # Examples
250 ///
251 /// ```
252 /// use std::io::{self, Cursor};
253 /// use byte_order::NumberReader;
254 ///
255 /// fn main() -> io::Result<()> {
256 /// let mut reader = NumberReader::new(Cursor::new(vec![0x12]));
257 /// assert_eq!(0x12i8, reader.read_i8()?);
258 /// Ok(())
259 /// }
260 /// ```
261 ///
262 /// [`Read::read_exact`]: Read::read_exact
263 #[inline]
264 pub fn read_i8(&mut self) -> io::Result<i8> {
265 Ok(self.read_u8()? as i8)
266 }
267
268 /// Reads an unsigned 16-bit integer from the underlying reader.
269 ///
270 /// # Errors
271 ///
272 /// This method propagates any error recieved from the internal call to
273 /// [`Read::read_exact`].
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// use std::io::{self, Cursor};
279 /// use byte_order::{ByteOrder, NumberReader};
280 ///
281 /// fn main() -> io::Result<()> {
282 /// let src = Cursor::new(vec![0x12, 0x34]);
283 ///
284 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
285 /// assert_eq!(0x1234u16, be_reader.read_u16()?);
286 ///
287 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
288 /// assert_eq!(0x3412u16, le_reader.read_u16()?);
289 ///
290 /// Ok(())
291 /// }
292 /// ```
293 ///
294 /// [`Read::read_exact`]: Read::read_exact
295 #[inline]
296 pub fn read_u16(&mut self) -> io::Result<u16> {
297 let mut buf = [0; mem::size_of::<u16>()];
298 self.inner.read_exact(&mut buf)?;
299 Ok(if let ByteOrder::LE = self.order {
300 u16::from_le_bytes(buf)
301 } else {
302 u16::from_be_bytes(buf)
303 })
304 }
305
306 /// Reads a signed 16-bit integer from the underlying reader.
307 ///
308 /// # Errors
309 ///
310 /// This method propagates any error recieved from the internal call to
311 /// [`Read::read_exact`].
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// use std::io::{self, Cursor};
317 /// use byte_order::{ByteOrder, NumberReader};
318 ///
319 /// fn main() -> io::Result<()> {
320 /// let src = Cursor::new(vec![0x12, 0x34]);
321 ///
322 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
323 /// assert_eq!(0x1234i16, be_reader.read_i16()?);
324 ///
325 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
326 /// assert_eq!(0x3412i16, le_reader.read_i16()?);
327 ///
328 /// Ok(())
329 /// }
330 /// ```
331 ///
332 /// [`Read::read_exact`]: Read::read_exact
333 #[inline]
334 pub fn read_i16(&mut self) -> io::Result<i16> {
335 Ok(self.read_u16()? as i16)
336 }
337
338 /// Reads an unsigned 32-bit integer from the underlying reader.
339 ///
340 /// # Errors
341 ///
342 /// This method propagates any error recieved from the internal call to
343 /// [`Read::read_exact`].
344 ///
345 /// # Examples
346 ///
347 /// ```
348 /// use std::io::{self, Cursor};
349 /// use byte_order::{ByteOrder, NumberReader};
350 ///
351 /// fn main() -> io::Result<()> {
352 /// let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78]);
353 ///
354 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
355 /// assert_eq!(0x12345678u32, be_reader.read_u32()?);
356 ///
357 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
358 /// assert_eq!(0x78563412u32, le_reader.read_u32()?);
359 ///
360 /// Ok(())
361 /// }
362 /// ```
363 ///
364 /// [`Read::read_exact`]: Read::read_exact
365 #[inline]
366 pub fn read_u32(&mut self) -> io::Result<u32> {
367 let mut buf = [0; mem::size_of::<u32>()];
368 self.inner.read_exact(&mut buf)?;
369 Ok(if let ByteOrder::LE = self.order {
370 u32::from_le_bytes(buf)
371 } else {
372 u32::from_be_bytes(buf)
373 })
374 }
375
376 /// Reads a signed 32-bit integer from the underlying reader.
377 ///
378 /// # Errors
379 ///
380 /// This method propagates any error recieved from the internal call to
381 /// [`Read::read_exact`].
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use std::io::{self, Cursor};
387 /// use byte_order::{ByteOrder, NumberReader};
388 ///
389 /// fn main() -> io::Result<()> {
390 /// let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78]);
391 ///
392 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
393 /// assert_eq!(0x12345678i32, be_reader.read_i32()?);
394 ///
395 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
396 /// assert_eq!(0x78563412i32, le_reader.read_i32()?);
397 ///
398 /// Ok(())
399 /// }
400 /// ```
401 ///
402 /// [`Read::read_exact`]: Read::read_exact
403 #[inline]
404 pub fn read_i32(&mut self) -> io::Result<i32> {
405 Ok(self.read_u32()? as i32)
406 }
407
408 /// Reads an unsigned 64-bit integer from the underlying reader.
409 ///
410 /// # Errors
411 ///
412 /// This method propagates any error recieved from the internal call to
413 /// [`Read::read_exact`].
414 ///
415 /// # Examples
416 ///
417 /// ```
418 /// use std::io::{self, Cursor};
419 /// use byte_order::{ByteOrder, NumberReader};
420 ///
421 /// fn main() -> io::Result<()> {
422 /// let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);
423 ///
424 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
425 /// assert_eq!(0x1234567890123456u64, be_reader.read_u64()?);
426 ///
427 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
428 /// assert_eq!(0x5634129078563412u64, le_reader.read_u64()?);
429 ///
430 /// Ok(())
431 /// }
432 /// ```
433 ///
434 /// [`Read::read_exact`]: Read::read_exact
435 #[inline]
436 pub fn read_u64(&mut self) -> io::Result<u64> {
437 let mut buf = [0; mem::size_of::<u64>()];
438 self.inner.read_exact(&mut buf)?;
439 Ok(if let ByteOrder::LE = self.order {
440 u64::from_le_bytes(buf)
441 } else {
442 u64::from_be_bytes(buf)
443 })
444 }
445
446 /// Reads a signed 64-bit integer from the underlying reader.
447 ///
448 /// # Errors
449 ///
450 /// This method propagates any error recieved from the internal call to
451 /// [`Read::read_exact`].
452 ///
453 /// # Examples
454 ///
455 /// ```
456 /// use std::io::{self, Cursor};
457 /// use byte_order::{ByteOrder, NumberReader};
458 ///
459 /// fn main() -> io::Result<()> {
460 /// let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);
461 ///
462 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
463 /// assert_eq!(0x1234567890123456i64, be_reader.read_i64()?);
464 ///
465 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
466 /// assert_eq!(0x5634129078563412i64, le_reader.read_i64()?);
467 ///
468 /// Ok(())
469 /// }
470 /// ```
471 ///
472 /// [`Read::read_exact`]: Read::read_exact
473 #[inline]
474 pub fn read_i64(&mut self) -> io::Result<i64> {
475 Ok(self.read_u64()? as i64)
476 }
477
478 /// Reads an unsigned 128-bit integer from the underlying reader.
479 ///
480 /// # Errors
481 ///
482 /// This method propagates any error recieved from the internal call to
483 /// [`Read::read_exact`].
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use std::io::{self, Cursor};
489 /// use byte_order::{ByteOrder, NumberReader};
490 ///
491 /// fn main() -> io::Result<()> {
492 /// let src = Cursor::new(vec![
493 /// 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56,
494 /// 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12,
495 /// ]);
496 ///
497 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
498 /// assert_eq!(0x12345678901234567890123456789012u128, be_reader.read_u128()?);
499 ///
500 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
501 /// assert_eq!(0x12907856341290785634129078563412u128, le_reader.read_u128()?);
502 ///
503 /// Ok(())
504 /// }
505 /// ```
506 ///
507 /// [`Read::read_exact`]: Read::read_exact
508 #[inline]
509 pub fn read_u128(&mut self) -> io::Result<u128> {
510 let mut buf = [0; mem::size_of::<u128>()];
511 self.inner.read_exact(&mut buf)?;
512 Ok(if let ByteOrder::LE = self.order {
513 u128::from_le_bytes(buf)
514 } else {
515 u128::from_be_bytes(buf)
516 })
517 }
518
519 /// Reads a signed 128-bit integer from the underlying reader.
520 ///
521 /// # Errors
522 ///
523 /// This method propagates any error recieved from the internal call to
524 /// [`Read::read_exact`].
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// use std::io::{self, Cursor};
530 /// use byte_order::{ByteOrder, NumberReader};
531 ///
532 /// fn main() -> io::Result<()> {
533 /// let src = Cursor::new(vec![
534 /// 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56,
535 /// 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12,
536 /// ]);
537 ///
538 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, src.clone());
539 /// assert_eq!(0x12345678901234567890123456789012u128, be_reader.read_u128()?);
540 ///
541 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, src.clone());
542 /// assert_eq!(0x12907856341290785634129078563412u128, le_reader.read_u128()?);
543 ///
544 /// Ok(())
545 /// }
546 /// ```
547 ///
548 /// [`Read::read_exact`]: Read::read_exact
549 #[inline]
550 pub fn read_i128(&mut self) -> io::Result<i128> {
551 Ok(self.read_u128()? as i128)
552 }
553
554 /// Reads a IEEE754 single-precision floating point number from the
555 /// underlying reader.
556 ///
557 /// # Errors
558 ///
559 /// This method propagates any error recieved from the internal call to
560 /// [`Read::read_exact`].
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// use std::io::{self, Cursor};
566 /// use byte_order::{ByteOrder, NumberReader};
567 ///
568 /// fn main() -> io::Result<()> {
569 /// let be_src = Cursor::new(vec![0x41, 0x48, 0x00, 0x00]);
570 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, be_src);
571 /// assert_eq!(12.5f32, be_reader.read_f32()?);
572 ///
573 /// let le_src = Cursor::new(vec![0x00, 0x00, 0x48, 0x41]);
574 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, le_src);
575 /// assert_eq!(12.5f32, le_reader.read_f32()?);
576 ///
577 /// Ok(())
578 /// }
579 /// ```
580 ///
581 /// [`Read::read_exact`]: Read::read_exact
582 #[inline]
583 pub fn read_f32(&mut self) -> io::Result<f32> {
584 let mut buf = [0; mem::size_of::<f32>()];
585 self.inner.read_exact(&mut buf)?;
586 Ok(if let ByteOrder::LE = self.order {
587 f32::from_le_bytes(buf)
588 } else {
589 f32::from_be_bytes(buf)
590 })
591 }
592
593 /// Reads a IEEE754 double-precision floating point number from the
594 /// underlying reader.
595 ///
596 /// # Errors
597 ///
598 /// This method propagates any error recieved from the internal call to
599 /// [`Read::read_exact`].
600 ///
601 /// # Examples
602 ///
603 /// ```
604 /// use std::io::{self, Cursor};
605 /// use byte_order::{ByteOrder, NumberReader};
606 ///
607 /// fn main() -> io::Result<()> {
608 /// let be_src = Cursor::new(vec![0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
609 /// let mut be_reader = NumberReader::with_order(ByteOrder::BE, be_src);
610 /// assert_eq!(12.5f64, be_reader.read_f64()?);
611 ///
612 /// let le_src = Cursor::new(vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
613 /// let mut le_reader = NumberReader::with_order(ByteOrder::LE, le_src);
614 /// assert_eq!(12.5f64, le_reader.read_f64()?);
615 ///
616 /// Ok(())
617 /// }
618 /// ```
619 ///
620 /// [`Read::read_exact`]: Read::read_exact
621 #[inline]
622 pub fn read_f64(&mut self) -> io::Result<f64> {
623 let mut buf = [0; mem::size_of::<f64>()];
624 self.inner.read_exact(&mut buf)?;
625 Ok(if let ByteOrder::LE = self.order {
626 f64::from_le_bytes(buf)
627 } else {
628 f64::from_be_bytes(buf)
629 })
630 }
631}
632
633impl<R: Read> Read for NumberReader<R> {
634 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
635 self.inner.read(buf)
636 }
637}