Debian Codegraph @

src/target/endian.rs

raw
1 //! Endianness
2
3 use crate::error::Error;
4 use core::{fmt, str::FromStr};
5
6 #[cfg(feature = "serde")]
7 use serde::{de, de::Error as DeError, ser, Deserialize, Serialize};
8
9 /// `target_endian`: [Endianness](https://en.wikipedia.org/wiki/Endianness) of the target.
10 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
11 #[non_exhaustive]
12 pub enum Endian {
13 /// `big`
14 Big,
15
16 /// `little`
17 Little,
18 }
19
20 impl Endian {
21 /// String representing this `Endian` which matches `#[cfg(target_endian)]`
22 pub fn as_str(self) -> &'static str {
23 match self {
24 Endian::Big => "big",
25 Endian::Little => "little",
26 }
27 }
28 }
29
30 impl FromStr for Endian {
31 type Err = Error;
32
33 /// Create a new `Endian` from the given string
34 fn from_str(name: &str) -> Result<Self, Self::Err> {
35 let result = match name {
36 "big" => Endian::Big,
37 "little" => Endian::Little,
38 _ => return Err(Error),
39 };
40
41 Ok(result)
42 }
43 }
44
45 impl fmt::Display for Endian {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.write_str(self.as_str())
48 }
49 }
50
51 #[cfg(feature = "serde")]
52 impl Serialize for Endian {
53 fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
54 serializer.serialize_str(self.as_str())
55 }
56 }
57
58 #[cfg(all(feature = "serde", feature = "std"))]
59 impl<'de> Deserialize<'de> for Endian {
60 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
61 let string = std::string::String::deserialize(deserializer)?;
62 string.parse().map_err(|_| {
63 D::Error::custom(std::format!(
64 "Unrecognized value '{}' for target_endian",
65 string
66 ))
67 })
68 }
69 }