font-parse 0.1.1

SFNT/OTF/TrueType/WOFF/WOFF2 binary font parser: offset tables, character maps, glyph outlines, variable fonts
Documentation
//! WOFF 1.0 container: per-table zlib decoding and SFNT reconstruction.
//!
//! Structure (spec: WOFF File Format 1.0): 44-byte header, 20-byte table
//! directory entries (`tag, offset, compLength, origLength, origChecksum`),
//! then per-table data — zlib-compressed when `compLength < origLength`,
//! stored verbatim otherwise. Reconstruction assembles a standalone SFNT
//! with sorted directory entries, computed checksums, and the original
//! per-table checksums preserved from the container.

use crate::error::{ParseError, RawTag};
use crate::reader::{be_u16_at, be_u32_at};
use alloc::vec::Vec;

const TAG: RawTag = *b"wOFF";
const WOFF_SIGNATURE: u32 = 0x774F_4646; // 'wOFF'

/// Header size.
const HEADER: usize = 44;
/// Directory entry size.
const ENTRY: usize = 20;

/// Decode a WOFF 1.0 container into an owned, validated SFNT.
///
/// # Errors
/// [`ParseError::InvalidSfnt`] for a bad signature, header fields, table
/// bytes, or decompression mismatch; [`ParseError::TruncatedTable`] for
/// short structures.
pub fn decode(data: &[u8]) -> Result<crate::OwnedFont, ParseError> {
    if data.len() < HEADER {
        return Err(ParseError::TruncatedTable {
            tag: TAG,
            expected: HEADER,
            got: data.len(),
        });
    }
    if be_u32_at(data, 0, TAG)? != WOFF_SIGNATURE {
        return Err(ParseError::InvalidSfnt);
    }
    let flavor = be_u32_at(data, 4, TAG)?;
    let declared_len = be_u32_at(data, 8, TAG)?;
    let num_tables = usize::from(be_u16_at(data, 12, TAG)?);
    if num_tables == 0 {
        return Err(ParseError::InvalidSfnt);
    }
    let dir_len = HEADER + num_tables * ENTRY;
    if data.len() < dir_len {
        return Err(ParseError::TruncatedTable {
            tag: TAG,
            expected: dir_len,
            got: data.len(),
        });
    }
    // Container length must agree with the header (spec: no trailing junk).
    if usize::try_from(declared_len)
        .map(|l| l > data.len())
        .unwrap_or(true)
    {
        return Err(ParseError::InvalidSfnt);
    }
    let mut tables: Vec<(RawTag, Vec<u8>)> = Vec::with_capacity(num_tables);
    for i in 0..num_tables {
        let at = HEADER + i * ENTRY;
        let tag_bytes = crate::reader::slice_at(data, at, 4, TAG)?;
        let mut tag: [u8; 4] = *b"????";
        tag.copy_from_slice(tag_bytes);
        let offset = be_u32_at(data, at + 4, TAG)?;
        let comp_length = be_u32_at(data, at + 8, TAG)?;
        let orig_length = be_u32_at(data, at + 12, TAG)?;
        let comp_length = usize::try_from(comp_length).map_err(|_| ParseError::InvalidSfnt)?;
        let orig_length = usize::try_from(orig_length).map_err(|_| ParseError::InvalidSfnt)?;
        let offset = usize::try_from(offset).map_err(|_| ParseError::InvalidSfnt)?;
        let end = offset
            .checked_add(comp_length)
            .ok_or(ParseError::InvalidSfnt)?;
        if end > data.len() {
            return Err(ParseError::TruncatedTable {
                tag,
                expected: end,
                got: data.len(),
            });
        }
        if comp_length > orig_length {
            return Err(ParseError::InvalidSfnt);
        }
        let compressed = crate::reader::slice_at(data, offset, comp_length, TAG)?;
        let bytes = if comp_length < orig_length {
            // zlib per-table compression; the output must match origLength.
            let limit = orig_length.saturating_add(1);
            let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(compressed, limit)
                .map_err(|_| ParseError::InvalidSfnt)?;
            if out.len() != orig_length {
                return Err(ParseError::InvalidSfnt);
            }
            out
        } else {
            compressed.to_vec()
        };
        tables.push((tag, bytes));
    }
    let sfnt = crate::font::build_sfnt(flavor, &mut tables)?;
    crate::OwnedFont::from_sfnt(sfnt)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
    use super::decode;
    use crate::error::ParseError;
    use alloc::vec::Vec;

    // Test harness: assertions legitimately panic; the lib target stays
    // lint-clean. The fixture is generated by tests/fixtures/generate_fonts.py.

    const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/minimal.woff");

    #[test]
    fn decodes_reference_fixture() {
        let font = decode(FIXTURE).unwrap();
        let f = font.as_font_ref().unwrap();
        assert_eq!(f.head().unwrap().units_per_em().unwrap(), 1000);
        assert_eq!(f.num_glyphs(), 4);
        let cmap = f.cmap().unwrap();
        assert_eq!(cmap.codepoint('A').map(crate::GlyphId::to_u32), Some(1));
    }

    #[test]
    fn rejects_bad_containers() {
        // Not a WOFF signature (too short even to check).
        assert_eq!(
            decode(b"nope").unwrap_err(),
            ParseError::TruncatedTable {
                tag: *b"wOFF",
                expected: 44,
                got: 4
            }
        );
        // Truncated header.
        assert_eq!(
            decode(&FIXTURE[..40]).unwrap_err(),
            ParseError::TruncatedTable {
                tag: *b"wOFF",
                expected: 44,
                got: 40
            }
        );
        // Truncated mid-decode: valid signature, missing directory.
        let mut short: Vec<u8> = FIXTURE[..46].to_vec();
        short[12..14].copy_from_slice(&16u16.to_be_bytes()); // claim 16 tables
        assert!(matches!(
            decode(&short),
            Err(ParseError::TruncatedTable { .. })
        ));
        // Bad signature with sufficient length.
        let mut bad_sig: Vec<u8> = FIXTURE.to_vec();
        bad_sig[3] = b'X';
        assert_eq!(decode(&bad_sig).unwrap_err(), ParseError::InvalidSfnt);
    }
}