wfdisc 0.1.1

Reader for CSS 3.0 / NNSA KB Core wfdisc seismological waveform descriptor files. Cross-validated against ObsPy.
Documentation
//! [`Samples`] — owned container for decoded waveform samples.
//!
//! One variant per native datatype, mirroring miniseed-rs' `Data` enum.

use std::io::Read;

use crate::datatype::DataType;
use crate::error::{Error, Result};
use crate::DEFAULT_MAX_SAMPLE_BYTES;

/// Decoded samples for one trace, typed by encoding.
///
/// `S3` is sign-extended into `i32` because Rust has no `i24`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Samples {
    /// 16-bit signed integers (from `s2` or `i2`).
    I16(Vec<i16>),
    /// 32-bit signed integers (from `s4`, `i4`, or sign-extended `s3`).
    I32(Vec<i32>),
    /// 32-bit IEEE-754 floats (from `t4` or `f4`).
    F32(Vec<f32>),
    /// 64-bit IEEE-754 floats (from `t8` or `f8`).
    F64(Vec<f64>),
}

impl Samples {
    /// Number of samples in this trace.
    pub fn len(&self) -> usize {
        match self {
            Samples::I16(v) => v.len(),
            Samples::I32(v) => v.len(),
            Samples::F32(v) => v.len(),
            Samples::F64(v) => v.len(),
        }
    }

    /// `true` if there are zero samples.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Discriminant string useful for logging/diagnostics.
    pub const fn kind(&self) -> &'static str {
        match self {
            Samples::I16(_) => "i16",
            Samples::I32(_) => "i32",
            Samples::F32(_) => "f32",
            Samples::F64(_) => "f64",
        }
    }

    /// Convert all samples to `f64` without applying any calibration.
    pub fn to_f64(&self) -> Vec<f64> {
        match self {
            Samples::I16(v) => v.iter().map(|&x| x as f64).collect(),
            Samples::I32(v) => v.iter().map(|&x| x as f64).collect(),
            Samples::F32(v) => v.iter().map(|&x| x as f64).collect(),
            Samples::F64(v) => v.clone(),
        }
    }

    /// Borrow as `&[i32]` if and only if the underlying datatype is `i32`.
    pub fn as_i32(&self) -> Option<&[i32]> {
        match self {
            Samples::I32(v) => Some(v),
            _ => None,
        }
    }

    /// Borrow as `&[i16]` if and only if the underlying datatype is `i16`.
    pub fn as_i16(&self) -> Option<&[i16]> {
        match self {
            Samples::I16(v) => Some(v),
            _ => None,
        }
    }

    /// Borrow as `&[f32]` if and only if the underlying datatype is `f32`.
    pub fn as_f32(&self) -> Option<&[f32]> {
        match self {
            Samples::F32(v) => Some(v),
            _ => None,
        }
    }

    /// Borrow as `&[f64]` if and only if the underlying datatype is `f64`.
    pub fn as_f64(&self) -> Option<&[f64]> {
        match self {
            Samples::F64(v) => Some(v),
            _ => None,
        }
    }

    /// Decode `nsamp` samples of `dtype` from `reader`.
    ///
    /// Implements the byte-level layout from CSS 3.0 / ObsPy: every native
    /// datatype is packed contiguously with no headers, padding, or
    /// framing.
    ///
    /// Returns [`Error::UnsupportedDatatype`] for ASCII or compressed
    /// encodings.
    ///
    /// Payload size is capped at [`DEFAULT_MAX_SAMPLE_BYTES`]; use
    /// [`Self::decode_with_max_bytes`] for a different limit.
    pub fn decode<R: Read>(reader: &mut R, dtype: DataType, nsamp: usize) -> Result<Self> {
        Self::decode_with_max_bytes(reader, dtype, nsamp, DEFAULT_MAX_SAMPLE_BYTES)
    }

    /// Like [`Self::decode`] with a caller-supplied byte cap.
    ///
    /// # Errors
    ///
    /// Returns [`Error::SampleSizeExceeded`] when `bytes_per_sample * nsamp`
    /// overflows `usize` or exceeds `max_bytes`.
    pub fn decode_with_max_bytes<R: Read>(
        reader: &mut R,
        dtype: DataType,
        nsamp: usize,
        max_bytes: usize,
    ) -> Result<Self> {
        let byte_len = sample_byte_len(dtype, nsamp, max_bytes)?;
        let mut buf = vec![0u8; byte_len];
        reader.read_exact(&mut buf)?;
        Ok(match dtype {
            DataType::S4 => Samples::I32(decode_chunks::<4, i32>(&buf, |c| {
                i32::from_be_bytes(*c)
            })),
            DataType::I4 => Samples::I32(decode_chunks::<4, i32>(&buf, |c| {
                i32::from_le_bytes(*c)
            })),
            DataType::S2 => Samples::I16(decode_chunks::<2, i16>(&buf, |c| {
                i16::from_be_bytes(*c)
            })),
            DataType::I2 => Samples::I16(decode_chunks::<2, i16>(&buf, |c| {
                i16::from_le_bytes(*c)
            })),
            DataType::S3 => Samples::I32(decode_s3(&buf, nsamp)),
            DataType::T4 => Samples::F32(decode_chunks::<4, f32>(&buf, |c| {
                f32::from_be_bytes(*c)
            })),
            DataType::F4 => Samples::F32(decode_chunks::<4, f32>(&buf, |c| {
                f32::from_le_bytes(*c)
            })),
            DataType::T8 => Samples::F64(decode_chunks::<8, f64>(&buf, |c| {
                f64::from_be_bytes(*c)
            })),
            DataType::F8 => Samples::F64(decode_chunks::<8, f64>(&buf, |c| {
                f64::from_le_bytes(*c)
            })),
            other => return Err(Error::UnsupportedDatatype(other)),
        })
    }
}

