binrw/
endian.rs

1//! Type definitions for byte order handling.
2
3use crate::BinResult;
4#[cfg(not(feature = "std"))]
5use alloc::boxed::Box;
6pub use Endian::{Big as BE, Little as LE};
7
8/// Defines the order of bytes in a multi-byte type.
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum Endian {
11    /// The most significant byte is stored first.
12    Big,
13    /// The least significant byte is stored first.
14    Little,
15}
16
17impl Endian {
18    #[cfg(target_endian = "big")]
19    /// The target platform’s native endianness.
20    pub const NATIVE: Self = Endian::Big;
21    #[cfg(target_endian = "little")]
22    /// The target platform’s native endianness.
23    pub const NATIVE: Self = Endian::Little;
24
25    /// Converts a byte array containing a UTF-16 [byte order mark] into an
26    /// `Endian` value.
27    ///
28    /// [byte order mark]: https://en.wikipedia.org/wiki/Byte_order_mark
29    ///
30    /// # Errors
31    ///
32    /// Returns an error if the input does not contain a byte order mark.
33    pub fn from_utf16_bom_bytes(bom: [u8; 2]) -> BinResult<Self> {
34        match u16::from_le_bytes(bom) {
35            BOM => Ok(Self::Little),
36            REVERSE_BOM => Ok(Self::Big),
37            _ => Err(crate::Error::BadMagic {
38                pos: u64::MAX,
39                found: Box::new("Invalid UTF-16 BOM"),
40            }),
41        }
42    }
43
44    /// Converts an `Endian` value into an array containing a UTF-16
45    /// [byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark).
46    #[must_use]
47    pub fn into_utf16_bom_bytes(self) -> [u8; 2] {
48        match self {
49            Self::Little => u16::to_le_bytes(BOM),
50            Self::Big => u16::to_be_bytes(BOM),
51        }
52    }
53}
54
55impl core::fmt::Display for Endian {
56    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
57        match self {
58            Self::Big => write!(f, "Big"),
59            Self::Little => write!(f, "Little"),
60        }
61    }
62}
63
64const BOM: u16 = 0xFEFF;
65const REVERSE_BOM: u16 = 0xFFFE;