Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom types for the meta table #1244

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions font-test-data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,25 @@ pub mod colrv1_json {
pub mod ttc {
pub static TTC: &[u8] = include_bytes!("../test_data/ttc/TTC.ttc");
}

pub mod meta {
// the table from the binary for 'Sankofa'
#[rustfmt::skip]
pub static SIMPLE_META_TABLE: &[u8] = &[
0x00, 0x00, 0x00, 0x01, // version 1
0x00, 0x00, 0x00, 0x00, // flags 0
0x00, 0x00, 0x00, 0x28, // reserved (?)
0x00, 0x00, 0x00, 0x02, // data_maps_count 2
0x64, 0x6c, 0x6e, 0x67, // tag: dlng
0x00, 0x00, 0x00, 0x28, // data offset
0x00, 0x00, 0x00, 0x0d, // data length
0x73, 0x6c, 0x6e, 0x67, // tag: slng
0x00, 0x00, 0x00, 0x35, // data offset
0x00, 0x00, 0x00, 0x04, // length
0x65, 0x6e, 0x2d, 0x6c,
0x61, 0x74, 0x6e, 0x2c,
0x20, 0x6c, 0x61, 0x74,
0x6e, 0x6c, 0x61, 0x74,
0x6e, 0x00, 0x00, 0x00,
];
}
178 changes: 178 additions & 0 deletions read-fonts/generated/generated_meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// THIS FILE IS AUTOGENERATED.
// Any changes to this file will be overwritten.
// For more information about how codegen works, see font-codegen/README.md

#[allow(unused_imports)]
use crate::codegen_prelude::*;

/// [`meta`](https://docs.microsoft.com/en-us/typography/opentype/spec/meta)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MetaMarker {
data_maps_byte_len: usize,
}

impl MetaMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}

pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}

pub fn reserved_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}

pub fn data_maps_count_byte_range(&self) -> Range<usize> {
let start = self.reserved_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}

pub fn data_maps_byte_range(&self) -> Range<usize> {
let start = self.data_maps_count_byte_range().end;
start..start + self.data_maps_byte_len
}
}

impl TopLevelTable for Meta<'_> {
/// `meta`
const TAG: Tag = Tag::new(b"meta");
}

impl<'a> FontRead<'a> for Meta<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u32>();
let data_maps_count: u32 = cursor.read()?;
let data_maps_byte_len = (data_maps_count as usize)
.checked_mul(DataMapRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(data_maps_byte_len);
cursor.finish(MetaMarker { data_maps_byte_len })
}
}

/// [`meta`](https://docs.microsoft.com/en-us/typography/opentype/spec/meta)
pub type Meta<'a> = TableRef<'a, MetaMarker>;

impl<'a> Meta<'a> {
/// Version number of the metadata table — set to 1.
pub fn version(&self) -> u32 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}

/// Flags — currently unused; set to 0.
pub fn flags(&self) -> u32 {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}

/// The number of data maps in the table.
pub fn data_maps_count(&self) -> u32 {
let range = self.shape.data_maps_count_byte_range();
self.data.read_at(range.start).unwrap()
}

/// Array of data map records.
pub fn data_maps(&self) -> &'a [DataMapRecord] {
let range = self.shape.data_maps_byte_range();
self.data.read_array(range).unwrap()
}
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Meta<'a> {
fn type_name(&self) -> &str {
"Meta"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("flags", self.flags())),
2usize => Some(Field::new("data_maps_count", self.data_maps_count())),
3usize => Some(Field::new(
"data_maps",
traversal::FieldType::array_of_records(
stringify!(DataMapRecord),
self.data_maps(),
self.offset_data(),
),
)),
_ => None,
}
}
}

#[cfg(feature = "experimental_traverse")]
impl<'a> std::fmt::Debug for Meta<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}

/// <https://learn.microsoft.com/en-us/typography/opentype/spec/meta#table-formats>
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct DataMapRecord {
/// A tag indicating the type of metadata.
pub tag: BigEndian<Tag>,
/// Offset in bytes from the beginning of the metadata table to the data for this tag.
pub data_offset: BigEndian<Offset32>,
/// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
pub data_length: BigEndian<u32>,
}

impl DataMapRecord {
/// A tag indicating the type of metadata.
pub fn tag(&self) -> Tag {
self.tag.get()
}

/// Offset in bytes from the beginning of the metadata table to the data for this tag.
pub fn data_offset(&self) -> Offset32 {
self.data_offset.get()
}

/// Offset in bytes from the beginning of the metadata table to the data for this tag.
///
/// The `data` argument should be retrieved from the parent table
/// By calling its `offset_data` method.
pub fn data<'a>(&self, data: FontData<'a>) -> Result<Metadata<'a>, ReadError> {
let args = (self.tag(), self.data_length());
self.data_offset().resolve_with_args(data, &args)
}

/// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
pub fn data_length(&self) -> u32 {
self.data_length.get()
}
}

impl FixedSize for DataMapRecord {
const RAW_BYTE_LEN: usize = Tag::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for DataMapRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "DataMapRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("tag", self.tag())),
1usize => Some(Field::new("data_offset", traversal::FieldType::Unknown)),
2usize => Some(Field::new("data_length", self.data_length())),
_ => None,
}),
data,
}
}
}
3 changes: 2 additions & 1 deletion read-fonts/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ impl<'a, T: FontRead<'a> + VarSize> VarLenArray<'a, T> {
}

