use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FourCc(pub [u8; 4]);
impl FourCc {
pub const fn as_bytes(&self) -> &[u8; 4] {
&self.0
}
}
impl From<[u8; 4]> for FourCc {
fn from(bytes: [u8; 4]) -> Self {
Self(bytes)
}
}
impl fmt::Display for FourCc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.iter().all(|b| b.is_ascii_graphic() || *b == b' ') {
for b in &self.0 {
write!(f, "{}", *b as char)?;
}
Ok(())
} else {
write!(
f,
"0x{:02x}{:02x}{:02x}{:02x}",
self.0[0], self.0[1], self.0[2], self.0[3]
)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CodecId {
WaveFormatTag(u16),
FourCc(FourCc),
Name(String),
}
impl fmt::Display for CodecId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::WaveFormatTag(tag) => write!(f, "WAVE format tag 0x{tag:04x}"),
Self::FourCc(code) => write!(f, "four-CC '{code}'"),
Self::Name(name) => write!(f, "codec '{name}'"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn printable_four_cc_displays_as_text() {
assert_eq!(FourCc(*b"RIFF").to_string(), "RIFF");
assert_eq!(FourCc(*b"fmt ").to_string(), "fmt ");
}
#[test]
fn unprintable_four_cc_displays_as_hex() {
assert_eq!(FourCc([0x00, 0x01, 0xff, 0x7f]).to_string(), "0x0001ff7f");
}
#[test]
fn codec_id_names_the_specific_identity() {
assert_eq!(
CodecId::WaveFormatTag(7).to_string(),
"WAVE format tag 0x0007"
);
assert_eq!(
CodecId::FourCc(FourCc(*b"alaw")).to_string(),
"four-CC 'alaw'"
);
assert_eq!(
CodecId::Name("opus".to_string()).to_string(),
"codec 'opus'"
);
}
#[test]
fn four_cc_exposes_the_bytes_it_was_built_from() {
let tag = FourCc::from(*b"fLaC");
assert_eq!(tag.as_bytes(), b"fLaC");
}
}