1use core::fmt;
2use core::str::FromStr;
3
4#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
8pub struct Fourcc(pub [u8; 4]);
9
10impl Fourcc {
11 pub const RIFF: Self = Self(*b"RIFF");
13 pub const RIFX: Self = Self(*b"RIFX");
15 pub const RF64: Self = Self(*b"RF64");
17 pub const BW64: Self = Self(*b"BW64");
19 pub const LIST: Self = Self(*b"LIST");
21 pub const DS64: Self = Self(*b"ds64");
23 pub const JUNK: Self = Self(*b"JUNK");
25
26 pub const fn new(bytes: [u8; 4]) -> Self {
28 Self(bytes)
29 }
30
31 pub const fn from_str(value: &str) -> Self {
36 let bytes = value.as_bytes();
37 if bytes.len() != 4 {
38 panic!("a Fourcc string must contain exactly four bytes");
39 }
40 Self([bytes[0], bytes[1], bytes[2], bytes[3]])
41 }
42
43 pub const fn as_bytes(&self) -> &[u8; 4] {
45 &self.0
46 }
47
48 pub fn as_str(&self) -> Option<&str> {
50 if self.0.iter().all(u8::is_ascii) {
51 core::str::from_utf8(&self.0).ok()
52 } else {
53 None
54 }
55 }
56}
57
58impl fmt::Display for Fourcc {
59 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60 for byte in self.0 {
61 if (0x20..=0x7e).contains(&byte) {
62 formatter.write_str(core::str::from_utf8(&[byte]).unwrap_or("?"))?;
63 } else {
64 write!(formatter, "\\x{byte:02x}")?;
65 }
66 }
67 Ok(())
68 }
69}
70
71impl fmt::Debug for Fourcc {
72 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73 formatter.write_str("\"")?;
74 fmt::Display::fmt(self, formatter)?;
75 formatter.write_str("\"")
76 }
77}
78
79impl From<[u8; 4]> for Fourcc {
80 fn from(bytes: [u8; 4]) -> Self {
81 Self(bytes)
82 }
83}
84
85impl TryFrom<&[u8]> for Fourcc {
86 type Error = FourccError;
87
88 fn try_from(bytes: &[u8]) -> core::result::Result<Self, Self::Error> {
89 if bytes.len() != 4 {
90 return Err(FourccError {
91 length: bytes.len(),
92 });
93 }
94 Ok(Self([bytes[0], bytes[1], bytes[2], bytes[3]]))
95 }
96}
97
98impl FromStr for Fourcc {
99 type Err = FourccError;
100
101 fn from_str(value: &str) -> core::result::Result<Self, Self::Err> {
102 Self::try_from(value.as_bytes())
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct FourccError {
109 length: usize,
110}
111
112impl FourccError {
113 pub const fn length(self) -> usize {
115 self.length
116 }
117}
118
119impl fmt::Display for FourccError {
120 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(
122 formatter,
123 "a Fourcc value must contain 4 bytes, received {}",
124 self.length
125 )
126 }
127}
128
129#[cfg(feature = "std")]
130impl std::error::Error for FourccError {}