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

Add initial implementation of meta #1237

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
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)
}
}
35 changes: 35 additions & 0 deletions resources/codegen_inputs/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#![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
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
115 changes: 115 additions & 0 deletions write-fonts/generated/generated_meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// 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 {
/// Array of data map records.
pub data_maps: Vec<DataMapRecord>,
}

impl Meta {
/// Construct a new `Meta`
pub fn new(data_maps: Vec<DataMapRecord>) -> Self {
Self {
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);
(array_len(&self.data_maps).unwrap() as u32).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: 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
Loading