1use crate::BinResult;
4#[cfg(not(feature = "std"))]
5use alloc::boxed::Box;
6pub use Endian::{Big as BE, Little as LE};
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum Endian {
11 Big,
13 Little,
15}
16
17impl Endian {
18 #[cfg(target_endian = "big")]
19 pub const NATIVE: Self = Endian::Big;
21 #[cfg(target_endian = "little")]
22 pub const NATIVE: Self = Endian::Little;
24
25 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 #[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;