let item_len = T::read_len_at(data, 0)?;
let next = T::read(data);
let item_data = data.slice(..item_len)?;
let next = T::read(item_data);
data = data.split_off(item_len)?;
Some(next)
})
Expand Down
4 changes: 4 additions & 0 deletions read-fonts/src/table_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@ pub trait TableProvider<'a> {
self.expect_data_for_tag(tables::ift::IFTX_TAG)
.and_then(FontRead::read)
}

fn meta(&self) -> Result<tables::meta::Meta<'a>, ReadError> {
self.expect_table()
}
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions read-fonts/src/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub mod layout;
pub mod loca;
pub mod ltag;
pub mod maxp;
pub mod meta;
pub mod mvar;
pub mod name;
pub mod os2;
Expand Down
116 changes: 116 additions & 0 deletions read-fonts/src/tables/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//! The [meta (Metadata)](https://docs.microsoft.com/en-us/typography/opentype/spec/meta) table

include!("../../generated/generated_meta.rs");

pub const DLNG: Tag = Tag::new(b"dlng");
pub const SLNG: Tag = Tag::new(b"slng");

/// Data stored in the 'meta' table.
pub enum Metadata<'a> {
/// Used for the 'dlng' and 'slng' metadata
ScriptLangTags(VarLenArray<'a, ScriptLangTag<'a>>),
/// Other metadata, which may exist in certain apple fonts
Other(&'a [u8]),
}

impl ReadArgs for Metadata<'_> {
type Args = (Tag, u32);
}

impl<'a> FontReadWithArgs<'a> for Metadata<'a> {
fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, ReadError> {
let (tag, len) = *args;
let data = data.slice(0..len as usize).ok_or(ReadError::OutOfBounds)?;
if [DLNG, SLNG].contains(&tag) {
VarLenArray::read(data).map(Metadata::ScriptLangTags)
} else {
Ok(Metadata::Other(data.as_bytes()))
}
}
}

#[derive(Clone, Debug)]
pub struct ScriptLangTag<'a>(&'a str);

impl<'a> ScriptLangTag<'a> {
pub fn as_str(&self) -> &'a str {
self.0
}
}

impl AsRef<str> for ScriptLangTag<'_> {
fn as_ref(&self) -> &str {
self.0
}
}

#[cfg(feature = "std")]
impl From<ScriptLangTag<'_>> for String {
fn from(value: ScriptLangTag<'_>) -> Self {
value.0.into()
}
}

impl VarSize for ScriptLangTag<'_> {
type Size = u32;

fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
let bytes = data.split_off(pos)?.as_bytes();
if bytes.is_empty() {
return None;
}
let end = data
.as_bytes()
.iter()
.position(|b| *b == b',')
.map(|pos| pos + 1) // include comma
.unwrap_or(bytes.len());
Some(end)
}
}

impl<'a> FontRead<'a> for ScriptLangTag<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
std::str::from_utf8(data.as_bytes())
.map_err(|_| ReadError::MalformedData("LangScriptTag must be utf8"))
.map(|s| ScriptLangTag(s.trim_matches([' ', ','])))
}
}

#[cfg(test)]
mod tests {
use super::*;
use font_test_data::meta as test_data;

impl PartialEq<&str> for ScriptLangTag<'_> {
fn eq(&self, other: &&str) -> bool {
self.as_ref() == *other
}
}

fn expect_script_lang_tags(table: Metadata, expected: &[&str]) -> bool {
let Metadata::ScriptLangTags(langs) = table else {
panic!("wrong metadata");
};
let result = langs.iter().map(|x| x.unwrap()).collect::<Vec<_>>();
result == expected
}

#[test]
fn parse_simple() {
let table = Meta::read(test_data::SIMPLE_META_TABLE.into()).unwrap();
let rec1 = table.data_maps()[0];
let rec2 = table.data_maps()[1];

assert_eq!(rec1.tag(), Tag::new(b"dlng"));
assert_eq!(rec2.tag(), Tag::new(b"slng"));
assert!(expect_script_lang_tags(
rec1.data(table.offset_data()).unwrap(),
&["en-latn", "latn"]
));
assert!(expect_script_lang_tags(
rec2.data(table.offset_data()).unwrap(),
&["latn"]
));
}
}
38 changes: 38 additions & 0 deletions resources/codegen_inputs/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#![parse_module(read_fonts::tables::meta)]

/// [`meta`](https://docs.microsoft.com/en-us/typography/opentype/spec/meta)
#[tag = "meta"]
table Meta {
/// Version number of the metadata table — set to 1.
#[compile(1)]
version: u32,
/// Flags — currently unused; set to 0.
#[compile(0)]
flags: u32,
/// Not used; set to 0.
#[skip_getter]
#[compile(0)]
reserved: u32,
/// The number of data maps in the table.
#[compile(array_len($data_maps))]
data_maps_count: u32,
/// Array of data map records.
#[count($data_maps_count)]
data_maps: [DataMapRecord],
}

/// <https://learn.microsoft.com/en-us/typography/opentype/spec/meta#table-formats>
#[skip_from_obj]
record DataMapRecord {
/// A tag indicating the type of metadata.
tag: Tag,
/// Offset in bytes from the beginning of the metadata table to the data for this tag.
#[read_offset_with($tag, $data_length)]
#[traverse_with(skip)]
#[validate(validate_data_type)]
data_offset: Offset32<Metadata>,
/// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
#[compile(self.compute_data_len())]
data_length: u32,
}

Loading