use std::fmt;
use std::str::FromStr;
use crate::error::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DataType {
S4,
S2,
S3,
I4,
I2,
T4,
T8,
F4,
F8,
A0,
AHash,
B0,
BHash,
C0,
CHash,
E1,
G2,
Cd,
Sc,
}
impl DataType {
pub const fn code(self) -> &'static str {
match self {
DataType::S4 => "s4",
DataType::S2 => "s2",
DataType::S3 => "s3",
DataType::I4 => "i4",
DataType::I2 => "i2",
DataType::T4 => "t4",
DataType::T8 => "t8",
DataType::F4 => "f4",
DataType::F8 => "f8",
DataType::A0 => "a0",
DataType::AHash => "a#",
DataType::B0 => "b0",
DataType::BHash => "b#",
DataType::C0 => "c0",
DataType::CHash => "c#",
DataType::E1 => "e1",
DataType::G2 => "g2",
DataType::Cd => "cd",
DataType::Sc => "sc",
}
}
pub const fn bytes_per_sample(self) -> Option<usize> {
Some(match self {
DataType::S4 | DataType::I4 | DataType::T4 | DataType::F4 => 4,
DataType::S2 | DataType::I2 => 2,
DataType::S3 => 3,
DataType::T8 | DataType::F8 => 8,
_ => return None,
})
}
pub const fn is_supported(self) -> bool {
self.bytes_per_sample().is_some()
}
}
impl fmt::Display for DataType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.code())
}
}
impl FromStr for DataType {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let trimmed = s.trim();
Ok(match trimmed {
"s4" => DataType::S4,
"s2" => DataType::S2,
"s3" => DataType::S3,
"i4" => DataType::I4,
"i2" => DataType::I2,
"t4" => DataType::T4,
"t8" => DataType::T8,
"f4" => DataType::F4,
"f8" => DataType::F8,
"a0" => DataType::A0,
"a#" => DataType::AHash,
"b0" => DataType::B0,
"b#" => DataType::BHash,
"c0" => DataType::C0,
"c#" => DataType::CHash,
"e1" => DataType::E1,
"g2" => DataType::G2,
"cd" => DataType::Cd,
"sc" => DataType::Sc,
other => {
return Err(Error::UnknownDatatype {
code: other.to_string(),
});
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_all_known_codes() {
for code in [
"s4", "s2", "s3", "i4", "i2", "t4", "t8", "f4", "f8", "a0", "a#", "b0", "b#", "c0",
"c#", "e1", "g2", "cd", "sc",
] {
let dt: DataType = code.parse().unwrap();
assert_eq!(dt.code(), code);
}
}
#[test]
fn parses_with_surrounding_whitespace() {
assert_eq!(DataType::S4, " s4 ".parse().unwrap());
}
#[test]
fn rejects_unknown_code() {
let err = "xx".parse::<DataType>().unwrap_err();
assert!(matches!(err, Error::UnknownDatatype { .. }));
}
#[test]
fn bytes_per_sample_matches_spec() {
assert_eq!(DataType::S4.bytes_per_sample(), Some(4));
assert_eq!(DataType::S2.bytes_per_sample(), Some(2));
assert_eq!(DataType::S3.bytes_per_sample(), Some(3));
assert_eq!(DataType::T8.bytes_per_sample(), Some(8));
assert_eq!(DataType::A0.bytes_per_sample(), None);
assert_eq!(DataType::E1.bytes_per_sample(), None);
}
#[test]
fn is_supported_only_for_native_binary() {
assert!(DataType::S4.is_supported());
assert!(!DataType::A0.is_supported());
assert!(!DataType::E1.is_supported());
}
}