mf4-rs 4.2.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
Documentation
// blocks/common.rs
use byteorder::{ByteOrder, LittleEndian};

use crate::blocks::text_block::TextBlock;
use crate::blocks::metadata_block::MetadataBlock;
use crate::error::MdfError;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BlockHeader {
    pub id: String,       // 4-byte string
    pub reserved0: u32,   // 4 bytes
    pub block_len: u64,   // 8 bytes
    pub links_nr: u64,    // 8 bytes
}

impl Default for BlockHeader {
    /// Returns a BlockHeader with id 'UNSET' and block_len 0 as a placeholder.
    /// This is not a valid MDF block header and should be replaced before writing.
    fn default() -> Self {
        BlockHeader {
            id: String::from("UNSET"), // Placeholder, must be set by user
            reserved0: 0,
            block_len: 0, // Placeholder, must be set by user
            links_nr: 0,
        }
    }
}


impl BlockHeader {
    /// Serializes the BlockHeader to bytes according to MDF 4.1 specification.
    ///
    /// The BlockHeader is always 24 bytes and consists of:
    /// - id: 4 bytes (ASCII characters, must be exactly 4 bytes)
    /// - reserved0: 4 bytes (always 0)
    /// - block_len: 8 bytes (total length of the block including this header)
    /// - links_nr: 8 bytes (number of links in this block)
    ///
    /// # Returns
    /// - `Ok(Vec<u8>)` containing the serialized block header
    /// - `Err(MdfError)` if serialization fails
    pub fn to_bytes(&self) -> Result<Vec<u8>, MdfError> {
        // Create a buffer with exactly 24 bytes capacity
        let mut buffer = Vec::with_capacity(24);
        
        // 1. Write the ID field (4 bytes)
        // The ID must be exactly 4 bytes - truncate or pad as needed
        let id_bytes = self.id.as_bytes();
        let mut id_field = [0u8; 4]; // Initialize with zeros for padding
        
        // Copy either all bytes or first 4 bytes of ID
        let id_len = std::cmp::min(id_bytes.len(), 4);
        id_field[..id_len].copy_from_slice(&id_bytes[..id_len]);
        buffer.extend_from_slice(&id_field);
        
        // 2. Write reserved0 field (4 bytes)
        buffer.extend_from_slice(&self.reserved0.to_le_bytes());
        
        // 3. Write block_len field (8 bytes)
        buffer.extend_from_slice(&self.block_len.to_le_bytes());
        
        // 4. Write links_nr field (8 bytes)
        buffer.extend_from_slice(&self.links_nr.to_le_bytes());
        
        // Verify buffer is exactly 24 bytes
        if buffer.len() != 24 {
            return Err(MdfError::BlockSerializationError(
                format!("BlockHeader must be exactly 24 bytes, got {}", buffer.len())
            ));
        }
        
        Ok(buffer)
    }

    /// Parse a block header from the first 24 bytes of `bytes`.
    ///
    /// # Arguments
    /// * `bytes` - Slice containing at least 24 bytes from the MDF file.
    ///
    /// # Returns
    /// A [`BlockHeader`] on success or [`MdfError::TooShortBuffer`] when the
    /// slice is smaller than 24 bytes.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
        let expected_bytes = 24;
        if bytes.len() < expected_bytes {
            return Err(MdfError::TooShortBuffer {
                actual:   bytes.len(),
                expected: expected_bytes,
                file:     file!(),
                line:     line!(),
            });
        }
        Ok(Self {
            id: String::from_utf8_lossy(&bytes[0..4]).to_string(),
            reserved0: LittleEndian::read_u32(&bytes[4..8]),
            block_len: LittleEndian::read_u64(&bytes[8..16]),
            links_nr: LittleEndian::read_u64(&bytes[16..24]),
        })
    }
}

