#endianness #numbers #order #byte #reading #read #reader

byte-order

Rust library for reading and writing numbers in big-endian and little-endian

3 releases (breaking)

0.3.0 May 22, 2021
0.2.0 May 22, 2021
0.1.0 May 6, 2021

#43 in #endianness

Download history 44/week @ 2024-03-11 39/week @ 2024-03-18 50/week @ 2024-03-25 120/week @ 2024-04-01 46/week @ 2024-04-08 47/week @ 2024-04-15 47/week @ 2024-04-22 37/week @ 2024-04-29 42/week @ 2024-05-06 33/week @ 2024-05-13 34/week @ 2024-05-20 31/week @ 2024-05-27 40/week @ 2024-06-03 40/week @ 2024-06-10 33/week @ 2024-06-17 43/week @ 2024-06-24

160 downloads per month
Used in 6 crates (via loco-protocol)

MIT license

44KB
240 lines

byte-order  Build Status Latest Version

Rust library for reading and writing numbers in big-endian and little-endian. View the documentation on docs.rs here.

License

This crate is available as open source under the terms of the MIT License.


lib.rs:

This crate provides convenience methods for encoding and decoding numbers in either big-endian or little-endian byte order.

The organization of the crate is simple. A struct, NumberReader, wraps some reader with convenience methods to read each type of number in Rust except for numbers that have platform-dependent sizes (usize and isize). Likewise, a struct, NumberWriter, does the same for writers. Finally, an enum named ByteOrder is used to differentiate the endianness that NumberReader and NumberWriter structures perform their operations.

Examples

Read unsigned 16-bit big-endian integers from a reader:

use std::io::{self, Cursor};
use byte_order::{ByteOrder, NumberReader};

fn main() -> io::Result<()> {
    let src = Cursor::new(vec![0x12, 0x34, 0x56, 0x78]);

    let mut be_reader = NumberReader::with_order(ByteOrder::BE, src);
    assert_eq!(0x1234u16, be_reader.read_u16()?);
    assert_eq!(0x5678u16, be_reader.read_u16()?);

    Ok(())
}

Write unsigned 16-bit little-endian integers to a writer:

use std::io;
use byte_order::{ByteOrder, NumberWriter};

fn main() -> io::Result<()> {
    let mut le_writer = NumberWriter::with_order(ByteOrder::LE, vec![]);
    le_writer.write_u16(0x1234)?;
    le_writer.write_u16(0x5678)?;
    assert_eq!(le_writer.into_inner(), vec![0x34, 0x12, 0x78, 0x56]);

    Ok(())
}

Alternatives

This crate is an alternative to byteorder. What makes byte_order different at the design-level is the exclusion of extension traits and the ability to decide endianness once at the creation of a NumberReader or NumberWriter instead of once per operation.

The performance between byteorder and byte_order is comparable. It is strongly advised you compare these two crates and use what best suits your specific use case.

Likewise, as of Rust 1.32, the standard numeric types provide built-in methods like to_le_bytes and from_be_bytes, which support many of the same use cases.

No runtime deps