lib_endian/endian.rs
1/// An Enum for handling byte order.
2#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
3pub enum Endian {
4 Big,
5 Little,
6}
7
8#[cfg(target_endian = "big")]
9const NATIVE_ENDIAN: Endian = Endian::Big;
10#[cfg(target_endian = "little")]
11const NATIVE_ENDIAN: Endian = Endian::Little;
12
13impl Endian {
14 /// The byte order of the current target.
15 ///
16 /// # Examples
17 ///
18 /// ```
19 /// use lib_endian::Endian;
20 /// const NE: Endian = Endian::NATIVE;
21 /// ```
22 pub const NATIVE: Self = NATIVE_ENDIAN;
23
24 /// Tests for `self` and `other` values to be equal.
25 ///
26 /// # Examples
27 ///
28 /// ```
29 /// use lib_endian::Endian;
30 /// const BE: Endian = Endian::Big;
31 /// const IS_EQUAL: bool = BE.is(Endian::Big);
32 /// assert!(IS_EQUAL);
33 /// ```
34 ///
35 /// You can also use `==` out Constant Expressions:
36 ///
37 /// ```
38 /// use lib_endian::Endian;
39 /// let be = Endian::Big;
40 /// let is_equal = be == Endian::Big;
41 /// assert!(is_equal);
42 /// ```
43 pub const fn is(self, other: Self) -> bool {
44 self as u8 == other as u8
45 }
46
47 /// Returns a new `Endian` value which is different from `self`.
48 ///
49 /// # Examples
50 ///
51 /// ```
52 /// use lib_endian::Endian;
53 /// const BE: Endian = Endian::Little.reverse();
54 /// const IS_EQUAL: bool = BE.reverse().is(Endian::Little);
55 /// assert!(IS_EQUAL);
56 /// ```
57 ///
58 /// You can also use `!` out Constant Expressions:
59 ///
60 /// ```
61 /// use lib_endian::Endian;
62 /// let be = !Endian::Little;
63 /// let is_equal = !be == Endian::Little;
64 /// assert!(is_equal);
65 /// ```
66 pub const fn reverse(self) -> Self {
67 match self {
68 Self::Big => Self::Little,
69 Self::Little => Self::Big,
70 }
71 }
72
73 /// Returns `Endian::native()` if `reverse` is true,
74 /// otherwise returns `Endian::native().reverse()`.
75 ///
76 /// # Examples
77 ///
78 /// ```
79 /// use lib_endian::Endian;
80 ///
81 /// const REVERSE: bool = true;
82 ///
83 /// const NE_REV: Endian = Endian::native_or_reversed(REVERSE);
84 /// assert_eq!(NE_REV, Endian::NATIVE.reverse());
85 ///
86 /// const NE: Endian = Endian::native_or_reversed(!REVERSE);
87 /// assert_eq!(NE, Endian::NATIVE);
88 /// ```
89 pub const fn native_or_reversed(reverse: bool) -> Self {
90 if reverse {
91 Self::NATIVE.reverse()
92 } else {
93 Self::NATIVE
94 }
95 }
96}
97
98impl std::ops::Not for Endian {
99 type Output = Self;
100
101 fn not(self) -> Self::Output {
102 self.reverse()
103 }
104}