use std::error::Error;
use flate2::{Decompress, FlushDecompress, Status};
use crate::text::glyph::FontData;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub(crate) enum WoffError {
#[error("invalid WOFF file")]
InvalidWoff,
#[error("invalid WOFF2 file")]
InvalidWoff2,
}
#[cfg(test)]
#[must_use]
pub(crate) fn is_woff(data: &[u8]) -> bool {
matches!(data.get(..4), Some(b"wOFF" | b"wOF2"))
}
pub(crate) fn to_sfnt(data: FontData) -> Result<FontData, WoffError> {
let decoded = match data.as_bytes().get(..4) {
Some(b"wOFF") => decode_woff(data.as_bytes())?,
Some(b"wOF2") => decode_woff2(data.as_bytes())?,
_ => return Ok(data),
};
Ok(FontData::from(decoded).with_face_index(data.face_index()))
}
pub(crate) fn decode_woff2(data: &[u8]) -> Result<Vec<u8>, WoffError> {
wuff::decompress_woff2(data).map_err(|_| WoffError::InvalidWoff2)
}
pub(crate) fn decode_woff(data: &[u8]) -> Result<Vec<u8>, WoffError> {
if !tables_are_disjoint(data) {
return Err(WoffError::InvalidWoff);
}
wuff::decompress_woff1_with_custom_z(data, &mut inflate).map_err(|_| WoffError::InvalidWoff)
}
fn tables_are_disjoint(data: &[u8]) -> bool {
let read_u32 = |at: usize| Some(u64::from(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?)));
let Some(&[high, low]) = data.get(12..14) else {
return false;
};
let ranges: Option<Vec<(u64, u64)>> = (0..usize::from(u16::from_be_bytes([high, low])))
.map(|i| {
let entry = 44 + i * 20;
let offset = read_u32(entry + 4)?;
Some((offset, offset + read_u32(entry + 8)?))
})
.collect();
let Some(mut ranges) = ranges else {
return false;
};
ranges.sort_unstable();
ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0)
}
const MAX_DEFLATE_RATIO: usize = 1032;
fn inflate(compressed: &[u8], length: usize) -> Result<Vec<u8>, Box<dyn Error>> {
if length > compressed.len().saturating_mul(MAX_DEFLATE_RATIO) {
return Err("table longer than its zlib stream can inflate to".into());
}
let mut table = Vec::new();
table.try_reserve_exact(length)?;
let mut inflater = Decompress::new(true);
match inflater.decompress_vec(compressed, &mut table, FlushDecompress::Finish)? {
Status::StreamEnd if table.len() == length => Ok(table),
_ => Err("zlib stream not of the table's length".into()),
}
}