pub trait BlockParse<'a>: Sized {
    const ID: &'static str;

    fn parse_header(bytes: &[u8]) -> Result<BlockHeader, MdfError> {
        // `BlockHeader::from_bytes` performs its own length check, so pass the
        // slice through unsliced to avoid panicking on buffers < 24 bytes.
        let header = BlockHeader::from_bytes(bytes)?;
        if header.id != Self::ID {
            return Err(MdfError::BlockIDError {
                actual: header.id.clone(),
                expected: Self::ID.to_string(),
            });
        }
        Ok(header)
    }

    fn from_bytes(bytes: &'a [u8]) -> Result<Self, MdfError>;
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum DataType {
    UnsignedIntegerLE,
    UnsignedIntegerBE,
    SignedIntegerLE,
    SignedIntegerBE,
    FloatLE,
    FloatBE,
    StringLatin1,
    StringUtf8,
    StringUtf16LE,
    StringUtf16BE,
    ByteArray,
    MimeSample,
    MimeStream,
    CanOpenDate,
    CanOpenTime,
    ComplexLE,
    ComplexBE,
    Unknown(()),
}

impl DataType {
    /// The canonical name of this data type, shared by every language binding
    /// (`ChannelInfo.data_type`, the writer's `add_channel`): the variant name,
    /// e.g. `"FloatLE"`, `"UnsignedIntegerLE"`, `"StringUtf8"`.
    pub fn name(&self) -> &'static str {
        match self {
            DataType::UnsignedIntegerLE => "UnsignedIntegerLE",
            DataType::UnsignedIntegerBE => "UnsignedIntegerBE",
            DataType::SignedIntegerLE => "SignedIntegerLE",
            DataType::SignedIntegerBE => "SignedIntegerBE",
            DataType::FloatLE => "FloatLE",
            DataType::FloatBE => "FloatBE",
            DataType::StringLatin1 => "StringLatin1",
            DataType::StringUtf8 => "StringUtf8",
            DataType::StringUtf16LE => "StringUtf16LE",
            DataType::StringUtf16BE => "StringUtf16BE",
            DataType::ByteArray => "ByteArray",
            DataType::MimeSample => "MimeSample",
            DataType::MimeStream => "MimeStream",
            DataType::CanOpenDate => "CanOpenDate",
            DataType::CanOpenTime => "CanOpenTime",
            DataType::ComplexLE => "ComplexLE",
            DataType::ComplexBE => "ComplexBE",
            DataType::Unknown(_) => "Unknown",
        }
    }

    /// Parse a canonical data-type name (the inverse of [`DataType::name`]).
    pub fn from_name(name: &str) -> Result<DataType, crate::error::MdfError> {
        Ok(match name {
            "UnsignedIntegerLE" => DataType::UnsignedIntegerLE,
            "UnsignedIntegerBE" => DataType::UnsignedIntegerBE,
            "SignedIntegerLE" => DataType::SignedIntegerLE,
            "SignedIntegerBE" => DataType::SignedIntegerBE,
            "FloatLE" => DataType::FloatLE,
            "FloatBE" => DataType::FloatBE,
            "StringLatin1" => DataType::StringLatin1,
            "StringUtf8" => DataType::StringUtf8,
            "StringUtf16LE" => DataType::StringUtf16LE,
            "StringUtf16BE" => DataType::StringUtf16BE,
            "ByteArray" => DataType::ByteArray,
            other => {
                return Err(crate::error::MdfError::InvalidArgument(format!(
                    "unknown data type '{}'. Expected one of: FloatLE, FloatBE, \
                     UnsignedIntegerLE, UnsignedIntegerBE, SignedIntegerLE, \
                     SignedIntegerBE, StringUtf8, StringLatin1, StringUtf16LE, \
                     StringUtf16BE, ByteArray",
                    other
                )));
            }
        })
    }

    /// `true` for the text data types.
    pub fn is_string(&self) -> bool {
        matches!(
            self,
            DataType::StringLatin1
                | DataType::StringUtf8
                | DataType::StringUtf16LE
                | DataType::StringUtf16BE
        )
    }

    /// Converts the DataType enum value to its corresponding u8 representation
    /// according to the MDF 4.1 specification.
    /// 
    /// # Returns
    /// The u8 value corresponding to this DataType
    /// 
    /// # Note
    /// For ComplexLE, ComplexBE, and Unknown variants, we use values that match
    /// the MDF 4.1 specification (15, 16) or a default (0) for Unknown.
    pub fn to_u8(&self) -> u8 {
        match self {
            DataType::UnsignedIntegerLE => 0,
            DataType::UnsignedIntegerBE => 1,
            DataType::SignedIntegerLE => 2,
            DataType::SignedIntegerBE => 3,
            DataType::FloatLE => 4,
            DataType::FloatBE => 5,
            DataType::StringLatin1 => 6,
            DataType::StringUtf8 => 7,
            DataType::StringUtf16LE => 8,
            DataType::StringUtf16BE => 9,
            DataType::ByteArray => 10,
            DataType::MimeSample => 11,
            DataType::MimeStream => 12,
            DataType::CanOpenDate => 13,
            DataType::CanOpenTime => 14,
            DataType::ComplexLE => 15,      // Complex numbers, little-endian
            DataType::ComplexBE => 16,      // Complex numbers, big-endian
            DataType::Unknown(_) => 0,      // Default to 0 for unknown types
        }
    }
    
    /// Convert a numeric representation to the corresponding `DataType`.
    /// Values outside the known range yield `DataType::Unknown`.
    pub fn from_u8(value: u8) -> Self {
        match value {
            0 => DataType::UnsignedIntegerLE,
            1 => DataType::UnsignedIntegerBE,
            2 => DataType::SignedIntegerLE,
            3 => DataType::SignedIntegerBE,
            4 => DataType::FloatLE,
            5 => DataType::FloatBE,
            6 => DataType::StringLatin1,
            7 => DataType::StringUtf8,
            8 => DataType::StringUtf16LE,
            9 => DataType::StringUtf16BE,
            10 => DataType::ByteArray,
            11 => DataType::MimeSample,
            12 => DataType::MimeStream,
            13 => DataType::CanOpenDate,
            14 => DataType::CanOpenTime,
            15 => DataType::ComplexLE,
            16 => DataType::ComplexBE,
            _ => DataType::Unknown(()),
        }
    }

    /// Returns a typical bit width for this data type.
    /// This is used when creating channels without an explicit bit count.
    pub fn default_bits(&self) -> u32 {
        match self {
            DataType::UnsignedIntegerLE
            | DataType::UnsignedIntegerBE
            | DataType::SignedIntegerLE
            | DataType::SignedIntegerBE => 32,
            DataType::FloatLE | DataType::FloatBE => 32,
            DataType::StringLatin1
            | DataType::StringUtf8
            | DataType::StringUtf16LE
            | DataType::StringUtf16BE
            | DataType::ByteArray
            | DataType::MimeSample
            | DataType::MimeStream => 8,
            DataType::CanOpenDate | DataType::CanOpenTime => 64,
            DataType::ComplexLE | DataType::ComplexBE => 64,
            DataType::Unknown(_) => 8,
        }
    }
}

