Skip to content

Commit

Permalink
Add initial implementation of meta table, with read and write
Browse files Browse the repository at this point in the history
This commit adds the code necessary to read and write the `meta` table,
including its codegen definition, manual extras to handle the variable
length data fields, and plumbing to surface it within `read-fonts` and
`write-fonts`.

Where possible, this commit borrows liberally from the implementation of
other tables, especially `name` (for its handling of variable length
data).

This is an early implementation, and as such requires manual and
automated testing. Additionally, there is an implementation of the
FontWrite trait for &[u8] that may be redundant.
  • Loading branch information
Hoolean authored and cmyr committed Nov 19, 2024
1 parent a41651c commit 6e445f8
Show file tree
Hide file tree
Showing 9 changed files with 382 additions and 0 deletions.
168 changes: 168 additions & 0 deletions read-fonts/generated/generated_meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// 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 {
fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
fn flags_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
fn reserved_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
fn data_maps_count_byte_range(&self) -> Range<usize> {
let start = self.reserved_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
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()
}

/// 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",
FieldType::offset_to_array_of_scalars(self.data_offset(), self.data(_data)),
)),
2usize => Some(Field::new("data_length", self.data_length())),
_ => None,
}),
data,
}
}
}
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
15 changes: 15 additions & 0 deletions read-fonts/src/tables/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//! The [meta (Metadata)](https://docs.microsoft.com/en-us/typography/opentype/spec/meta) table
include!("../../generated/generated_meta.rs");

impl DataMapRecord {
/// The data under this record, interpreted from length and offset.
pub fn data<'a>(&self, data: FontData<'a>) -> Result<&'a [u8], ReadError> {
let start = self.data_offset().to_usize();
let end = start + self.data_length() as usize;

data.as_bytes()
.get(start..end)
.ok_or(ReadError::OutOfBounds)
}
}
34 changes: 34 additions & 0 deletions resources/codegen_inputs/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![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.
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
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.
#[offset_getter(data)]
#[compile_with(compile_map_value)]
data_offset: Offset32<[u8]>,
/// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
#[compile(skip)]
data_length: u32,
}
10 changes: 10 additions & 0 deletions resources/codegen_plan.toml
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,16 @@ mode = "compile"
source = "resources/codegen_inputs/maxp.rs"
target = "write-fonts/generated/generated_maxp.rs"

[[generate]]
mode = "parse"
source = "resources/codegen_inputs/meta.rs"
target = "read-fonts/generated/generated_meta.rs"

[[generate]]
mode = "compile"
source = "resources/codegen_inputs/meta.rs"
target = "write-fonts/generated/generated_meta.rs"

[[generate]]
mode = "parse"
source = "resources/codegen_inputs/stat.rs"
Expand Down
119 changes: 119 additions & 0 deletions write-fonts/generated/generated_meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Meta {
/// The number of data maps in the table.
pub data_maps_count: u32,
/// Array of data map records.
pub data_maps: Vec<DataMapRecord>,
}

impl Meta {
/// Construct a new `Meta`
pub fn new(data_maps_count: u32, data_maps: Vec<DataMapRecord>) -> Self {
Self {
data_maps_count,
data_maps: data_maps.into_iter().map(Into::into).collect(),
}
}
}

impl FontWrite for Meta {
#[allow(clippy::unnecessary_cast)]
fn write_into(&self, writer: &mut TableWriter) {
(1 as u32).write_into(writer);
(0 as u32).write_into(writer);
(0 as u32).write_into(writer);
self.data_maps_count.write_into(writer);
self.data_maps.write_into(writer);
}
fn table_type(&self) -> TableType {
TableType::TopLevel(Meta::TAG)
}
}

impl Validate for Meta {
fn validate_impl(&self, ctx: &mut ValidationCtx) {
ctx.in_table("Meta", |ctx| {
ctx.in_field("data_maps", |ctx| {
if self.data_maps.len() > (u32::MAX as usize) {
ctx.report("array exceeds max length");
}
self.data_maps.validate_impl(ctx);
});
})
}
}

impl TopLevelTable for Meta {
const TAG: Tag = Tag::new(b"meta");
}

impl<'a> FromObjRef<read_fonts::tables::meta::Meta<'a>> for Meta {
fn from_obj_ref(obj: &read_fonts::tables::meta::Meta<'a>, _: FontData) -> Self {
let offset_data = obj.offset_data();
Meta {
data_maps_count: obj.data_maps_count(),
data_maps: obj.data_maps().to_owned_obj(offset_data),
}
}
}

impl<'a> FromTableRef<read_fonts::tables::meta::Meta<'a>> for Meta {}

impl<'a> FontRead<'a> for Meta {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
<read_fonts::tables::meta::Meta as FontRead>::read(data).map(|x| x.to_owned_table())
}
}

/// https://learn.microsoft.com/en-us/typography/opentype/spec/meta#table-formats
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DataMapRecord {
/// A tag indicating the type of metadata.
pub tag: Tag,
/// Offset in bytes from the beginning of the metadata table to the data for this tag.
pub data: OffsetMarker<Vec<u8>, WIDTH_32>,
}

impl DataMapRecord {
/// Construct a new `DataMapRecord`
pub fn new(tag: Tag, data: Vec<u8>) -> Self {
Self {
tag,
data: data.into(),
}
}
}

impl FontWrite for DataMapRecord {
#[allow(clippy::unnecessary_cast)]
fn write_into(&self, writer: &mut TableWriter) {
self.tag.write_into(writer);
(self.compile_map_value()).write_into(writer);
}
fn table_type(&self) -> TableType {
TableType::Named("DataMapRecord")
}
}

impl Validate for DataMapRecord {
fn validate_impl(&self, _ctx: &mut ValidationCtx) {}
}

impl FromObjRef<read_fonts::tables::meta::DataMapRecord> for DataMapRecord {
fn from_obj_ref(obj: &read_fonts::tables::meta::DataMapRecord, offset_data: FontData) -> Self {
DataMapRecord {
tag: obj.tag(),
data: obj.data(offset_data).to_owned_obj(offset_data),
}
}
}
2 changes: 2 additions & 0 deletions write-fonts/src/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod ift;
pub mod layout;
pub mod loca;
pub mod maxp;
pub mod meta;
pub mod mvar;
pub mod name;
pub mod os2;
Expand Down Expand Up @@ -51,6 +52,7 @@ fn do_we_even_serde() {
hvar: hvar::Hvar,
loca: loca::Loca,
maxp: maxp::Maxp,
meta: meta::Meta,
name: name::Name,
os2: os2::Os2,
post: post::Post,
Expand Down
Loading

0 comments on commit 6e445f8

Please sign in to comment.