Skip to main content

riff_chunks/
fourcc.rs

1use core::fmt;
2use core::str::FromStr;
3
4/// A four-byte chunk identifier.
5///
6/// RIFF identifiers are often ASCII, but readers accept every byte value.
7#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
8pub struct Fourcc(pub [u8; 4]);
9
10impl Fourcc {
11    /// The little-endian RIFF form identifier.
12    pub const RIFF: Self = Self(*b"RIFF");
13    /// The big-endian RIFX form identifier.
14    pub const RIFX: Self = Self(*b"RIFX");
15    /// The RF64 form identifier.
16    pub const RF64: Self = Self(*b"RF64");
17    /// The BW64 form identifier.
18    pub const BW64: Self = Self(*b"BW64");
19    /// The list chunk identifier.
20    pub const LIST: Self = Self(*b"LIST");
21    /// The RF64 size-table chunk identifier.
22    pub const DS64: Self = Self(*b"ds64");
23    /// The reserved filler chunk identifier.
24    pub const JUNK: Self = Self(*b"JUNK");
25
26    /// Creates an identifier from four bytes.
27    pub const fn new(bytes: [u8; 4]) -> Self {
28        Self(bytes)
29    }
30
31    /// Creates an identifier from a four-byte string.
32    ///
33    /// This function is intended for constants and panics when `value` is not
34    /// exactly four bytes. Use the [`FromStr`] implementation for runtime text.
35    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    /// Returns the four stored bytes.
44    pub const fn as_bytes(&self) -> &[u8; 4] {
45        &self.0
46    }
47
48    /// Returns the identifier as text when every byte is ASCII.
49    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/// Reports the byte length of an invalid textual or slice identifier.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct FourccError {
109    length: usize,
110}
111
112impl FourccError {
113    /// Returns the received byte length.
114    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 {}