wfdisc 0.1.1

Reader for CSS 3.0 / NNSA KB Core wfdisc seismological waveform descriptor files. Cross-validated against ObsPy.
Documentation
//! Sample-encoding datatype codes used by the `datatype` column of a
//! wfdisc row.
//!
//! The set, names and binary semantics come from CSS 3.0 (Anderson et al.
//! 1990) and the ObsPy `DTYPE` table; see crate-level docs for the full
//! mapping.

use std::fmt;
use std::str::FromStr;

use crate::error::Error;

/// Two-character datatype code carried in column 14 of a wfdisc row.
///
/// Variants are grouped by *binary native* (decoded by this crate),
/// *ASCII* (recognised but not decoded) and *compressed* (recognised but
/// not decoded).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DataType {
    /// `s4` — big-endian signed 32-bit integer.
    S4,
    /// `s2` — big-endian signed 16-bit integer.
    S2,
    /// `s3` — big-endian signed 24-bit integer (3 bytes packed, sign-extended to `i32`).
    S3,
    /// `i4` — little-endian signed 32-bit integer.
    I4,
    /// `i2` — little-endian signed 16-bit integer.
    I2,
    /// `t4` — big-endian IEEE-754 32-bit float.
    T4,
    /// `t8` — big-endian IEEE-754 64-bit float.
    T8,
    /// `f4` — little-endian IEEE-754 32-bit float.
    F4,
    /// `f8` — little-endian IEEE-754 64-bit float.
    F8,
    /// `a0` — ASCII float, 15-character fields, no separator. Recognised but unsupported.
    A0,
    /// `a#` — ASCII float, 15-character fields, hash-prefixed records. Recognised but unsupported.
    AHash,
    /// `b0` — ASCII double, 24-character fields. Recognised but unsupported.
    B0,
    /// `b#` — ASCII double, hash-prefixed. Recognised but unsupported.
    BHash,
    /// `c0` — ASCII int, 12-character fields. Recognised but unsupported.
    C0,
    /// `c#` — ASCII int, hash-prefixed. Recognised but unsupported.
    CHash,
    /// `e1` — CSS-style compressed integer. Recognised but unsupported.
    E1,
    /// `g2` — Gulf compressed. Recognised but unsupported.
    G2,
    /// `cd` — Canadian compressed. Recognised but unsupported.
    Cd,
    /// `sc` — Steim-compressed (in the `sc` flavour). Recognised but unsupported.
    Sc,
}

impl DataType {
    /// Returns the two-character ASCII code as it appears in the file.
    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",
        }
    }

    /// Number of raw bytes occupied by a single sample of this datatype.
    ///
    /// Returns `None` for variants without a fixed binary footprint
    /// (ASCII and compressed encodings).
    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,
        })
    }

    /// `true` if [`crate::Samples`] can be produced from this datatype today.
    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());
    }
}