byte_order/
lib.rs

1//! This crate provides convenience methods for encoding and decoding numbers in
2//! either big-endian or little-endian byte order.
3//!
4//! The organization of the crate is simple. A struct, [`NumberReader`], wraps
5//! some [reader] with convenience methods to read each type of number in Rust
6//! except for numbers that have platform-dependent sizes (`usize` and
7//! `isize`). Likewise, a struct, [`NumberWriter`], does the same for
8//! [writers]. Finally, an enum named [`ByteOrder`] is used to differentiate
9//! the endianness that [`NumberReader`] and [`NumberWriter`] structures perform
10//! their operations.
11//!
12//! # Examples
13//!
14//! Read unsigned 16-bit big-endian integers from a reader:
15//!
16//! ```
17//! use std::io::{self, Cursor};
18//! use byte_order::{ByteOrder, NumberReader};
19//!
20//! fn main() -> io::Result<()> {
21//!     let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78]);
22//!
23//!     let mut be_reader = NumberReader::with_order(ByteOrder::BE, src);
24//!     assert_eq!(0x1234u16, be_reader.read_u16()?);
25//!     assert_eq!(0x5678u16, be_reader.read_u16()?);
26//!
27//!     Ok(())
28//! }
29//! ```
30//!
31//! Write unsigned 16-bit little-endian integers to a writer:
32//!
33//! ```
34//! use std::io;
35//! use byte_order::{ByteOrder, NumberWriter};
36//!
37//! fn main() -> io::Result<()> {
38//!     let mut le_writer = NumberWriter::with_order(ByteOrder::LE, vec![]);
39//!     le_writer.write_u16(0x1234)?;
40//!     le_writer.write_u16(0x5678)?;
41//!     assert_eq!(le_writer.into_inner(), vec![0x34, 0x12, 0x78, 0x56]);
42//!
43//!     Ok(())
44//! }
45//! ```
46//!
47//! # Alternatives
48//!
49//! This crate is an alternative to `byteorder`. What makes `byte_order`
50//! different at the design-level is the exclusion of extension traits and the
51//! ability to decide endianness once at the creation of a [`NumberReader`] or
52//! [`NumberWriter`] instead of once per operation.
53//!
54//! The performance between `byteorder` and `byte_order` is comparable. It is
55//! strongly advised you compare these two crates and use what best suits your
56//! specific use case.
57//!
58//! Likewise, as of Rust 1.32, the standard numeric types provide built-in
59//! methods like `to_le_bytes` and `from_be_bytes`, which support many of the
60//! same use cases.
61//!
62//! [`NumberReader`]: crate::NumberReader
63//! [`NumberWriter`]: crate::NumberWriter
64//! [reader]: https://doc.rust-lang.org/std/io/trait.Read.html
65//! [writers]: https://doc.rust-lang.org/std/io/trait.Write.html
66//! [`ByteOrder`]: crate::ByteOrder
67
68mod order;
69mod read;
70mod write;
71
72pub use order::ByteOrder;
73pub use read::NumberReader;
74pub use write::NumberWriter;