use types::{FixedSize, ReadScalar, Tag};
use crate::font_data::FontData;
pub trait FontRead<'a>: Sized {
fn read(data: FontData<'a>) -> Result<Self, ReadError>;
}
pub trait ReadArgs {
type Args: Copy;
}
pub trait FontReadWithArgs<'a>: Sized + ReadArgs {
fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, ReadError>;
}
impl<'a, T: FontRead<'a>> ReadArgs for T {
type Args = ();
}
impl<'a, T: FontRead<'a>> FontReadWithArgs<'a> for T {
fn read_with_args(data: FontData<'a>, _: &Self::Args) -> Result<Self, ReadError> {
Self::read(data)
}
}
pub trait Format<T> {
const FORMAT: T;
}
pub trait ComputeSize: ReadArgs {
fn compute_size(args: &Self::Args) -> usize;
}
pub trait VarSize {
type Size: ReadScalar + FixedSize + Into<u32>;
#[doc(hidden)]
fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
let asu32 = data.read_at::<Self::Size>(pos).ok()?.into();
Some(asu32 as usize + Self::Size::RAW_BYTE_LEN)
}
}
#[derive(Debug, Clone)]
pub enum ReadError {
OutOfBounds,
InvalidFormat(i64),
InvalidSfnt(u32),
InvalidTtc(Tag),
InvalidCollectionIndex(u32),
InvalidArrayLen,
ValidationError,
NullOffset,
TableIsMissing(Tag),
MetricIsMissing(Tag),
MalformedData(&'static str),
}
impl std::fmt::Display for ReadError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ReadError::OutOfBounds => write!(f, "An offset was out of bounds"),
ReadError::InvalidFormat(x) => write!(f, "Invalid format '{x}'"),
ReadError::InvalidSfnt(ver) => write!(f, "Invalid sfnt version 0x{ver:08X}"),
ReadError::InvalidTtc(tag) => write!(f, "Invalid ttc tag {tag}"),
ReadError::InvalidCollectionIndex(ix) => {
write!(f, "Invalid index {ix} for font collection")
}
ReadError::InvalidArrayLen => {
write!(f, "Specified array length not a multiple of item size")
}
ReadError::ValidationError => write!(f, "A validation error occured"),
ReadError::NullOffset => write!(f, "An offset was unexpectedly null"),
ReadError::TableIsMissing(tag) => write!(f, "the {tag} table is missing"),
ReadError::MetricIsMissing(tag) => write!(f, "the {tag} metric is missing"),
ReadError::MalformedData(msg) => write!(f, "Malformed data: '{msg}'"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ReadError {}