/// Bytes required to hold `nsamp` samples of `dtype`, bounded by `max_bytes`.
pub(crate) fn sample_byte_len(dtype: DataType, nsamp: usize, max_bytes: usize) -> Result<usize> {
    let bps = dtype
        .bytes_per_sample()
        .ok_or(Error::UnsupportedDatatype(dtype))?;
    let total = bps.checked_mul(nsamp).ok_or_else(|| {
        let requested = (bps as u128).saturating_mul(nsamp as u128);
        Error::SampleSizeExceeded {
            requested: requested.min(usize::MAX as u128) as usize,
            max: max_bytes,
        }
    })?;
    if total > max_bytes {
        return Err(Error::SampleSizeExceeded {
            requested: total,
            max: max_bytes,
        });
    }
    Ok(total)
}

fn decode_chunks<const N: usize, T>(buf: &[u8], mut conv: impl FnMut(&[u8; N]) -> T) -> Vec<T> {
    buf.chunks_exact(N)
        .map(|c| conv(<&[u8; N]>::try_from(c).expect("chunks_exact yields exact-size slices")))
        .collect()
}

fn decode_s3(buf: &[u8], nsamp: usize) -> Vec<i32> {
    let mut out = Vec::with_capacity(nsamp);
    for c in buf.chunks_exact(3) {
        let raw = (u32::from(c[0]) << 16) | (u32::from(c[1]) << 8) | u32::from(c[2]);
        let signed = if raw & 0x0080_0000 != 0 {
            (raw | 0xFF00_0000) as i32
        } else {
            raw as i32
        };
        out.push(signed);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn decode_s4_big_endian() {
        let bytes = [0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF];
        let s = Samples::decode(&mut Cursor::new(bytes), DataType::S4, 2).unwrap();
        assert_eq!(s.as_i32(), Some(&[1_i32, -1][..]));
    }

    #[test]
    fn decode_i4_little_endian() {
        let bytes = [0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF];
        let s = Samples::decode(&mut Cursor::new(bytes), DataType::I4, 2).unwrap();
        assert_eq!(s.as_i32(), Some(&[1_i32, -1][..]));
    }

    #[test]
    fn decode_s4_and_i4_agree_on_palindromic_values() {
        let bytes = [0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF];
        let be = Samples::decode(&mut Cursor::new(bytes), DataType::S4, 2).unwrap();
        let le = Samples::decode(&mut Cursor::new(bytes), DataType::I4, 2).unwrap();
        assert_eq!(be, le);
    }

    #[test]
    fn decode_s2_and_i2() {
        let be_bytes = [0x12, 0x34, 0x80, 0x00];
        let le_bytes = [0x34, 0x12, 0x00, 0x80];
        let be = Samples::decode(&mut Cursor::new(be_bytes), DataType::S2, 2).unwrap();
        let le = Samples::decode(&mut Cursor::new(le_bytes), DataType::I2, 2).unwrap();
        assert_eq!(be.as_i16(), Some(&[0x1234_i16, i16::MIN][..]));
        assert_eq!(le.as_i16(), Some(&[0x1234_i16, i16::MIN][..]));
    }

    #[test]
    fn decode_s3_sign_extends() {
        let bytes = [0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00];
        let s = Samples::decode(&mut Cursor::new(bytes), DataType::S3, 3).unwrap();
        assert_eq!(s.as_i32(), Some(&[1_i32, -1, -8_388_608][..]));
    }

    #[test]
    fn decode_t4_and_f4() {
        let v = 1.5_f32;
        let be = v.to_be_bytes();
        let le = v.to_le_bytes();
        let be_s = Samples::decode(&mut Cursor::new(be), DataType::T4, 1).unwrap();
        let le_s = Samples::decode(&mut Cursor::new(le), DataType::F4, 1).unwrap();
        assert_eq!(be_s.as_f32(), Some(&[1.5_f32][..]));
        assert_eq!(le_s.as_f32(), Some(&[1.5_f32][..]));
    }

    #[test]
    fn decode_t8_and_f8() {
        let v = std::f64::consts::PI;
        let be = v.to_be_bytes();
        let le = v.to_le_bytes();
        let be_s = Samples::decode(&mut Cursor::new(be), DataType::T8, 1).unwrap();
        let le_s = Samples::decode(&mut Cursor::new(le), DataType::F8, 1).unwrap();
        assert_eq!(be_s.as_f64(), Some(&[v][..]));
        assert_eq!(le_s.as_f64(), Some(&[v][..]));
    }

    #[test]
    fn unsupported_datatype_returns_error() {
        let err = Samples::decode(&mut Cursor::new([0u8; 8]), DataType::A0, 1).unwrap_err();
        assert!(matches!(err, Error::UnsupportedDatatype(DataType::A0)));
    }

    #[test]
    fn truncated_buffer_returns_io_error() {
        let err = Samples::decode(&mut Cursor::new([0u8; 3]), DataType::S4, 2).unwrap_err();
        assert!(matches!(err, Error::Io(_)));
    }

    #[test]
    fn huge_nsamp_returns_sample_size_exceeded_without_allocating() {
        let err = Samples::decode_with_max_bytes(
            &mut Cursor::new([]),
            DataType::S4,
            usize::MAX / 2,
            DEFAULT_MAX_SAMPLE_BYTES,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            Error::SampleSizeExceeded { requested, max }
            if max == DEFAULT_MAX_SAMPLE_BYTES && requested > max
        ));
    }

    #[test]
    fn checked_mul_overflow_returns_sample_size_exceeded() {
        let err = Samples::decode_with_max_bytes(
            &mut Cursor::new([]),
            DataType::S4,
            usize::MAX,
            usize::MAX,
        )
        .unwrap_err();
        assert!(matches!(err, Error::SampleSizeExceeded { .. }));
    }

    #[test]
    fn to_f64_handles_all_variants() {
        assert_eq!(Samples::I16(vec![1, -2]).to_f64(), vec![1.0, -2.0]);
        assert_eq!(Samples::I32(vec![1, -2]).to_f64(), vec![1.0, -2.0]);
        assert_eq!(Samples::F32(vec![0.5]).to_f64(), vec![0.5]);
        assert_eq!(Samples::F64(vec![0.25]).to_f64(), vec![0.25]);
    }

    #[test]
    fn len_and_kind() {
        let s = Samples::I32(vec![1, 2, 3]);
        assert_eq!(s.len(), 3);
        assert_eq!(s.kind(), "i32");
        assert!(!s.is_empty());
        assert!(Samples::I16(vec![]).is_empty());
    }
}