/// Read a text or metadata block at `address` and return its contents.
///
/// # Arguments
/// * `mmap` - The full memory mapped MDF file.
/// * `address` - Offset of the target block; use `0` for no block.
///
/// # Returns
/// The block's string contents if present or `Ok(None)` if `address` is zero or
/// the block type is not text or metadata.
pub fn read_string_block(mmap: &[u8], address: u64) -> Result<Option<String>, MdfError> {
    if address == 0 {
        return Ok(None);
    }

    let offset = address as usize;
    if offset.checked_add(24).is_none_or(|end| end > mmap.len()) {
        return Err(MdfError::TooShortBuffer {
            actual:   mmap.len(),
            expected: offset.saturating_add(24),
            file:     file!(),
            line:     line!(),
        });
    }
    let header = BlockHeader::from_bytes(&mmap[offset..offset + 24])?;

    match header.id.as_str() {
        "##TX" => Ok(Some(TextBlock::from_bytes(&mmap[offset..])?.text)),
        "##MD" => Ok(Some(MetadataBlock::from_bytes(&mmap[offset..])?.xml)),
        _ => Ok(None),
    }
}

/// Read a text or metadata block via a [`ByteRangeReader`].
///
/// Mirrors [`read_string_block`] but fetches the block bytes through a range
/// reader instead of a memory-mapped slice. Returns `Ok(None)` for `address ==
/// 0` or non-text block IDs.
///
/// A name/unit/comment text block is a *leaf*: the walk does not follow a link
/// out of it, so reads go through
/// [`read_range_optional`](crate::index::ByteRangeReader::read_range_optional).
/// For on-demand readers that is identical to `read_range`; for an incremental
/// gap-gathering reader it lets the walk record a not-yet-fetched text block and
/// carry on (returning `Ok(None)` here) instead of aborting on the first miss.
pub fn read_string_block_via_reader<R>(
    reader: &mut R,
    address: u64,
) -> Result<Option<String>, MdfError>
where
    R: crate::index::ByteRangeReader<Error = MdfError>,
{
    if address == 0 {
        return Ok(None);
    }

    let header_bytes = match reader.read_range_optional(address, 24)? {
        Some(bytes) => bytes,
        None => return Ok(None),
    };
    let header = BlockHeader::from_bytes(&header_bytes)?;

    match header.id.as_str() {
        "##TX" => match reader.read_range_optional(address, header.block_len)? {
            Some(bytes) => Ok(Some(TextBlock::from_bytes(&bytes)?.text)),
            None => Ok(None),
        },
        "##MD" => match reader.read_range_optional(address, header.block_len)? {
            Some(bytes) => Ok(Some(MetadataBlock::from_bytes(&bytes)?.xml)),
            None => Ok(None),
        },
        _ => Ok(None),
    }
}