Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 20:53:56 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions
File diff suppressed because one or more lines are too long
+676
View File
@@ -0,0 +1,676 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
dependencies = [
"memchr",
]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bumpalo"
version = "3.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "bytemuck"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4da9a32f3fed317401fa3c862968128267c3106685286e15d5aaa3d7389c2f60"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [
"bitflags",
"textwrap",
"unicode-width",
]
[[package]]
name = "core_maths"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b02505ccb8c50b0aa21ace0fc08c3e53adebd4e58caa18a36152803c7709a3"
dependencies = [
"libm",
]
[[package]]
name = "criterion"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f"
dependencies = [
"atty",
"cast",
"clap",
"criterion-plot",
"csv",
"itertools",
"lazy_static",
"num-traits",
"oorandom",
"plotters",
"rayon",
"regex",
"serde",
"serde_cbor",
"serde_derive",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
[[package]]
name = "csv"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdc4883a9c96732e4733212c01447ebd805833b7275a73ca3ee080fd77afdaf"
dependencies = [
"csv-core",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "csv-core"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d02f3b0da4c6504f86e9cd789d8dbafab48c2321be74e9987593de5a894d93d"
dependencies = [
"memchr",
]
[[package]]
name = "either"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
[[package]]
name = "font-types"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02a596f5713680923a2080d86de50fe472fb290693cf0f701187a1c8b36996b7"
dependencies = [
"bytemuck",
"serde",
]
[[package]]
name = "getrandom"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "half"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403"
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
[[package]]
name = "js-sys"
version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
name = "libm"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "memchr"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "oorandom"
version = "11.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9"
[[package]]
name = "plotters"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
dependencies = [
"num-traits",
"plotters-backend",
"plotters-svg",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "plotters-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
[[package]]
name = "plotters-svg"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
dependencies = [
"plotters-backend",
]
[[package]]
name = "ppv-lite86"
version = "0.2.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "rayon"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4963ed1bc86e4f3ee217022bd855b297cef07fb9eac5dfa1f788b220b49b3bd"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "read-fonts"
version = "0.29.3"
dependencies = [
"bytemuck",
"core_maths",
"criterion",
"font-types",
"rand",
"serde",
"serde_json",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "ryu"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_cbor"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5"
dependencies = [
"half",
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "syn"
version = "2.0.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "textwrap"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"unicode-width",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-width"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
dependencies = [
"cfg-if",
"once_cell",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
[[package]]
name = "web-sys"
version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "zerocopy"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [
"byteorder",
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+95
View File
@@ -0,0 +1,95 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.75"
name = "read-fonts"
version = "0.29.3"
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Reading OpenType font files."
readme = "README.md"
categories = [
"text-processing",
"parsing",
"graphics",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/googlefonts/fontations"
[package.metadata.docs.rs]
features = [
"libm",
"serde",
"std",
]
[features]
codegen_test = []
default = ["std"]
experimental_traverse = ["std"]
ift = []
libm = ["dep:core_maths"]
scaler_test = []
serde = [
"dep:serde",
"font-types/serde",
]
spec_next = []
std = ["font-types/std"]
[lib]
name = "read_fonts"
path = "src/lib.rs"
[[bench]]
name = "bench_helper"
path = "benches/bench_helper.rs"
[[bench]]
name = "int_set_benchmark"
path = "benches/int_set_benchmark.rs"
harness = false
[[bench]]
name = "sparse_bit_set_benchmark"
path = "benches/sparse_bit_set_benchmark.rs"
harness = false
[dependencies.bytemuck]
version = "1.13.1"
[dependencies.core_maths]
version = "0.1"
optional = true
[dependencies.font-types]
version = "0.9.0"
features = ["bytemuck"]
[dependencies.serde]
version = "1.0"
features = ["derive"]
optional = true
[dev-dependencies.criterion]
version = "0.3.0"
[dev-dependencies.rand]
version = "0.8.5"
[dev-dependencies.serde_json]
version = "1.0"
+67
View File
@@ -0,0 +1,67 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2019 Colin Rothfels
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2019 Colin Rothfels
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
# read-fonts
This crate handles parsing and reading of OpenType fonts. It is intended to be a
high performance implementation suitable for tasks such as [shaping][], while
still providing a convenient, high-level API.
## Safety
Unsafe code is forbidden by a `#![forbid(unsafe_code)]` attribute in the root
of the library.
## codegen
Much of the code in this crate is generated automatically. This generated code
lives in the `generated` directory. Each file in this directory is included
in a module in the `src` directory, using Rust's [`include!`] macro. This allows
us to separate the generated code from any custom implementation code, while
allowing them to exist in the same module.
### what we generate
With certain exceptions that require manual handling, we generate code for each
*table*, *record*, *enum*, and *flags* type for each portion of the spec that we
cover.
## tables
All tables are aliases of the type `TableRef<Marker>`, where `Marker` is a
struct that indicates the type of the table. For instance, the [GDEF table][Gdef]
is defined as `TableRef<GdefMarker>`. `TableRef` itself is a wrapper around a
slice of bytes, with the *marker* type providing typed access to those bytes.
The marker type can only be created from a specific byte slice, and is always
associated with that slice. It is created through a `parse` method that performs
a one-time validation of the slice, ensuring that all expected fields are
present. This includes bounds checking any arrays, as well as ensuring the
presence of fields the existence of which may depend on the table's version.
### variable lengths and version-dependent fields
**n.b**: *the design described below has not been benchmarked against the
alternatives, and may change*
For fields that have variable length, or which only exist in certain table
versions, the marker struct has a corresponding field where that length or
offset is stored. This means that at runtime there is no need to double check a
version or length.
### TableRef methods
For each table, we define methods on the type `TableRef<Marker>` that provide
access to that table's fields. These methods use the marker type to determine
the byte range of a given field, and then interpret those bytes as the
appropriate type.
## records
Unlike tables, which are essentially a set of methods for reading into a byte
slice, *records* are **in general** represented as simple packed structs
containing scalar types in big-endian encodings. This means that, in general,
records are zerocopy types that can be cast from raw bytes.
The exception to this is when a record has variable length; in this case the
record is still a simple struct, but cannot be cast from raw bytes, and must be
copied.
## flags and enums
For flags, we generate a type modeled on those generated by the [`bitflags!` macro][bitflags].
For enums, we generate a raw Rust enum.
[shaping]: https://fonts.google.com/knowledge/glossary/shaping
[`include!`]: http://doc.rust-lang.org/1.63.0/std/macro.include.html
[gdef-marker]: https://github.com/googlefonts/fontations/blob/main/read-fonts/generated/generated_gdef.rs#L11
[Gdef]: https://github.com/googlefonts/fontations/blob/main/read-fonts/generated/generated_gdef.rs#L77
[bitflags]: https://docs.rs/bitflags/latest/bitflags/
+17
View File
@@ -0,0 +1,17 @@
use read_fonts::collections::IntSet;
use rand::Rng;
pub fn random_set(size: u32, max_value: u32) -> IntSet<u32> {
let mut rng = rand::thread_rng();
let mut set = IntSet::<u32>::empty();
for _ in 0..size {
loop {
let candidate: u32 = rng.gen::<u32>() % max_value;
if set.insert(candidate) {
break;
}
}
}
set
}
+145
View File
@@ -0,0 +1,145 @@
mod bench_helper;
use bench_helper::random_set;
use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion};
use read_fonts::collections::IntSet;
struct SetTest {
set_size: u32,
density: u32,
}
impl SetTest {
fn max_value(&self) -> u32 {
self.density * self.set_size
}
}
impl std::fmt::Display for SetTest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.set_size, self.density)
}
}
fn set_parameters() -> Vec<SetTest> {
let mut inputs: Vec<SetTest> = Vec::<SetTest>::new();
for density in [2, 8, 64, 512] {
for set_size in [1024, 4096, 32_768, 65_536] {
inputs.push(SetTest { set_size, density })
}
}
inputs
}
pub fn insert_benchmark(c: &mut Criterion) {
const NUM_INSERTS: u32 = 1000;
let inputs = set_parameters();
for input in inputs {
c.bench_with_input(
BenchmarkId::new("BM_SetInsert_1000", &input),
&input,
|b, p: &SetTest| {
let set = random_set(p.set_size, p.max_value());
b.iter_batched(
|| set.clone(),
|mut s| {
for i in 0..NUM_INSERTS {
let v: u32 = i.wrapping_mul(2_654_435_761) % p.max_value();
s.insert(v);
}
},
BatchSize::SmallInput,
)
},
);
}
}
pub fn ordered_extend_benchmark(c: &mut Criterion) {
let num_inserts = 1000u32;
let inputs = set_parameters();
for input in inputs {
c.bench_with_input(
BenchmarkId::new("BM_SetOrderedInsert_1000", &input),
&input,
|b, p: &SetTest| {
let set = random_set(p.set_size, p.max_value());
b.iter_batched(
|| set.clone(),
|mut s| {
s.extend(0..num_inserts);
},
BatchSize::SmallInput,
)
},
);
}
}
pub fn lookup_random_benchmark(c: &mut Criterion) {
let inputs = set_parameters();
for input in inputs {
let set = random_set(input.set_size, input.max_value());
let mut needle = input.max_value() / 2;
c.bench_with_input(
BenchmarkId::new("BM_SetLookup/random", &input),
&set,
|b, s: &IntSet<u32>| {
b.iter(|| {
needle += 12345;
s.contains(needle % input.max_value())
})
},
);
}
}
pub fn lookup_ordered_benchmark(c: &mut Criterion) {
let inputs = set_parameters();
for input in inputs {
let set = random_set(input.set_size, input.max_value());
let mut needle = input.max_value() / 2;
c.bench_with_input(
BenchmarkId::new("BM_SetLookup/ordered", &input),
&set,
|b, s: &IntSet<u32>| {
b.iter(|| {
needle += 3;
s.contains(needle % input.max_value())
})
},
);
}
}
pub fn iteration_benchmark(c: &mut Criterion) {
let inputs = set_parameters();
for input in inputs {
let set = random_set(input.set_size, input.max_value());
c.bench_with_input(
BenchmarkId::new("BM_SetIteration", &input),
&set,
|b, s: &IntSet<u32>| {
b.iter(|| {
for v in s.iter() {
black_box(v);
}
})
},
);
}
}
criterion_group!(
benches,
insert_benchmark,
ordered_extend_benchmark,
lookup_random_benchmark,
lookup_ordered_benchmark,
iteration_benchmark,
);
criterion_main!(benches);
+68
View File
@@ -0,0 +1,68 @@
mod bench_helper;
use bench_helper::random_set;
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use read_fonts::collections::int_set::{sparse_bit_set::to_sparse_bit_set_with_bf, IntSet};
struct SparseSetTest {
set_size: u32,
density: u32,
branch_factor: u32,
}
impl SparseSetTest {
fn max_value(&self) -> u32 {
self.density * self.set_size
}
}
impl std::fmt::Display for SparseSetTest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"bf{}_{}/{}",
self.branch_factor, self.set_size, self.density
)
}
}
fn set_parameters() -> Vec<SparseSetTest> {
let mut inputs: Vec<SparseSetTest> = Vec::<SparseSetTest>::new();
for branch_factor in [2, 4, 8, 32] {
for density in [2, 8] {
for set_size in [1024, 4096, 32_768] {
inputs.push(SparseSetTest {
set_size,
density,
branch_factor,
})
}
}
}
inputs
}
pub fn decode_benchmark(c: &mut Criterion) {
let inputs = set_parameters();
for input in inputs {
let set = random_set(input.set_size, input.max_value());
let encoded = match input.branch_factor {
2 => to_sparse_bit_set_with_bf::<2>(&set),
4 => to_sparse_bit_set_with_bf::<4>(&set),
8 => to_sparse_bit_set_with_bf::<8>(&set),
32 => to_sparse_bit_set_with_bf::<32>(&set),
_ => panic!("not implemented."),
};
c.bench_with_input(
BenchmarkId::new("BM_SparseSetDecode", &input),
&input,
|b, _: &SparseSetTest| {
b.iter(|| black_box(IntSet::<u32>::from_sparse_bit_set(&encoded)));
},
);
}
}
criterion_group!(benches, decode_benchmark);
criterion_main!(benches);
+378
View File
@@ -0,0 +1,378 @@
// 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::*;
/// The OpenType [Table Directory](https://docs.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TableDirectoryMarker {
table_records_byte_len: usize,
}
impl TableDirectoryMarker {
pub fn sfnt_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn num_tables_byte_range(&self) -> Range<usize> {
let start = self.sfnt_version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn search_range_byte_range(&self) -> Range<usize> {
let start = self.num_tables_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn entry_selector_byte_range(&self) -> Range<usize> {
let start = self.search_range_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn range_shift_byte_range(&self) -> Range<usize> {
let start = self.entry_selector_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn table_records_byte_range(&self) -> Range<usize> {
let start = self.range_shift_byte_range().end;
start..start + self.table_records_byte_len
}
}
impl MinByteRange for TableDirectoryMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.table_records_byte_range().end
}
}
impl<'a> FontRead<'a> for TableDirectory<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
let num_tables: u16 = cursor.read()?;
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
let table_records_byte_len = (num_tables as usize)
.checked_mul(TableRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(table_records_byte_len);
cursor.finish(TableDirectoryMarker {
table_records_byte_len,
})
}
}
/// The OpenType [Table Directory](https://docs.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
pub type TableDirectory<'a> = TableRef<'a, TableDirectoryMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> TableDirectory<'a> {
/// 0x00010000 or 0x4F54544F
pub fn sfnt_version(&self) -> u32 {
let range = self.shape.sfnt_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of tables.
pub fn num_tables(&self) -> u16 {
let range = self.shape.num_tables_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn search_range(&self) -> u16 {
let range = self.shape.search_range_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn entry_selector(&self) -> u16 {
let range = self.shape.entry_selector_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn range_shift(&self) -> u16 {
let range = self.shape.range_shift_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Table records array—one for each top-level table in the font
pub fn table_records(&self) -> &'a [TableRecord] {
let range = self.shape.table_records_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for TableDirectory<'a> {
fn type_name(&self) -> &str {
"TableDirectory"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("sfnt_version", self.sfnt_version())),
1usize => Some(Field::new("num_tables", self.num_tables())),
2usize => Some(Field::new("search_range", self.search_range())),
3usize => Some(Field::new("entry_selector", self.entry_selector())),
4usize => Some(Field::new("range_shift", self.range_shift())),
5usize => Some(Field::new(
"table_records",
traversal::FieldType::array_of_records(
stringify!(TableRecord),
self.table_records(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for TableDirectory<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Record for a table in a font.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct TableRecord {
/// Table identifier.
pub tag: BigEndian<Tag>,
/// Checksum for the table.
pub checksum: BigEndian<u32>,
/// Offset from the beginning of the font data.
pub offset: BigEndian<u32>,
/// Length of the table.
pub length: BigEndian<u32>,
}
impl TableRecord {
/// Table identifier.
pub fn tag(&self) -> Tag {
self.tag.get()
}
/// Checksum for the table.
pub fn checksum(&self) -> u32 {
self.checksum.get()
}
/// Offset from the beginning of the font data.
pub fn offset(&self) -> u32 {
self.offset.get()
}
/// Length of the table.
pub fn length(&self) -> u32 {
self.length.get()
}
}
impl FixedSize for TableRecord {
const RAW_BYTE_LEN: usize =
Tag::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for TableRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "TableRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("tag", self.tag())),
1usize => Some(Field::new("checksum", self.checksum())),
2usize => Some(Field::new("offset", self.offset())),
3usize => Some(Field::new("length", self.length())),
_ => None,
}),
data,
}
}
}
/// [TTC Header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TTCHeaderMarker {
table_directory_offsets_byte_len: usize,
dsig_tag_byte_start: Option<usize>,
dsig_length_byte_start: Option<usize>,
dsig_offset_byte_start: Option<usize>,
}
impl TTCHeaderMarker {
pub fn ttc_tag_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + Tag::RAW_BYTE_LEN
}
pub fn version_byte_range(&self) -> Range<usize> {
let start = self.ttc_tag_byte_range().end;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn num_fonts_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn table_directory_offsets_byte_range(&self) -> Range<usize> {
let start = self.num_fonts_byte_range().end;
start..start + self.table_directory_offsets_byte_len
}
pub fn dsig_tag_byte_range(&self) -> Option<Range<usize>> {
let start = self.dsig_tag_byte_start?;
Some(start..start + u32::RAW_BYTE_LEN)
}
pub fn dsig_length_byte_range(&self) -> Option<Range<usize>> {
let start = self.dsig_length_byte_start?;
Some(start..start + u32::RAW_BYTE_LEN)
}
pub fn dsig_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.dsig_offset_byte_start?;
Some(start..start + u32::RAW_BYTE_LEN)
}
}
impl MinByteRange for TTCHeaderMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.table_directory_offsets_byte_range().end
}
}
impl<'a> FontRead<'a> for TTCHeader<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<Tag>();
let version: MajorMinor = cursor.read()?;
let num_fonts: u32 = cursor.read()?;
let table_directory_offsets_byte_len = (num_fonts as usize)
.checked_mul(u32::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(table_directory_offsets_byte_len);
let dsig_tag_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<u32>());
let dsig_length_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<u32>());
let dsig_offset_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<u32>());
cursor.finish(TTCHeaderMarker {
table_directory_offsets_byte_len,
dsig_tag_byte_start,
dsig_length_byte_start,
dsig_offset_byte_start,
})
}
}
/// [TTC Header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
pub type TTCHeader<'a> = TableRef<'a, TTCHeaderMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> TTCHeader<'a> {
/// Font Collection ID string: \"ttcf\"
pub fn ttc_tag(&self) -> Tag {
let range = self.shape.ttc_tag_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Major/minor version of the TTC Header
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of fonts in TTC
pub fn num_fonts(&self) -> u32 {
let range = self.shape.num_fonts_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Array of offsets to the TableDirectory for each font from the beginning of the file
pub fn table_directory_offsets(&self) -> &'a [BigEndian<u32>] {
let range = self.shape.table_directory_offsets_byte_range();
self.data.read_array(range).unwrap()
}
/// Tag indicating that a DSIG table exists, 0x44534947 ('DSIG') (null if no signature)
pub fn dsig_tag(&self) -> Option<u32> {
let range = self.shape.dsig_tag_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// The length (in bytes) of the DSIG table (null if no signature)
pub fn dsig_length(&self) -> Option<u32> {
let range = self.shape.dsig_length_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// The offset (in bytes) of the DSIG table from the beginning of the TTC file (null if no signature)
pub fn dsig_offset(&self) -> Option<u32> {
let range = self.shape.dsig_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for TTCHeader<'a> {
fn type_name(&self) -> &str {
"TTCHeader"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("ttc_tag", self.ttc_tag())),
1usize => Some(Field::new("version", self.version())),
2usize => Some(Field::new("num_fonts", self.num_fonts())),
3usize => Some(Field::new(
"table_directory_offsets",
self.table_directory_offsets(),
)),
4usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("dsig_tag", self.dsig_tag().unwrap()))
}
5usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("dsig_length", self.dsig_length().unwrap()))
}
6usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("dsig_offset", self.dsig_offset().unwrap()))
}
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for TTCHeader<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
File diff suppressed because it is too large Load Diff
+245
View File
@@ -0,0 +1,245 @@
// 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::*;
/// The [anchor point](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct AnkrMarker {}
impl AnkrMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn lookup_table_offset_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn glyph_data_table_offset_byte_range(&self) -> Range<usize> {
let start = self.lookup_table_offset_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
}
impl MinByteRange for AnkrMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.glyph_data_table_offset_byte_range().end
}
}
impl TopLevelTable for Ankr<'_> {
/// `ankr`
const TAG: Tag = Tag::new(b"ankr");
}
impl<'a> FontRead<'a> for Ankr<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<Offset32>();
cursor.advance::<u32>();
cursor.finish(AnkrMarker {})
}
}
/// The [anchor point](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html) table.
pub type Ankr<'a> = TableRef<'a, AnkrMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Ankr<'a> {
/// Version number (set to zero).
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Flags (currently unused; set to zero).
pub fn flags(&self) -> u16 {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset to the table's lookup table; currently this is always `0x0000000C`.
///
/// Lookup values are two byte offsets into the glyph data table.
pub fn lookup_table_offset(&self) -> Offset32 {
let range = self.shape.lookup_table_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`lookup_table_offset`][Self::lookup_table_offset].
pub fn lookup_table(&self) -> Result<LookupU16<'a>, ReadError> {
let data = self.data;
self.lookup_table_offset().resolve(data)
}
/// Offset to the glyph data table.
pub fn glyph_data_table_offset(&self) -> u32 {
let range = self.shape.glyph_data_table_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Ankr<'a> {
fn type_name(&self) -> &str {
"Ankr"
}
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(
"lookup_table_offset",
FieldType::offset(self.lookup_table_offset(), self.lookup_table()),
)),
3usize => Some(Field::new(
"glyph_data_table_offset",
self.glyph_data_table_offset(),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Ankr<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GlyphDataEntryMarker {
anchor_points_byte_len: usize,
}
impl GlyphDataEntryMarker {
pub fn num_points_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn anchor_points_byte_range(&self) -> Range<usize> {
let start = self.num_points_byte_range().end;
start..start + self.anchor_points_byte_len
}
}
impl MinByteRange for GlyphDataEntryMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.anchor_points_byte_range().end
}
}
impl<'a> FontRead<'a> for GlyphDataEntry<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let num_points: u32 = cursor.read()?;
let anchor_points_byte_len = (num_points as usize)
.checked_mul(AnchorPoint::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(anchor_points_byte_len);
cursor.finish(GlyphDataEntryMarker {
anchor_points_byte_len,
})
}
}
pub type GlyphDataEntry<'a> = TableRef<'a, GlyphDataEntryMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> GlyphDataEntry<'a> {
/// Number of anchor points for this glyph.
pub fn num_points(&self) -> u32 {
let range = self.shape.num_points_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Individual anchor points.
pub fn anchor_points(&self) -> &'a [AnchorPoint] {
let range = self.shape.anchor_points_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for GlyphDataEntry<'a> {
fn type_name(&self) -> &str {
"GlyphDataEntry"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("num_points", self.num_points())),
1usize => Some(Field::new(
"anchor_points",
traversal::FieldType::array_of_records(
stringify!(AnchorPoint),
self.anchor_points(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for GlyphDataEntry<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Individual anchor point.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct AnchorPoint {
pub x: BigEndian<i16>,
pub y: BigEndian<i16>,
}
impl AnchorPoint {
pub fn x(&self) -> i16 {
self.x.get()
}
pub fn y(&self) -> i16 {
self.y.get()
}
}
impl FixedSize for AnchorPoint {
const RAW_BYTE_LEN: usize = i16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for AnchorPoint {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "AnchorPoint",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("x", self.x())),
1usize => Some(Field::new("y", self.y())),
_ => None,
}),
data,
}
}
}
+264
View File
@@ -0,0 +1,264 @@
// 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::*;
/// The [avar (Axis Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct AvarMarker {
axis_segment_maps_byte_len: usize,
axis_index_map_offset_byte_start: Option<usize>,
var_store_offset_byte_start: Option<usize>,
}
impl AvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn _reserved_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn axis_count_byte_range(&self) -> Range<usize> {
let start = self._reserved_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn axis_segment_maps_byte_range(&self) -> Range<usize> {
let start = self.axis_count_byte_range().end;
start..start + self.axis_segment_maps_byte_len
}
pub fn axis_index_map_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.axis_index_map_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
pub fn var_store_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.var_store_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
}
impl MinByteRange for AvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.axis_segment_maps_byte_range().end
}
}
impl TopLevelTable for Avar<'_> {
/// `avar`
const TAG: Tag = Tag::new(b"avar");
}
impl<'a> FontRead<'a> for Avar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: MajorMinor = cursor.read()?;
cursor.advance::<u16>();
let axis_count: u16 = cursor.read()?;
let axis_segment_maps_byte_len = {
let data = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
<SegmentMaps as VarSize>::total_len_for_count(data, axis_count as usize)?
};
cursor.advance_by(axis_segment_maps_byte_len);
let axis_index_map_offset_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<Offset32>());
let var_store_offset_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<Offset32>());
cursor.finish(AvarMarker {
axis_segment_maps_byte_len,
axis_index_map_offset_byte_start,
var_store_offset_byte_start,
})
}
}
/// The [avar (Axis Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
pub type Avar<'a> = TableRef<'a, AvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Avar<'a> {
/// Major version number of the axis variations table — set to 1 or 2.
/// Minor version number of the axis variations table — set to 0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of variation axes for this font. This must be the same number as axisCount in the 'fvar' table.
pub fn axis_count(&self) -> u16 {
let range = self.shape.axis_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The segment maps array — one segment map for each axis, in the order of axes specified in the 'fvar' table.
pub fn axis_segment_maps(&self) -> VarLenArray<'a, SegmentMaps<'a>> {
let range = self.shape.axis_segment_maps_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
/// Offset to DeltaSetIndexMap table (may be NULL).
pub fn axis_index_map_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.axis_index_map_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`axis_index_map_offset`][Self::axis_index_map_offset].
pub fn axis_index_map(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.axis_index_map_offset().map(|x| x.resolve(data))?
}
/// Offset to ItemVariationStore (may be NULL).
pub fn var_store_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.var_store_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`var_store_offset`][Self::var_store_offset].
pub fn var_store(&self) -> Option<Result<ItemVariationStore<'a>, ReadError>> {
let data = self.data;
self.var_store_offset().map(|x| x.resolve(data))?
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Avar<'a> {
fn type_name(&self) -> &str {
"Avar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("axis_count", self.axis_count())),
2usize => Some(Field::new(
"axis_segment_maps",
traversal::FieldType::var_array(
"SegmentMaps",
self.axis_segment_maps(),
self.offset_data(),
),
)),
3usize if version.compatible((2u16, 0u16)) => Some(Field::new(
"axis_index_map_offset",
FieldType::offset(self.axis_index_map_offset().unwrap(), self.axis_index_map()),
)),
4usize if version.compatible((2u16, 0u16)) => Some(Field::new(
"var_store_offset",
FieldType::offset(self.var_store_offset().unwrap(), self.var_store()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Avar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [SegmentMaps](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SegmentMaps<'a> {
/// The number of correspondence pairs for this axis.
pub position_map_count: BigEndian<u16>,
/// The array of axis value map records for this axis.
pub axis_value_maps: &'a [AxisValueMap],
}
impl<'a> SegmentMaps<'a> {
/// The number of correspondence pairs for this axis.
pub fn position_map_count(&self) -> u16 {
self.position_map_count.get()
}
/// The array of axis value map records for this axis.
pub fn axis_value_maps(&self) -> &'a [AxisValueMap] {
self.axis_value_maps
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SegmentMaps<'a> {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "SegmentMaps",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("position_map_count", self.position_map_count())),
1usize => Some(Field::new(
"axis_value_maps",
traversal::FieldType::array_of_records(
stringify!(AxisValueMap),
self.axis_value_maps(),
_data,
),
)),
_ => None,
}),
data,
}
}
}
/// [AxisValueMap](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct AxisValueMap {
/// A normalized coordinate value obtained using default normalization.
pub from_coordinate: BigEndian<F2Dot14>,
/// The modified, normalized coordinate value.
pub to_coordinate: BigEndian<F2Dot14>,
}
impl AxisValueMap {
/// A normalized coordinate value obtained using default normalization.
pub fn from_coordinate(&self) -> F2Dot14 {
self.from_coordinate.get()
}
/// The modified, normalized coordinate value.
pub fn to_coordinate(&self) -> F2Dot14 {
self.to_coordinate.get()
}
}
impl FixedSize for AxisValueMap {
const RAW_BYTE_LEN: usize = F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for AxisValueMap {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "AxisValueMap",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("from_coordinate", self.from_coordinate())),
1usize => Some(Field::new("to_coordinate", self.to_coordinate())),
_ => None,
}),
data,
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+83
View File
@@ -0,0 +1,83 @@
// 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::*;
/// The [Color Bitmap Data](https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CbdtMarker {}
impl CbdtMarker {
pub fn major_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn minor_version_byte_range(&self) -> Range<usize> {
let start = self.major_version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for CbdtMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.minor_version_byte_range().end
}
}
impl TopLevelTable for Cbdt<'_> {
/// `CBDT`
const TAG: Tag = Tag::new(b"CBDT");
}
impl<'a> FontRead<'a> for Cbdt<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(CbdtMarker {})
}
}
/// The [Color Bitmap Data](https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt) table
pub type Cbdt<'a> = TableRef<'a, CbdtMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Cbdt<'a> {
/// Major version of the CBDT table, = 3.
pub fn major_version(&self) -> u16 {
let range = self.shape.major_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minor version of CBDT table, = 0.
pub fn minor_version(&self) -> u16 {
let range = self.shape.minor_version_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cbdt<'a> {
fn type_name(&self) -> &str {
"Cbdt"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major_version", self.major_version())),
1usize => Some(Field::new("minor_version", self.minor_version())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cbdt<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+123
View File
@@ -0,0 +1,123 @@
// 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::*;
/// The [Color Bitmap Location](https://learn.microsoft.com/en-us/typography/opentype/spec/cblc) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CblcMarker {
bitmap_sizes_byte_len: usize,
}
impl CblcMarker {
pub fn major_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn minor_version_byte_range(&self) -> Range<usize> {
let start = self.major_version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_sizes_byte_range(&self) -> Range<usize> {
let start = self.minor_version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn bitmap_sizes_byte_range(&self) -> Range<usize> {
let start = self.num_sizes_byte_range().end;
start..start + self.bitmap_sizes_byte_len
}
}
impl MinByteRange for CblcMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.bitmap_sizes_byte_range().end
}
}
impl TopLevelTable for Cblc<'_> {
/// `CBLC`
const TAG: Tag = Tag::new(b"CBLC");
}
impl<'a> FontRead<'a> for Cblc<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let num_sizes: u32 = cursor.read()?;
let bitmap_sizes_byte_len = (num_sizes as usize)
.checked_mul(BitmapSize::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(bitmap_sizes_byte_len);
cursor.finish(CblcMarker {
bitmap_sizes_byte_len,
})
}
}
/// The [Color Bitmap Location](https://learn.microsoft.com/en-us/typography/opentype/spec/cblc) table
pub type Cblc<'a> = TableRef<'a, CblcMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Cblc<'a> {
/// Major version of the CBLC table, = 3.
pub fn major_version(&self) -> u16 {
let range = self.shape.major_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minor version of CBLC table, = 0.
pub fn minor_version(&self) -> u16 {
let range = self.shape.minor_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of BitmapSize records.
pub fn num_sizes(&self) -> u32 {
let range = self.shape.num_sizes_byte_range();
self.data.read_at(range.start).unwrap()
}
/// BitmapSize records array.
pub fn bitmap_sizes(&self) -> &'a [BitmapSize] {
let range = self.shape.bitmap_sizes_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cblc<'a> {
fn type_name(&self) -> &str {
"Cblc"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major_version", self.major_version())),
1usize => Some(Field::new("minor_version", self.minor_version())),
2usize => Some(Field::new("num_sizes", self.num_sizes())),
3usize => Some(Field::new(
"bitmap_sizes",
traversal::FieldType::array_of_records(
stringify!(BitmapSize),
self.bitmap_sizes(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cblc<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+140
View File
@@ -0,0 +1,140 @@
// 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::*;
/// [Compact Font Format](https://learn.microsoft.com/en-us/typography/opentype/spec/cff) table header
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CffHeaderMarker {
_padding_byte_len: usize,
trailing_data_byte_len: usize,
}
impl CffHeaderMarker {
pub fn major_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u8::RAW_BYTE_LEN
}
pub fn minor_byte_range(&self) -> Range<usize> {
let start = self.major_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn hdr_size_byte_range(&self) -> Range<usize> {
let start = self.minor_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn off_size_byte_range(&self) -> Range<usize> {
let start = self.hdr_size_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn _padding_byte_range(&self) -> Range<usize> {
let start = self.off_size_byte_range().end;
start..start + self._padding_byte_len
}
pub fn trailing_data_byte_range(&self) -> Range<usize> {
let start = self._padding_byte_range().end;
start..start + self.trailing_data_byte_len
}
}
impl MinByteRange for CffHeaderMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.trailing_data_byte_range().end
}
}
impl<'a> FontRead<'a> for CffHeader<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u8>();
cursor.advance::<u8>();
let hdr_size: u8 = cursor.read()?;
cursor.advance::<u8>();
let _padding_byte_len = (transforms::subtract(hdr_size, 4_usize))
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(_padding_byte_len);
let trailing_data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(trailing_data_byte_len);
cursor.finish(CffHeaderMarker {
_padding_byte_len,
trailing_data_byte_len,
})
}
}
/// [Compact Font Format](https://learn.microsoft.com/en-us/typography/opentype/spec/cff) table header
pub type CffHeader<'a> = TableRef<'a, CffHeaderMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> CffHeader<'a> {
/// Format major version (starting at 1).
pub fn major(&self) -> u8 {
let range = self.shape.major_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Format minor version (starting at 0).
pub fn minor(&self) -> u8 {
let range = self.shape.minor_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Header size (bytes).
pub fn hdr_size(&self) -> u8 {
let range = self.shape.hdr_size_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Absolute offset size.
pub fn off_size(&self) -> u8 {
let range = self.shape.off_size_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Padding bytes before the start of the Name INDEX.
pub fn _padding(&self) -> &'a [u8] {
let range = self.shape._padding_byte_range();
self.data.read_array(range).unwrap()
}
/// Remaining table data.
pub fn trailing_data(&self) -> &'a [u8] {
let range = self.shape.trailing_data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CffHeader<'a> {
fn type_name(&self) -> &str {
"CffHeader"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major", self.major())),
1usize => Some(Field::new("minor", self.minor())),
2usize => Some(Field::new("hdr_size", self.hdr_size())),
3usize => Some(Field::new("off_size", self.off_size())),
4usize => Some(Field::new("_padding", self._padding())),
5usize => Some(Field::new("trailing_data", self.trailing_data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CffHeader<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+158
View File
@@ -0,0 +1,158 @@
// 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::*;
/// [Compact Font Format (CFF) version 2](https://learn.microsoft.com/en-us/typography/opentype/spec/cff2) table header
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Cff2HeaderMarker {
_padding_byte_len: usize,
top_dict_data_byte_len: usize,
trailing_data_byte_len: usize,
}
impl Cff2HeaderMarker {
pub fn major_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u8::RAW_BYTE_LEN
}
pub fn minor_version_byte_range(&self) -> Range<usize> {
let start = self.major_version_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn header_size_byte_range(&self) -> Range<usize> {
let start = self.minor_version_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn top_dict_length_byte_range(&self) -> Range<usize> {
let start = self.header_size_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn _padding_byte_range(&self) -> Range<usize> {
let start = self.top_dict_length_byte_range().end;
start..start + self._padding_byte_len
}
pub fn top_dict_data_byte_range(&self) -> Range<usize> {
let start = self._padding_byte_range().end;
start..start + self.top_dict_data_byte_len
}
pub fn trailing_data_byte_range(&self) -> Range<usize> {
let start = self.top_dict_data_byte_range().end;
start..start + self.trailing_data_byte_len
}
}
impl MinByteRange for Cff2HeaderMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.trailing_data_byte_range().end
}
}
impl<'a> FontRead<'a> for Cff2Header<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u8>();
cursor.advance::<u8>();
let header_size: u8 = cursor.read()?;
let top_dict_length: u16 = cursor.read()?;
let _padding_byte_len = (transforms::subtract(header_size, 5_usize))
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(_padding_byte_len);
let top_dict_data_byte_len = (top_dict_length as usize)
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(top_dict_data_byte_len);
let trailing_data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(trailing_data_byte_len);
cursor.finish(Cff2HeaderMarker {
_padding_byte_len,
top_dict_data_byte_len,
trailing_data_byte_len,
})
}
}
/// [Compact Font Format (CFF) version 2](https://learn.microsoft.com/en-us/typography/opentype/spec/cff2) table header
pub type Cff2Header<'a> = TableRef<'a, Cff2HeaderMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Cff2Header<'a> {
/// Format major version (set to 2).
pub fn major_version(&self) -> u8 {
let range = self.shape.major_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Format minor version (set to 0).
pub fn minor_version(&self) -> u8 {
let range = self.shape.minor_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Header size (bytes).
pub fn header_size(&self) -> u8 {
let range = self.shape.header_size_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Length of Top DICT structure in bytes.
pub fn top_dict_length(&self) -> u16 {
let range = self.shape.top_dict_length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Padding bytes before the start of the Top DICT.
pub fn _padding(&self) -> &'a [u8] {
let range = self.shape._padding_byte_range();
self.data.read_array(range).unwrap()
}
/// Data containing the Top DICT.
pub fn top_dict_data(&self) -> &'a [u8] {
let range = self.shape.top_dict_data_byte_range();
self.data.read_array(range).unwrap()
}
/// Remaining table data.
pub fn trailing_data(&self) -> &'a [u8] {
let range = self.shape.trailing_data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cff2Header<'a> {
fn type_name(&self) -> &str {
"Cff2Header"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major_version", self.major_version())),
1usize => Some(Field::new("minor_version", self.minor_version())),
2usize => Some(Field::new("header_size", self.header_size())),
3usize => Some(Field::new("top_dict_length", self.top_dict_length())),
4usize => Some(Field::new("_padding", self._padding())),
5usize => Some(Field::new("top_dict_data", self.top_dict_data())),
6usize => Some(Field::new("trailing_data", self.trailing_data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cff2Header<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+663
View File
@@ -0,0 +1,663 @@
// 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::*;
/// [CPAL (Color Palette Table)](https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-table-header) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CpalMarker {
color_record_indices_byte_len: usize,
palette_types_array_offset_byte_start: Option<usize>,
palette_labels_array_offset_byte_start: Option<usize>,
palette_entry_labels_array_offset_byte_start: Option<usize>,
}
impl CpalMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_palette_entries_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_palettes_byte_range(&self) -> Range<usize> {
let start = self.num_palette_entries_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_color_records_byte_range(&self) -> Range<usize> {
let start = self.num_palettes_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn color_records_array_offset_byte_range(&self) -> Range<usize> {
let start = self.num_color_records_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn color_record_indices_byte_range(&self) -> Range<usize> {
let start = self.color_records_array_offset_byte_range().end;
start..start + self.color_record_indices_byte_len
}
pub fn palette_types_array_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.palette_types_array_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
pub fn palette_labels_array_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.palette_labels_array_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
pub fn palette_entry_labels_array_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.palette_entry_labels_array_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
}
impl MinByteRange for CpalMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.color_record_indices_byte_range().end
}
}
impl TopLevelTable for Cpal<'_> {
/// `CPAL`
const TAG: Tag = Tag::new(b"CPAL");
}
impl<'a> FontRead<'a> for Cpal<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: u16 = cursor.read()?;
cursor.advance::<u16>();
let num_palettes: u16 = cursor.read()?;
cursor.advance::<u16>();
cursor.advance::<Offset32>();
let color_record_indices_byte_len = (num_palettes as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(color_record_indices_byte_len);
let palette_types_array_offset_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
version
.compatible(1u16)
.then(|| cursor.advance::<Offset32>());
let palette_labels_array_offset_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
version
.compatible(1u16)
.then(|| cursor.advance::<Offset32>());
let palette_entry_labels_array_offset_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
version
.compatible(1u16)
.then(|| cursor.advance::<Offset32>());
cursor.finish(CpalMarker {
color_record_indices_byte_len,
palette_types_array_offset_byte_start,
palette_labels_array_offset_byte_start,
palette_entry_labels_array_offset_byte_start,
})
}
}
/// [CPAL (Color Palette Table)](https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-table-header) table
pub type Cpal<'a> = TableRef<'a, CpalMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Cpal<'a> {
/// Table version number (=0).
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of palette entries in each palette.
pub fn num_palette_entries(&self) -> u16 {
let range = self.shape.num_palette_entries_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of palettes in the table.
pub fn num_palettes(&self) -> u16 {
let range = self.shape.num_palettes_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Total number of color records, combined for all palettes.
pub fn num_color_records(&self) -> u16 {
let range = self.shape.num_color_records_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the beginning of CPAL table to the first
/// ColorRecord.
pub fn color_records_array_offset(&self) -> Nullable<Offset32> {
let range = self.shape.color_records_array_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`color_records_array_offset`][Self::color_records_array_offset].
pub fn color_records_array(&self) -> Option<Result<&'a [ColorRecord], ReadError>> {
let data = self.data;
let args = self.num_color_records();
self.color_records_array_offset()
.resolve_with_args(data, &args)
}
/// Index of each palette’s first color record in the combined
/// color record array.
pub fn color_record_indices(&self) -> &'a [BigEndian<u16>] {
let range = self.shape.color_record_indices_byte_range();
self.data.read_array(range).unwrap()
}
/// Offset from the beginning of CPAL table to the [Palette Types Array][].
///
/// This is an array of 32-bit flag fields that describe properties of each palette.
///
/// [Palette Types Array]: https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-type-array
pub fn palette_types_array_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.palette_types_array_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`palette_types_array_offset`][Self::palette_types_array_offset].
pub fn palette_types_array(&self) -> Option<Result<&'a [BigEndian<PaletteType>], ReadError>> {
let data = self.data;
let args = self.num_palettes();
self.palette_types_array_offset()
.map(|x| x.resolve_with_args(data, &args))?
}
/// Offset from the beginning of CPAL table to the [Palette Labels Array][].
///
/// This is an array of 'name' table IDs (typically in the font-specific name
/// ID range) that specify user interface strings associated with each palette.
/// Use 0xFFFF if no name ID is provided for a palette.
///
/// [Palette Labels Array]: https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-labels-array
pub fn palette_labels_array_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.palette_labels_array_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`palette_labels_array_offset`][Self::palette_labels_array_offset].
pub fn palette_labels_array(&self) -> Option<Result<&'a [BigEndian<u16>], ReadError>> {
let data = self.data;
let args = self.num_palettes();
self.palette_labels_array_offset()
.map(|x| x.resolve_with_args(data, &args))?
}
/// Offset from the beginning of CPAL table to the [Palette Entry Labels Array][].
///
/// This is an array of 'name' table IDs (typically in the font-specific name
/// ID range) that specify user interface strings associated with each palette
/// entry, e.g. “Outline”, “Fill”. This set of palette entry labels applies
/// to all palettes in the font. Use 0xFFFF if no name ID is provided for a
/// palette entry.
///
/// [Palette Entry Labels Array]: https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-entry-label-array
pub fn palette_entry_labels_array_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.palette_entry_labels_array_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`palette_entry_labels_array_offset`][Self::palette_entry_labels_array_offset].
pub fn palette_entry_labels_array(&self) -> Option<Result<&'a [BigEndian<NameId>], ReadError>> {
let data = self.data;
let args = self.num_palette_entries();
self.palette_entry_labels_array_offset()
.map(|x| x.resolve_with_args(data, &args))?
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cpal<'a> {
fn type_name(&self) -> &str {
"Cpal"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"num_palette_entries",
self.num_palette_entries(),
)),
2usize => Some(Field::new("num_palettes", self.num_palettes())),
3usize => Some(Field::new("num_color_records", self.num_color_records())),
4usize => Some(Field::new(
"color_records_array_offset",
traversal::FieldType::offset_to_array_of_records(
self.color_records_array_offset(),
self.color_records_array(),
stringify!(ColorRecord),
self.offset_data(),
),
)),
5usize => Some(Field::new(
"color_record_indices",
self.color_record_indices(),
)),
6usize if version.compatible(1u16) => Some(Field::new(
"palette_types_array_offset",
FieldType::offset_to_array_of_scalars(
self.palette_types_array_offset().unwrap(),
self.palette_types_array(),
),
)),
7usize if version.compatible(1u16) => Some(Field::new(
"palette_labels_array_offset",
FieldType::offset_to_array_of_scalars(
self.palette_labels_array_offset().unwrap(),
self.palette_labels_array(),
),
)),
8usize if version.compatible(1u16) => Some(Field::new(
"palette_entry_labels_array_offset",
FieldType::offset_to_array_of_scalars(
self.palette_entry_labels_array_offset().unwrap(),
self.palette_entry_labels_array(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cpal<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The [PaletteType](https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-type-array) flags.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct PaletteType {
bits: u32,
}
impl PaletteType {
/// Bit 0: palette is appropriate to use when displaying the font on a light background such as white.
pub const USABLE_WITH_LIGHT_BACKGROUND: Self = Self { bits: 0x0001 };
/// Bit 1: palette is appropriate to use when displaying the font on a dark background such as black.
pub const USABLE_WITH_DARK_BACKGROUND: Self = Self { bits: 0x0002 };
}
impl PaletteType {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::USABLE_WITH_LIGHT_BACKGROUND.bits | Self::USABLE_WITH_DARK_BACKGROUND.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u32 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u32) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u32) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for PaletteType {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: PaletteType) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for PaletteType {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for PaletteType {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for PaletteType {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for PaletteType {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for PaletteType {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for PaletteType {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for PaletteType {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for PaletteType {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for PaletteType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[
(
"USABLE_WITH_LIGHT_BACKGROUND",
Self::USABLE_WITH_LIGHT_BACKGROUND,
),
(
"USABLE_WITH_DARK_BACKGROUND",
Self::USABLE_WITH_DARK_BACKGROUND,
),
];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for PaletteType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for PaletteType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for PaletteType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for PaletteType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for PaletteType {
type Raw = <u32 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u32>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<PaletteType> for FieldType<'a> {
fn from(src: PaletteType) -> FieldType<'a> {
src.bits().into()
}
}
/// [CPAL (Color Record)](https://learn.microsoft.com/en-us/typography/opentype/spec/cpal#palette-entries-and-color-records) record
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct ColorRecord {
/// Blue value (B0).
pub blue: u8,
/// Green value (B1).
pub green: u8,
/// Red value (B2).
pub red: u8,
/// Alpha value (B3).
pub alpha: u8,
}
impl ColorRecord {
/// Blue value (B0).
pub fn blue(&self) -> u8 {
self.blue
}
/// Green value (B1).
pub fn green(&self) -> u8 {
self.green
}
/// Red value (B2).
pub fn red(&self) -> u8 {
self.red
}
/// Alpha value (B3).
pub fn alpha(&self) -> u8 {
self.alpha
}
}
impl FixedSize for ColorRecord {
const RAW_BYTE_LEN: usize =
u8::RAW_BYTE_LEN + u8::RAW_BYTE_LEN + u8::RAW_BYTE_LEN + u8::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ColorRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "ColorRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("blue", self.blue())),
1usize => Some(Field::new("green", self.green())),
2usize => Some(Field::new("red", self.red())),
3usize => Some(Field::new("alpha", self.alpha())),
_ => None,
}),
data,
}
}
}
+129
View File
@@ -0,0 +1,129 @@
// 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::*;
/// The [cvar](https://learn.microsoft.com/en-us/typography/opentype/spec/cvar) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CvarMarker {
tuple_variation_headers_byte_len: usize,
}
impl CvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn tuple_variation_count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + TupleVariationCount::RAW_BYTE_LEN
}
pub fn data_offset_byte_range(&self) -> Range<usize> {
let start = self.tuple_variation_count_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn tuple_variation_headers_byte_range(&self) -> Range<usize> {
let start = self.data_offset_byte_range().end;
start..start + self.tuple_variation_headers_byte_len
}
}
impl MinByteRange for CvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.tuple_variation_headers_byte_range().end
}
}
impl TopLevelTable for Cvar<'_> {
/// `cvar`
const TAG: Tag = Tag::new(b"cvar");
}
impl<'a> FontRead<'a> for Cvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<TupleVariationCount>();
cursor.advance::<Offset16>();
let tuple_variation_headers_byte_len = cursor.remaining_bytes();
cursor.advance_by(tuple_variation_headers_byte_len);
cursor.finish(CvarMarker {
tuple_variation_headers_byte_len,
})
}
}
/// The [cvar](https://learn.microsoft.com/en-us/typography/opentype/spec/cvar) table.
pub type Cvar<'a> = TableRef<'a, CvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Cvar<'a> {
/// Major/minor version number of the CVT variations table — set to (1,0).
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// A packed field. The high 4 bits are flags, and the low 12 bits
/// are the number of tuple variation tables for this glyph. The
/// number of tuple variation tables can be any number between 1
/// and 4095.
pub fn tuple_variation_count(&self) -> TupleVariationCount {
let range = self.shape.tuple_variation_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the start of the 'cvar' table to the serialized data.
pub fn data_offset(&self) -> Offset16 {
let range = self.shape.data_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`data_offset`][Self::data_offset].
pub fn data(&self) -> Result<FontData<'a>, ReadError> {
let data = self.data;
self.data_offset().resolve(data)
}
/// Array of tuple variation headers.
pub fn tuple_variation_headers(&self) -> VarLenArray<'a, TupleVariationHeader> {
let range = self.shape.tuple_variation_headers_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cvar<'a> {
fn type_name(&self) -> &str {
"Cvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"tuple_variation_count",
traversal::FieldType::Unknown,
)),
2usize => Some(Field::new("data_offset", traversal::FieldType::Unknown)),
3usize => Some(Field::new(
"tuple_variation_headers",
traversal::FieldType::Unknown,
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+83
View File
@@ -0,0 +1,83 @@
// 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::*;
/// The [Embedded Bitmap Data](https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct EbdtMarker {}
impl EbdtMarker {
pub fn major_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn minor_version_byte_range(&self) -> Range<usize> {
let start = self.major_version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for EbdtMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.minor_version_byte_range().end
}
}
impl TopLevelTable for Ebdt<'_> {
/// `EBDT`
const TAG: Tag = Tag::new(b"EBDT");
}
impl<'a> FontRead<'a> for Ebdt<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(EbdtMarker {})
}
}
/// The [Embedded Bitmap Data](https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt) table
pub type Ebdt<'a> = TableRef<'a, EbdtMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Ebdt<'a> {
/// Major version of the EBDT table, = 2.
pub fn major_version(&self) -> u16 {
let range = self.shape.major_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minor version of EBDT table, = 0.
pub fn minor_version(&self) -> u16 {
let range = self.shape.minor_version_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Ebdt<'a> {
fn type_name(&self) -> &str {
"Ebdt"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major_version", self.major_version())),
1usize => Some(Field::new("minor_version", self.minor_version())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Ebdt<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+123
View File
@@ -0,0 +1,123 @@
// 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::*;
/// The [Embedded Bitmap Location](https://learn.microsoft.com/en-us/typography/opentype/spec/eblc) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct EblcMarker {
bitmap_sizes_byte_len: usize,
}
impl EblcMarker {
pub fn major_version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn minor_version_byte_range(&self) -> Range<usize> {
let start = self.major_version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_sizes_byte_range(&self) -> Range<usize> {
let start = self.minor_version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn bitmap_sizes_byte_range(&self) -> Range<usize> {
let start = self.num_sizes_byte_range().end;
start..start + self.bitmap_sizes_byte_len
}
}
impl MinByteRange for EblcMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.bitmap_sizes_byte_range().end
}
}
impl TopLevelTable for Eblc<'_> {
/// `EBLC`
const TAG: Tag = Tag::new(b"EBLC");
}
impl<'a> FontRead<'a> for Eblc<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let num_sizes: u32 = cursor.read()?;
let bitmap_sizes_byte_len = (num_sizes as usize)
.checked_mul(BitmapSize::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(bitmap_sizes_byte_len);
cursor.finish(EblcMarker {
bitmap_sizes_byte_len,
})
}
}
/// The [Embedded Bitmap Location](https://learn.microsoft.com/en-us/typography/opentype/spec/eblc) table
pub type Eblc<'a> = TableRef<'a, EblcMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Eblc<'a> {
/// Major version of the EBLC table, = 2.
pub fn major_version(&self) -> u16 {
let range = self.shape.major_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minor version of EBLC table, = 0.
pub fn minor_version(&self) -> u16 {
let range = self.shape.minor_version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of BitmapSize records.
pub fn num_sizes(&self) -> u32 {
let range = self.shape.num_sizes_byte_range();
self.data.read_at(range.start).unwrap()
}
/// BitmapSize records array.
pub fn bitmap_sizes(&self) -> &'a [BitmapSize] {
let range = self.shape.bitmap_sizes_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Eblc<'a> {
fn type_name(&self) -> &str {
"Eblc"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("major_version", self.major_version())),
1usize => Some(Field::new("minor_version", self.minor_version())),
2usize => Some(Field::new("num_sizes", self.num_sizes())),
3usize => Some(Field::new(
"bitmap_sizes",
traversal::FieldType::array_of_records(
stringify!(BitmapSize),
self.bitmap_sizes(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Eblc<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+336
View File
@@ -0,0 +1,336 @@
// 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::*;
/// The [feature name](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6feat.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct FeatMarker {
names_byte_len: usize,
}
impl FeatMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn feature_name_count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn _reserved1_byte_range(&self) -> Range<usize> {
let start = self.feature_name_count_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn _reserved2_byte_range(&self) -> Range<usize> {
let start = self._reserved1_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn names_byte_range(&self) -> Range<usize> {
let start = self._reserved2_byte_range().end;
start..start + self.names_byte_len
}
}
impl MinByteRange for FeatMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.names_byte_range().end
}
}
impl TopLevelTable for Feat<'_> {
/// `feat`
const TAG: Tag = Tag::new(b"feat");
}
impl<'a> FontRead<'a> for Feat<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
let feature_name_count: u16 = cursor.read()?;
cursor.advance::<u16>();
cursor.advance::<u32>();
let names_byte_len = (feature_name_count as usize)
.checked_mul(FeatureName::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(names_byte_len);
cursor.finish(FeatMarker { names_byte_len })
}
}
/// The [feature name](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6feat.html) table.
pub type Feat<'a> = TableRef<'a, FeatMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Feat<'a> {
/// Version number of the feature name table (0x00010000 for the current
/// version).
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of entries in the feature name array.
pub fn feature_name_count(&self) -> u16 {
let range = self.shape.feature_name_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The feature name array, sorted by feature type.
pub fn names(&self) -> &'a [FeatureName] {
let range = self.shape.names_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Feat<'a> {
fn type_name(&self) -> &str {
"Feat"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("feature_name_count", self.feature_name_count())),
2usize => Some(Field::new(
"names",
traversal::FieldType::array_of_records(
stringify!(FeatureName),
self.names(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Feat<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Type, flags and names for a feature.
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct FeatureName {
/// Feature type.
pub feature: BigEndian<u16>,
/// The number of records in the setting name array.
pub n_settings: BigEndian<u16>,
/// Offset in bytes from the beginning of this table to this feature's
/// setting name array. The actual type of record this offset refers
/// to will depend on the exclusivity value, as described below.
pub setting_table_offset: BigEndian<Offset32>,
/// Flags associated with the feature type.
pub feature_flags: BigEndian<u16>,
/// The name table index for the feature's name.
pub name_index: BigEndian<NameId>,
}
impl FeatureName {
/// Feature type.
pub fn feature(&self) -> u16 {
self.feature.get()
}
/// The number of records in the setting name array.
pub fn n_settings(&self) -> u16 {
self.n_settings.get()
}
/// Offset in bytes from the beginning of this table to this feature's
/// setting name array. The actual type of record this offset refers
/// to will depend on the exclusivity value, as described below.
pub fn setting_table_offset(&self) -> Offset32 {
self.setting_table_offset.get()
}
/// Offset in bytes from the beginning of this table to this feature's
/// setting name array. The actual type of record this offset refers
/// to will depend on the exclusivity value, as described below.
///
/// The `data` argument should be retrieved from the parent table
/// By calling its `offset_data` method.
pub fn setting_table<'a>(&self, data: FontData<'a>) -> Result<SettingNameArray<'a>, ReadError> {
let args = self.n_settings();
self.setting_table_offset().resolve_with_args(data, &args)
}
/// Flags associated with the feature type.
pub fn feature_flags(&self) -> u16 {
self.feature_flags.get()
}
/// The name table index for the feature's name.
pub fn name_index(&self) -> NameId {
self.name_index.get()
}
}
impl FixedSize for FeatureName {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ Offset32::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ NameId::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for FeatureName {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "FeatureName",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("feature", self.feature())),
1usize => Some(Field::new("n_settings", self.n_settings())),
2usize => Some(Field::new(
"setting_table_offset",
FieldType::offset(self.setting_table_offset(), self.setting_table(_data)),
)),
3usize => Some(Field::new("feature_flags", self.feature_flags())),
4usize => Some(Field::new("name_index", self.name_index())),
_ => None,
}),
data,
}
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SettingNameArrayMarker {
settings_byte_len: usize,
}
impl SettingNameArrayMarker {
pub fn settings_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + self.settings_byte_len
}
}
impl MinByteRange for SettingNameArrayMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.settings_byte_range().end
}
}
impl ReadArgs for SettingNameArray<'_> {
type Args = u16;
}
impl<'a> FontReadWithArgs<'a> for SettingNameArray<'a> {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let n_settings = *args;
let mut cursor = data.cursor();
let settings_byte_len = (n_settings as usize)
.checked_mul(SettingName::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(settings_byte_len);
cursor.finish(SettingNameArrayMarker { settings_byte_len })
}
}
impl<'a> SettingNameArray<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(data: FontData<'a>, n_settings: u16) -> Result<Self, ReadError> {
let args = n_settings;
Self::read_with_args(data, &args)
}
}
pub type SettingNameArray<'a> = TableRef<'a, SettingNameArrayMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> SettingNameArray<'a> {
/// List of setting names for a feature.
pub fn settings(&self) -> &'a [SettingName] {
let range = self.shape.settings_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SettingNameArray<'a> {
fn type_name(&self) -> &str {
"SettingNameArray"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"settings",
traversal::FieldType::array_of_records(
stringify!(SettingName),
self.settings(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for SettingNameArray<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Associates a setting with a name identifier.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct SettingName {
/// The setting.
pub setting: BigEndian<u16>,
/// The name table index for the setting's name.
pub name_index: BigEndian<NameId>,
}
impl SettingName {
/// The setting.
pub fn setting(&self) -> u16 {
self.setting.get()
}
/// The name table index for the setting's name.
pub fn name_index(&self) -> NameId {
self.name_index.get()
}
}
impl FixedSize for SettingName {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + NameId::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SettingName {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "SettingName",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("setting", self.setting())),
1usize => Some(Field::new("name_index", self.name_index())),
_ => None,
}),
data,
}
}
}
+376
View File
@@ -0,0 +1,376 @@
// 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::*;
/// The [fvar (Font Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/fvar) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct FvarMarker {}
impl FvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn axis_instance_arrays_offset_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn _reserved_byte_range(&self) -> Range<usize> {
let start = self.axis_instance_arrays_offset_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn axis_count_byte_range(&self) -> Range<usize> {
let start = self._reserved_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn axis_size_byte_range(&self) -> Range<usize> {
let start = self.axis_count_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn instance_count_byte_range(&self) -> Range<usize> {
let start = self.axis_size_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn instance_size_byte_range(&self) -> Range<usize> {
let start = self.instance_count_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for FvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.instance_size_byte_range().end
}
}
impl TopLevelTable for Fvar<'_> {
/// `fvar`
const TAG: Tag = Tag::new(b"fvar");
}
impl<'a> FontRead<'a> for Fvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<Offset16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(FvarMarker {})
}
}
/// The [fvar (Font Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/fvar) table
pub type Fvar<'a> = TableRef<'a, FvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Fvar<'a> {
/// Major version number of the font variations table — set to 1.
/// Minor version number of the font variations table — set to 0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset in bytes from the beginning of the table to the start of the VariationAxisRecord array. The
/// InstanceRecord array directly follows.
pub fn axis_instance_arrays_offset(&self) -> Offset16 {
let range = self.shape.axis_instance_arrays_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`axis_instance_arrays_offset`][Self::axis_instance_arrays_offset].
pub fn axis_instance_arrays(&self) -> Result<AxisInstanceArrays<'a>, ReadError> {
let data = self.data;
let args = (
self.axis_count(),
self.instance_count(),
self.instance_size(),
);
self.axis_instance_arrays_offset()
.resolve_with_args(data, &args)
}
/// The number of variation axes in the font (the number of records in the axes array).
pub fn axis_count(&self) -> u16 {
let range = self.shape.axis_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The size in bytes of each VariationAxisRecord — set to 20 (0x0014) for this version.
pub fn axis_size(&self) -> u16 {
let range = self.shape.axis_size_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of named instances defined in the font (the number of records in the instances array).
pub fn instance_count(&self) -> u16 {
let range = self.shape.instance_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The size in bytes of each InstanceRecord — set to either axisCount * sizeof(Fixed) + 4, or to axisCount * sizeof(Fixed) + 6.
pub fn instance_size(&self) -> u16 {
let range = self.shape.instance_size_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Fvar<'a> {
fn type_name(&self) -> &str {
"Fvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"axis_instance_arrays_offset",
FieldType::offset(
self.axis_instance_arrays_offset(),
self.axis_instance_arrays(),
),
)),
2usize => Some(Field::new("axis_count", self.axis_count())),
3usize => Some(Field::new("axis_size", self.axis_size())),
4usize => Some(Field::new("instance_count", self.instance_count())),
5usize => Some(Field::new("instance_size", self.instance_size())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Fvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Shim table to handle combined axis and instance arrays.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct AxisInstanceArraysMarker {
axis_count: u16,
instance_size: u16,
axes_byte_len: usize,
instances_byte_len: usize,
}
impl AxisInstanceArraysMarker {
pub fn axes_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + self.axes_byte_len
}
pub fn instances_byte_range(&self) -> Range<usize> {
let start = self.axes_byte_range().end;
start..start + self.instances_byte_len
}
}
impl MinByteRange for AxisInstanceArraysMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.instances_byte_range().end
}
}
impl ReadArgs for AxisInstanceArrays<'_> {
type Args = (u16, u16, u16);
}
impl<'a> FontReadWithArgs<'a> for AxisInstanceArrays<'a> {
fn read_with_args(data: FontData<'a>, args: &(u16, u16, u16)) -> Result<Self, ReadError> {
let (axis_count, instance_count, instance_size) = *args;
let mut cursor = data.cursor();
let axes_byte_len = (axis_count as usize)
.checked_mul(VariationAxisRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(axes_byte_len);
let instances_byte_len = (instance_count as usize)
.checked_mul(<InstanceRecord as ComputeSize>::compute_size(&(
axis_count,
instance_size,
))?)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(instances_byte_len);
cursor.finish(AxisInstanceArraysMarker {
axis_count,
instance_size,
axes_byte_len,
instances_byte_len,
})
}
}
impl<'a> AxisInstanceArrays<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(
data: FontData<'a>,
axis_count: u16,
instance_count: u16,
instance_size: u16,
) -> Result<Self, ReadError> {
let args = (axis_count, instance_count, instance_size);
Self::read_with_args(data, &args)
}
}
/// Shim table to handle combined axis and instance arrays.
pub type AxisInstanceArrays<'a> = TableRef<'a, AxisInstanceArraysMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> AxisInstanceArrays<'a> {
/// Variation axis record array.
pub fn axes(&self) -> &'a [VariationAxisRecord] {
let range = self.shape.axes_byte_range();
self.data.read_array(range).unwrap()
}
/// Instance record array.
pub fn instances(&self) -> ComputedArray<'a, InstanceRecord<'a>> {
let range = self.shape.instances_byte_range();
self.data
.read_with_args(range, &(self.axis_count(), self.instance_size()))
.unwrap()
}
pub(crate) fn axis_count(&self) -> u16 {
self.shape.axis_count
}
pub(crate) fn instance_size(&self) -> u16 {
self.shape.instance_size
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for AxisInstanceArrays<'a> {
fn type_name(&self) -> &str {
"AxisInstanceArrays"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"axes",
traversal::FieldType::array_of_records(
stringify!(VariationAxisRecord),
self.axes(),
self.offset_data(),
),
)),
1usize => Some(Field::new(
"instances",
traversal::FieldType::computed_array(
"InstanceRecord",
self.instances(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for AxisInstanceArrays<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The [VariationAxisRecord](https://learn.microsoft.com/en-us/typography/opentype/spec/fvar#variationaxisrecord)
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct VariationAxisRecord {
/// Tag identifying the design variation for the axis.
pub axis_tag: BigEndian<Tag>,
/// The minimum coordinate value for the axis.
pub min_value: BigEndian<Fixed>,
/// The default coordinate value for the axis.
pub default_value: BigEndian<Fixed>,
/// The maximum coordinate value for the axis.
pub max_value: BigEndian<Fixed>,
/// Axis qualifiers — see details below.
pub flags: BigEndian<u16>,
/// The name ID for entries in the 'name' table that provide a display name for this axis.
pub axis_name_id: BigEndian<NameId>,
}
impl VariationAxisRecord {
/// Tag identifying the design variation for the axis.
pub fn axis_tag(&self) -> Tag {
self.axis_tag.get()
}
/// The minimum coordinate value for the axis.
pub fn min_value(&self) -> Fixed {
self.min_value.get()
}
/// The default coordinate value for the axis.
pub fn default_value(&self) -> Fixed {
self.default_value.get()
}
/// The maximum coordinate value for the axis.
pub fn max_value(&self) -> Fixed {
self.max_value.get()
}
/// Axis qualifiers — see details below.
pub fn flags(&self) -> u16 {
self.flags.get()
}
/// The name ID for entries in the 'name' table that provide a display name for this axis.
pub fn axis_name_id(&self) -> NameId {
self.axis_name_id.get()
}
}
impl FixedSize for VariationAxisRecord {
const RAW_BYTE_LEN: usize = Tag::RAW_BYTE_LEN
+ Fixed::RAW_BYTE_LEN
+ Fixed::RAW_BYTE_LEN
+ Fixed::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ NameId::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for VariationAxisRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "VariationAxisRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("axis_tag", self.axis_tag())),
1usize => Some(Field::new("min_value", self.min_value())),
2usize => Some(Field::new("default_value", self.default_value())),
3usize => Some(Field::new("max_value", self.max_value())),
4usize => Some(Field::new("flags", self.flags())),
5usize => Some(Field::new("axis_name_id", self.axis_name_id())),
_ => None,
}),
data,
}
}
}
+474
View File
@@ -0,0 +1,474 @@
// 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::*;
/// [gasp](https://learn.microsoft.com/en-us/typography/opentype/spec/gasp#gasp-table-formats)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GaspMarker {
gasp_ranges_byte_len: usize,
}
impl GaspMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_ranges_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn gasp_ranges_byte_range(&self) -> Range<usize> {
let start = self.num_ranges_byte_range().end;
start..start + self.gasp_ranges_byte_len
}
}
impl MinByteRange for GaspMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.gasp_ranges_byte_range().end
}
}
impl TopLevelTable for Gasp<'_> {
/// `gasp`
const TAG: Tag = Tag::new(b"gasp");
}
impl<'a> FontRead<'a> for Gasp<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
let num_ranges: u16 = cursor.read()?;
let gasp_ranges_byte_len = (num_ranges as usize)
.checked_mul(GaspRange::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(gasp_ranges_byte_len);
cursor.finish(GaspMarker {
gasp_ranges_byte_len,
})
}
}
/// [gasp](https://learn.microsoft.com/en-us/typography/opentype/spec/gasp#gasp-table-formats)
pub type Gasp<'a> = TableRef<'a, GaspMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Gasp<'a> {
/// Version number (set to 1)
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of records to follow
pub fn num_ranges(&self) -> u16 {
let range = self.shape.num_ranges_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Sorted by ppem
pub fn gasp_ranges(&self) -> &'a [GaspRange] {
let range = self.shape.gasp_ranges_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Gasp<'a> {
fn type_name(&self) -> &str {
"Gasp"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("num_ranges", self.num_ranges())),
2usize => Some(Field::new(
"gasp_ranges",
traversal::FieldType::array_of_records(
stringify!(GaspRange),
self.gasp_ranges(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Gasp<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct GaspRange {
/// Upper limit of range, in PPEM
pub range_max_ppem: BigEndian<u16>,
/// Flags describing desired rasterizer behavior.
pub range_gasp_behavior: BigEndian<GaspRangeBehavior>,
}
impl GaspRange {
/// Upper limit of range, in PPEM
pub fn range_max_ppem(&self) -> u16 {
self.range_max_ppem.get()
}
/// Flags describing desired rasterizer behavior.
pub fn range_gasp_behavior(&self) -> GaspRangeBehavior {
self.range_gasp_behavior.get()
}
}
impl FixedSize for GaspRange {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + GaspRangeBehavior::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for GaspRange {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "GaspRange",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("range_max_ppem", self.range_max_ppem())),
1usize => Some(Field::new(
"range_gasp_behavior",
self.range_gasp_behavior(),
)),
_ => None,
}),
data,
}
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct GaspRangeBehavior {
bits: u16,
}
impl GaspRangeBehavior {
/// Use gridfitting
pub const GASP_GRIDFIT: Self = Self { bits: 0x0001 };
/// Use grayscale rendering
pub const GASP_DOGRAY: Self = Self { bits: 0x0002 };
/// Use gridfitting with ClearType symmetric smoothing Only
/// supported in version 1 'gasp'
pub const GASP_SYMMETRIC_GRIDFIT: Self = Self { bits: 0x0004 };
/// Use smoothing along multiple axes with ClearType® Only
/// supported in version 1 'gasp'
pub const GASP_SYMMETRIC_SMOOTHING: Self = Self { bits: 0x0008 };
}
impl GaspRangeBehavior {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::GASP_GRIDFIT.bits
| Self::GASP_DOGRAY.bits
| Self::GASP_SYMMETRIC_GRIDFIT.bits
| Self::GASP_SYMMETRIC_SMOOTHING.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for GaspRangeBehavior {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: GaspRangeBehavior) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for GaspRangeBehavior {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for GaspRangeBehavior {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for GaspRangeBehavior {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for GaspRangeBehavior {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for GaspRangeBehavior {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for GaspRangeBehavior {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for GaspRangeBehavior {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for GaspRangeBehavior {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for GaspRangeBehavior {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[
("GASP_GRIDFIT", Self::GASP_GRIDFIT),
("GASP_DOGRAY", Self::GASP_DOGRAY),
("GASP_SYMMETRIC_GRIDFIT", Self::GASP_SYMMETRIC_GRIDFIT),
("GASP_SYMMETRIC_SMOOTHING", Self::GASP_SYMMETRIC_SMOOTHING),
];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for GaspRangeBehavior {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for GaspRangeBehavior {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for GaspRangeBehavior {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for GaspRangeBehavior {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for GaspRangeBehavior {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<GaspRangeBehavior> for FieldType<'a> {
fn from(src: GaspRangeBehavior) -> FieldType<'a> {
src.bits().into()
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+697
View File
@@ -0,0 +1,697 @@
// 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::*;
/// The ['gvar' header](https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#gvar-header)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GvarMarker {
glyph_variation_data_offsets_byte_len: usize,
}
impl GvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn axis_count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn shared_tuple_count_byte_range(&self) -> Range<usize> {
let start = self.axis_count_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn shared_tuples_offset_byte_range(&self) -> Range<usize> {
let start = self.shared_tuple_count_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn glyph_count_byte_range(&self) -> Range<usize> {
let start = self.shared_tuples_offset_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.glyph_count_byte_range().end;
start..start + GvarFlags::RAW_BYTE_LEN
}
pub fn glyph_variation_data_array_offset_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn glyph_variation_data_offsets_byte_range(&self) -> Range<usize> {
let start = self.glyph_variation_data_array_offset_byte_range().end;
start..start + self.glyph_variation_data_offsets_byte_len
}
}
impl MinByteRange for GvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.glyph_variation_data_offsets_byte_range().end
}
}
impl TopLevelTable for Gvar<'_> {
/// `gvar`
const TAG: Tag = Tag::new(b"gvar");
}
impl<'a> FontRead<'a> for Gvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<Offset32>();
let glyph_count: u16 = cursor.read()?;
let flags: GvarFlags = cursor.read()?;
cursor.advance::<u32>();
let glyph_variation_data_offsets_byte_len = (transforms::add(glyph_count, 1_usize))
.checked_mul(<U16Or32 as ComputeSize>::compute_size(&flags)?)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(glyph_variation_data_offsets_byte_len);
cursor.finish(GvarMarker {
glyph_variation_data_offsets_byte_len,
})
}
}
/// The ['gvar' header](https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#gvar-header)
pub type Gvar<'a> = TableRef<'a, GvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Gvar<'a> {
/// Major/minor version number of the glyph variations table — set to (1,0).
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of variation axes for this font. This must be the
/// same number as axisCount in the 'fvar' table.
pub fn axis_count(&self) -> u16 {
let range = self.shape.axis_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of shared tuple records. Shared tuple records can be
/// referenced within glyph variation data tables for multiple
/// glyphs, as opposed to other tuple records stored directly
/// within a glyph variation data table.
pub fn shared_tuple_count(&self) -> u16 {
let range = self.shape.shared_tuple_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the start of this table to the shared tuple records.
pub fn shared_tuples_offset(&self) -> Offset32 {
let range = self.shape.shared_tuples_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`shared_tuples_offset`][Self::shared_tuples_offset].
pub fn shared_tuples(&self) -> Result<SharedTuples<'a>, ReadError> {
let data = self.data;
let args = (self.shared_tuple_count(), self.axis_count());
self.shared_tuples_offset().resolve_with_args(data, &args)
}
/// The number of glyphs in this font. This must match the number
/// of glyphs stored elsewhere in the font.
pub fn glyph_count(&self) -> u16 {
let range = self.shape.glyph_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Bit-field that gives the format of the offset array that
/// follows. If bit 0 is clear, the offsets are uint16; if bit 0 is
/// set, the offsets are uint32.
pub fn flags(&self) -> GvarFlags {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the start of this table to the array of
/// GlyphVariationData tables.
pub fn glyph_variation_data_array_offset(&self) -> u32 {
let range = self.shape.glyph_variation_data_array_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offsets from the start of the GlyphVariationData array to each
/// GlyphVariationData table.
pub fn glyph_variation_data_offsets(&self) -> ComputedArray<'a, U16Or32> {
let range = self.shape.glyph_variation_data_offsets_byte_range();
self.data.read_with_args(range, &self.flags()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Gvar<'a> {
fn type_name(&self) -> &str {
"Gvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("axis_count", self.axis_count())),
2usize => Some(Field::new("shared_tuple_count", self.shared_tuple_count())),
3usize => Some(Field::new(
"shared_tuples_offset",
FieldType::offset(self.shared_tuples_offset(), self.shared_tuples()),
)),
4usize => Some(Field::new("glyph_count", self.glyph_count())),
5usize => Some(Field::new("flags", self.flags())),
6usize => Some(Field::new(
"glyph_variation_data_array_offset",
self.glyph_variation_data_array_offset(),
)),
7usize => Some(Field::new(
"glyph_variation_data_offsets",
traversal::FieldType::Unknown,
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Gvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct GvarFlags {
bits: u16,
}
impl GvarFlags {
/// If set, offsets to GlyphVariationData are 32 bits
pub const LONG_OFFSETS: Self = Self { bits: 1 };
}
impl GvarFlags {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::LONG_OFFSETS.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for GvarFlags {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: GvarFlags) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for GvarFlags {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for GvarFlags {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for GvarFlags {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for GvarFlags {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for GvarFlags {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for GvarFlags {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for GvarFlags {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for GvarFlags {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for GvarFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[("LONG_OFFSETS", Self::LONG_OFFSETS)];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for GvarFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for GvarFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for GvarFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for GvarFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for GvarFlags {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<GvarFlags> for FieldType<'a> {
fn from(src: GvarFlags) -> FieldType<'a> {
src.bits().into()
}
}
/// Array of tuple records shared across all glyph variation data tables.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SharedTuplesMarker {
axis_count: u16,
tuples_byte_len: usize,
}
impl SharedTuplesMarker {
pub fn tuples_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + self.tuples_byte_len
}
}
impl MinByteRange for SharedTuplesMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.tuples_byte_range().end
}
}
impl ReadArgs for SharedTuples<'_> {
type Args = (u16, u16);
}
impl<'a> FontReadWithArgs<'a> for SharedTuples<'a> {
fn read_with_args(data: FontData<'a>, args: &(u16, u16)) -> Result<Self, ReadError> {
let (shared_tuple_count, axis_count) = *args;
let mut cursor = data.cursor();
let tuples_byte_len = (shared_tuple_count as usize)
.checked_mul(<Tuple as ComputeSize>::compute_size(&axis_count)?)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(tuples_byte_len);
cursor.finish(SharedTuplesMarker {
axis_count,
tuples_byte_len,
})
}
}
impl<'a> SharedTuples<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(
data: FontData<'a>,
shared_tuple_count: u16,
axis_count: u16,
) -> Result<Self, ReadError> {
let args = (shared_tuple_count, axis_count);
Self::read_with_args(data, &args)
}
}
/// Array of tuple records shared across all glyph variation data tables.
pub type SharedTuples<'a> = TableRef<'a, SharedTuplesMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> SharedTuples<'a> {
pub fn tuples(&self) -> ComputedArray<'a, Tuple<'a>> {
let range = self.shape.tuples_byte_range();
self.data.read_with_args(range, &self.axis_count()).unwrap()
}
pub(crate) fn axis_count(&self) -> u16 {
self.shape.axis_count
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SharedTuples<'a> {
fn type_name(&self) -> &str {
"SharedTuples"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"tuples",
traversal::FieldType::computed_array("Tuple", self.tuples(), self.offset_data()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for SharedTuples<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The [GlyphVariationData](https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#the-glyphvariationdata-table-array) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GlyphVariationDataHeaderMarker {
tuple_variation_headers_byte_len: usize,
}
impl GlyphVariationDataHeaderMarker {
pub fn tuple_variation_count_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + TupleVariationCount::RAW_BYTE_LEN
}
pub fn serialized_data_offset_byte_range(&self) -> Range<usize> {
let start = self.tuple_variation_count_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn tuple_variation_headers_byte_range(&self) -> Range<usize> {
let start = self.serialized_data_offset_byte_range().end;
start..start + self.tuple_variation_headers_byte_len
}
}
impl MinByteRange for GlyphVariationDataHeaderMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.tuple_variation_headers_byte_range().end
}
}
impl<'a> FontRead<'a> for GlyphVariationDataHeader<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<TupleVariationCount>();
cursor.advance::<Offset16>();
let tuple_variation_headers_byte_len = cursor.remaining_bytes();
cursor.advance_by(tuple_variation_headers_byte_len);
cursor.finish(GlyphVariationDataHeaderMarker {
tuple_variation_headers_byte_len,
})
}
}
/// The [GlyphVariationData](https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#the-glyphvariationdata-table-array) table
pub type GlyphVariationDataHeader<'a> = TableRef<'a, GlyphVariationDataHeaderMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> GlyphVariationDataHeader<'a> {
/// A packed field. The high 4 bits are flags, and the low 12 bits
/// are the number of tuple variation tables for this glyph. The
/// number of tuple variation tables can be any number between 1
/// and 4095.
pub fn tuple_variation_count(&self) -> TupleVariationCount {
let range = self.shape.tuple_variation_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the start of the GlyphVariationData table to the
/// serialized data
pub fn serialized_data_offset(&self) -> Offset16 {
let range = self.shape.serialized_data_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`serialized_data_offset`][Self::serialized_data_offset].
pub fn serialized_data(&self) -> Result<FontData<'a>, ReadError> {
let data = self.data;
self.serialized_data_offset().resolve(data)
}
/// Array of tuple variation headers.
pub fn tuple_variation_headers(&self) -> VarLenArray<'a, TupleVariationHeader> {
let range = self.shape.tuple_variation_headers_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for GlyphVariationDataHeader<'a> {
fn type_name(&self) -> &str {
"GlyphVariationDataHeader"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"tuple_variation_count",
traversal::FieldType::Unknown,
)),
1usize => Some(Field::new(
"serialized_data_offset",
traversal::FieldType::Unknown,
)),
2usize => Some(Field::new(
"tuple_variation_headers",
traversal::FieldType::Unknown,
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for GlyphVariationDataHeader<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+150
View File
@@ -0,0 +1,150 @@
// 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::*;
/// The [Horizontal Device Metrics](https://learn.microsoft.com/en-us/typography/opentype/spec/hdmx) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HdmxMarker {
num_glyphs: u16,
records_byte_len: usize,
}
impl HdmxMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn num_records_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn size_device_record_byte_range(&self) -> Range<usize> {
let start = self.num_records_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn records_byte_range(&self) -> Range<usize> {
let start = self.size_device_record_byte_range().end;
start..start + self.records_byte_len
}
}
impl MinByteRange for HdmxMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.records_byte_range().end
}
}
impl TopLevelTable for Hdmx<'_> {
/// `hdmx`
const TAG: Tag = Tag::new(b"hdmx");
}
impl ReadArgs for Hdmx<'_> {
type Args = u16;
}
impl<'a> FontReadWithArgs<'a> for Hdmx<'a> {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let num_glyphs = *args;
let mut cursor = data.cursor();
cursor.advance::<u16>();
let num_records: u16 = cursor.read()?;
let size_device_record: u32 = cursor.read()?;
let records_byte_len = (num_records as usize)
.checked_mul(<DeviceRecord as ComputeSize>::compute_size(&(
num_glyphs,
size_device_record,
))?)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(records_byte_len);
cursor.finish(HdmxMarker {
num_glyphs,
records_byte_len,
})
}
}
impl<'a> Hdmx<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(data: FontData<'a>, num_glyphs: u16) -> Result<Self, ReadError> {
let args = num_glyphs;
Self::read_with_args(data, &args)
}
}
/// The [Horizontal Device Metrics](https://learn.microsoft.com/en-us/typography/opentype/spec/hdmx) table.
pub type Hdmx<'a> = TableRef<'a, HdmxMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Hdmx<'a> {
/// Table version number (set to 0).
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of device records.
pub fn num_records(&self) -> u16 {
let range = self.shape.num_records_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Size of device record, 32-bit aligned.
pub fn size_device_record(&self) -> u32 {
let range = self.shape.size_device_record_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Array of device records.
pub fn records(&self) -> ComputedArray<'a, DeviceRecord<'a>> {
let range = self.shape.records_byte_range();
self.data
.read_with_args(range, &(self.num_glyphs(), self.size_device_record()))
.unwrap()
}
pub(crate) fn num_glyphs(&self) -> u16 {
self.shape.num_glyphs
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hdmx<'a> {
fn type_name(&self) -> &str {
"Hdmx"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("num_records", self.num_records())),
2usize => Some(Field::new("size_device_record", self.size_device_record())),
3usize => Some(Field::new(
"records",
traversal::FieldType::computed_array(
"DeviceRecord",
self.records(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Hdmx<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+632
View File
@@ -0,0 +1,632 @@
// 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::*;
/// The `macStyle` field for the head table.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct MacStyle {
bits: u16,
}
impl MacStyle {
/// Bit 0: Bold (if set to 1)
pub const BOLD: Self = Self { bits: 0x0001 };
/// Bit 1: Italic (if set to 1)
pub const ITALIC: Self = Self { bits: 0x0002 };
/// Bit 2: Underline (if set to 1)
pub const UNDERLINE: Self = Self { bits: 0x0004 };
/// Bit 3: Outline (if set to 1)
pub const OUTLINE: Self = Self { bits: 0x0008 };
/// Bit 4: Shadow (if set to 1)
pub const SHADOW: Self = Self { bits: 0x0010 };
/// Bit 5: Condensed (if set to 1)
pub const CONDENSED: Self = Self { bits: 0x0020 };
/// Bit 6: Extended (if set to 1)
pub const EXTENDED: Self = Self { bits: 0x0040 };
}
impl MacStyle {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::BOLD.bits
| Self::ITALIC.bits
| Self::UNDERLINE.bits
| Self::OUTLINE.bits
| Self::SHADOW.bits
| Self::CONDENSED.bits
| Self::EXTENDED.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for MacStyle {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: MacStyle) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for MacStyle {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for MacStyle {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for MacStyle {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for MacStyle {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for MacStyle {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for MacStyle {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for MacStyle {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for MacStyle {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for MacStyle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[
("BOLD", Self::BOLD),
("ITALIC", Self::ITALIC),
("UNDERLINE", Self::UNDERLINE),
("OUTLINE", Self::OUTLINE),
("SHADOW", Self::SHADOW),
("CONDENSED", Self::CONDENSED),
("EXTENDED", Self::EXTENDED),
];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for MacStyle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for MacStyle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for MacStyle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for MacStyle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for MacStyle {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<MacStyle> for FieldType<'a> {
fn from(src: MacStyle) -> FieldType<'a> {
src.bits().into()
}
}
/// The [head](https://docs.microsoft.com/en-us/typography/opentype/spec/head)
/// (font header) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HeadMarker {}
impl HeadMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn font_revision_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Fixed::RAW_BYTE_LEN
}
pub fn checksum_adjustment_byte_range(&self) -> Range<usize> {
let start = self.font_revision_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn magic_number_byte_range(&self) -> Range<usize> {
let start = self.checksum_adjustment_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.magic_number_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn units_per_em_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn created_byte_range(&self) -> Range<usize> {
let start = self.units_per_em_byte_range().end;
start..start + LongDateTime::RAW_BYTE_LEN
}
pub fn modified_byte_range(&self) -> Range<usize> {
let start = self.created_byte_range().end;
start..start + LongDateTime::RAW_BYTE_LEN
}
pub fn x_min_byte_range(&self) -> Range<usize> {
let start = self.modified_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn y_min_byte_range(&self) -> Range<usize> {
let start = self.x_min_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn x_max_byte_range(&self) -> Range<usize> {
let start = self.y_min_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn y_max_byte_range(&self) -> Range<usize> {
let start = self.x_max_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn mac_style_byte_range(&self) -> Range<usize> {
let start = self.y_max_byte_range().end;
start..start + MacStyle::RAW_BYTE_LEN
}
pub fn lowest_rec_ppem_byte_range(&self) -> Range<usize> {
let start = self.mac_style_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn font_direction_hint_byte_range(&self) -> Range<usize> {
let start = self.lowest_rec_ppem_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn index_to_loc_format_byte_range(&self) -> Range<usize> {
let start = self.font_direction_hint_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn glyph_data_format_byte_range(&self) -> Range<usize> {
let start = self.index_to_loc_format_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
}
impl MinByteRange for HeadMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.glyph_data_format_byte_range().end
}
}
impl TopLevelTable for Head<'_> {
/// `head`
const TAG: Tag = Tag::new(b"head");
}
impl<'a> FontRead<'a> for Head<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<Fixed>();
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<LongDateTime>();
cursor.advance::<LongDateTime>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<MacStyle>();
cursor.advance::<u16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.finish(HeadMarker {})
}
}
/// The [head](https://docs.microsoft.com/en-us/typography/opentype/spec/head)
/// (font header) table.
pub type Head<'a> = TableRef<'a, HeadMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Head<'a> {
/// Version number of the font header table, set to (1, 0)
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Set by font manufacturer.
pub fn font_revision(&self) -> Fixed {
let range = self.shape.font_revision_byte_range();
self.data.read_at(range.start).unwrap()
}
/// To compute: set it to 0, sum the entire font as uint32, then
/// store 0xB1B0AFBA - sum. If the font is used as a component in a
/// font collection file, the value of this field will be
/// invalidated by changes to the file structure and font table
/// directory, and must be ignored.
pub fn checksum_adjustment(&self) -> u32 {
let range = self.shape.checksum_adjustment_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Set to 0x5F0F3CF5.
pub fn magic_number(&self) -> u32 {
let range = self.shape.magic_number_byte_range();
self.data.read_at(range.start).unwrap()
}
/// See the flags enum
pub fn flags(&self) -> u16 {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Set to a value from 16 to 16384. Any value in this range is
/// valid. In fonts that have TrueType outlines, a power of 2 is
/// recommended as this allows performance optimizations in some
/// rasterizers.
pub fn units_per_em(&self) -> u16 {
let range = self.shape.units_per_em_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of seconds since 12:00 midnight that started January 1st
/// 1904 in GMT/UTC time zone.
pub fn created(&self) -> LongDateTime {
let range = self.shape.created_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of seconds since 12:00 midnight that started January 1st
/// 1904 in GMT/UTC time zone.
pub fn modified(&self) -> LongDateTime {
let range = self.shape.modified_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum x coordinate across all glyph bounding boxes.
pub fn x_min(&self) -> i16 {
let range = self.shape.x_min_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum y coordinate across all glyph bounding boxes.
pub fn y_min(&self) -> i16 {
let range = self.shape.y_min_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum x coordinate across all glyph bounding boxes.
pub fn x_max(&self) -> i16 {
let range = self.shape.x_max_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum y coordinate across all glyph bounding boxes.
pub fn y_max(&self) -> i16 {
let range = self.shape.y_max_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Bits identifying the font's style; see [MacStyle]
pub fn mac_style(&self) -> MacStyle {
let range = self.shape.mac_style_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Smallest readable size in pixels.
pub fn lowest_rec_ppem(&self) -> u16 {
let range = self.shape.lowest_rec_ppem_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Deprecated (Set to 2).
pub fn font_direction_hint(&self) -> i16 {
let range = self.shape.font_direction_hint_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for short offsets (Offset16), 1 for long (Offset32).
pub fn index_to_loc_format(&self) -> i16 {
let range = self.shape.index_to_loc_format_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for current format.
pub fn glyph_data_format(&self) -> i16 {
let range = self.shape.glyph_data_format_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Head<'a> {
fn type_name(&self) -> &str {
"Head"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("font_revision", self.font_revision())),
2usize => Some(Field::new(
"checksum_adjustment",
self.checksum_adjustment(),
)),
3usize => Some(Field::new("magic_number", self.magic_number())),
4usize => Some(Field::new("flags", self.flags())),
5usize => Some(Field::new("units_per_em", self.units_per_em())),
6usize => Some(Field::new("created", self.created())),
7usize => Some(Field::new("modified", self.modified())),
8usize => Some(Field::new("x_min", self.x_min())),
9usize => Some(Field::new("y_min", self.y_min())),
10usize => Some(Field::new("x_max", self.x_max())),
11usize => Some(Field::new("y_max", self.y_max())),
12usize => Some(Field::new("mac_style", self.mac_style())),
13usize => Some(Field::new("lowest_rec_ppem", self.lowest_rec_ppem())),
14usize => Some(Field::new(
"font_direction_hint",
self.font_direction_hint(),
)),
15usize => Some(Field::new(
"index_to_loc_format",
self.index_to_loc_format(),
)),
16usize => Some(Field::new("glyph_data_format", self.glyph_data_format())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Head<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+265
View File
@@ -0,0 +1,265 @@
// 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::*;
/// [hhea](https://docs.microsoft.com/en-us/typography/opentype/spec/hhea) Horizontal Header Table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HheaMarker {}
impl HheaMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn ascender_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn descender_byte_range(&self) -> Range<usize> {
let start = self.ascender_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn line_gap_byte_range(&self) -> Range<usize> {
let start = self.descender_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn advance_width_max_byte_range(&self) -> Range<usize> {
let start = self.line_gap_byte_range().end;
start..start + UfWord::RAW_BYTE_LEN
}
pub fn min_left_side_bearing_byte_range(&self) -> Range<usize> {
let start = self.advance_width_max_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn min_right_side_bearing_byte_range(&self) -> Range<usize> {
let start = self.min_left_side_bearing_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn x_max_extent_byte_range(&self) -> Range<usize> {
let start = self.min_right_side_bearing_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn caret_slope_rise_byte_range(&self) -> Range<usize> {
let start = self.x_max_extent_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn caret_slope_run_byte_range(&self) -> Range<usize> {
let start = self.caret_slope_rise_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn caret_offset_byte_range(&self) -> Range<usize> {
let start = self.caret_slope_run_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved1_byte_range(&self) -> Range<usize> {
let start = self.caret_offset_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved2_byte_range(&self) -> Range<usize> {
let start = self.reserved1_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved3_byte_range(&self) -> Range<usize> {
let start = self.reserved2_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved4_byte_range(&self) -> Range<usize> {
let start = self.reserved3_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn metric_data_format_byte_range(&self) -> Range<usize> {
let start = self.reserved4_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn number_of_h_metrics_byte_range(&self) -> Range<usize> {
let start = self.metric_data_format_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for HheaMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.number_of_h_metrics_byte_range().end
}
}
impl TopLevelTable for Hhea<'_> {
/// `hhea`
const TAG: Tag = Tag::new(b"hhea");
}
impl<'a> FontRead<'a> for Hhea<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<UfWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<u16>();
cursor.finish(HheaMarker {})
}
}
/// [hhea](https://docs.microsoft.com/en-us/typography/opentype/spec/hhea) Horizontal Header Table
pub type Hhea<'a> = TableRef<'a, HheaMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Hhea<'a> {
/// The major/minor version (1, 0)
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic ascent.
pub fn ascender(&self) -> FWord {
let range = self.shape.ascender_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic descent.
pub fn descender(&self) -> FWord {
let range = self.shape.descender_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic line gap. Negative LineGap values are treated as
/// zero in some legacy platform implementations.
pub fn line_gap(&self) -> FWord {
let range = self.shape.line_gap_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum advance width value in 'hmtx' table.
pub fn advance_width_max(&self) -> UfWord {
let range = self.shape.advance_width_max_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum left sidebearing value in 'hmtx' table for glyphs with
/// contours (empty glyphs should be ignored).
pub fn min_left_side_bearing(&self) -> FWord {
let range = self.shape.min_left_side_bearing_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum right sidebearing value; calculated as min(aw - (lsb +
/// xMax - xMin)) for glyphs with contours (empty glyphs should be ignored).
pub fn min_right_side_bearing(&self) -> FWord {
let range = self.shape.min_right_side_bearing_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Max(lsb + (xMax-xMin))
pub fn x_max_extent(&self) -> FWord {
let range = self.shape.x_max_extent_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Used to calculate the slope of the cursor (rise/run); 1 for
/// vertical caret, 0 for horizontal.
pub fn caret_slope_rise(&self) -> i16 {
let range = self.shape.caret_slope_rise_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for vertical caret, 1 for horizontal.
pub fn caret_slope_run(&self) -> i16 {
let range = self.shape.caret_slope_run_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The amount by which a slanted highlight on a glyph needs to be
/// shifted to produce the best appearance. Set to 0 for
/// non-slanted fonts
pub fn caret_offset(&self) -> i16 {
let range = self.shape.caret_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for current format.
pub fn metric_data_format(&self) -> i16 {
let range = self.shape.metric_data_format_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of hMetric entries in 'hmtx' table
pub fn number_of_h_metrics(&self) -> u16 {
let range = self.shape.number_of_h_metrics_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hhea<'a> {
fn type_name(&self) -> &str {
"Hhea"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("ascender", self.ascender())),
2usize => Some(Field::new("descender", self.descender())),
3usize => Some(Field::new("line_gap", self.line_gap())),
4usize => Some(Field::new("advance_width_max", self.advance_width_max())),
5usize => Some(Field::new(
"min_left_side_bearing",
self.min_left_side_bearing(),
)),
6usize => Some(Field::new(
"min_right_side_bearing",
self.min_right_side_bearing(),
)),
7usize => Some(Field::new("x_max_extent", self.x_max_extent())),
8usize => Some(Field::new("caret_slope_rise", self.caret_slope_rise())),
9usize => Some(Field::new("caret_slope_run", self.caret_slope_run())),
10usize => Some(Field::new("caret_offset", self.caret_offset())),
11usize => Some(Field::new("metric_data_format", self.metric_data_format())),
12usize => Some(Field::new(
"number_of_h_metrics",
self.number_of_h_metrics(),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Hhea<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+165
View File
@@ -0,0 +1,165 @@
// 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::*;
/// The [hmtx (Horizontal Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HmtxMarker {
h_metrics_byte_len: usize,
left_side_bearings_byte_len: usize,
}
impl HmtxMarker {
pub fn h_metrics_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + self.h_metrics_byte_len
}
pub fn left_side_bearings_byte_range(&self) -> Range<usize> {
let start = self.h_metrics_byte_range().end;
start..start + self.left_side_bearings_byte_len
}
}
impl MinByteRange for HmtxMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.left_side_bearings_byte_range().end
}
}
impl TopLevelTable for Hmtx<'_> {
/// `hmtx`
const TAG: Tag = Tag::new(b"hmtx");
}
impl ReadArgs for Hmtx<'_> {
type Args = (u16, u16);
}
impl<'a> FontReadWithArgs<'a> for Hmtx<'a> {
fn read_with_args(data: FontData<'a>, args: &(u16, u16)) -> Result<Self, ReadError> {
let (number_of_h_metrics, num_glyphs) = *args;
let mut cursor = data.cursor();
let h_metrics_byte_len = (number_of_h_metrics as usize)
.checked_mul(LongMetric::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(h_metrics_byte_len);
let left_side_bearings_byte_len = (transforms::subtract(num_glyphs, number_of_h_metrics))
.checked_mul(i16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(left_side_bearings_byte_len);
cursor.finish(HmtxMarker {
h_metrics_byte_len,
left_side_bearings_byte_len,
})
}
}
impl<'a> Hmtx<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(
data: FontData<'a>,
number_of_h_metrics: u16,
num_glyphs: u16,
) -> Result<Self, ReadError> {
let args = (number_of_h_metrics, num_glyphs);
Self::read_with_args(data, &args)
}
}
/// The [hmtx (Horizontal Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx) table
pub type Hmtx<'a> = TableRef<'a, HmtxMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Hmtx<'a> {
/// Paired advance width/height and left/top side bearing values for each
/// glyph. Records are indexed by glyph ID.
pub fn h_metrics(&self) -> &'a [LongMetric] {
let range = self.shape.h_metrics_byte_range();
self.data.read_array(range).unwrap()
}
/// Leading (left/top) side bearings for glyph IDs greater than or equal to
/// numberOfLongMetrics.
pub fn left_side_bearings(&self) -> &'a [BigEndian<i16>] {
let range = self.shape.left_side_bearings_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hmtx<'a> {
fn type_name(&self) -> &str {
"Hmtx"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"h_metrics",
traversal::FieldType::array_of_records(
stringify!(LongMetric),
self.h_metrics(),
self.offset_data(),
),
)),
1usize => Some(Field::new("left_side_bearings", self.left_side_bearings())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Hmtx<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct LongMetric {
/// Advance width/height, in font design units.
pub advance: BigEndian<u16>,
/// Glyph leading (left/top) side bearing, in font design units.
pub side_bearing: BigEndian<i16>,
}
impl LongMetric {
/// Advance width/height, in font design units.
pub fn advance(&self) -> u16 {
self.advance.get()
}
/// Glyph leading (left/top) side bearing, in font design units.
pub fn side_bearing(&self) -> i16 {
self.side_bearing.get()
}
}
impl FixedSize for LongMetric {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for LongMetric {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "LongMetric",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("advance", self.advance())),
1usize => Some(Field::new("side_bearing", self.side_bearing())),
_ => None,
}),
data,
}
}
}
+165
View File
@@ -0,0 +1,165 @@
// 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::*;
/// The [HVAR (Horizontal Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/hvar) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HvarMarker {}
impl HvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn item_variation_store_offset_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn advance_width_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.item_variation_store_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn lsb_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.advance_width_mapping_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn rsb_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.lsb_mapping_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
}
impl MinByteRange for HvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.rsb_mapping_offset_byte_range().end
}
}
impl TopLevelTable for Hvar<'_> {
/// `HVAR`
const TAG: Tag = Tag::new(b"HVAR");
}
impl<'a> FontRead<'a> for Hvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.finish(HvarMarker {})
}
}
/// The [HVAR (Horizontal Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/hvar) table
pub type Hvar<'a> = TableRef<'a, HvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Hvar<'a> {
/// Major version number of the horizontal metrics variations table — set to 1.
/// Minor version number of the horizontal metrics variations table — set to 0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset in bytes from the start of this table to the item variation store table.
pub fn item_variation_store_offset(&self) -> Offset32 {
let range = self.shape.item_variation_store_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`item_variation_store_offset`][Self::item_variation_store_offset].
pub fn item_variation_store(&self) -> Result<ItemVariationStore<'a>, ReadError> {
let data = self.data;
self.item_variation_store_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for advance widths (may be NULL).
pub fn advance_width_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.advance_width_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`advance_width_mapping_offset`][Self::advance_width_mapping_offset].
pub fn advance_width_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.advance_width_mapping_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for left side bearings (may be NULL).
pub fn lsb_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.lsb_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`lsb_mapping_offset`][Self::lsb_mapping_offset].
pub fn lsb_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.lsb_mapping_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for right side bearings (may be NULL).
pub fn rsb_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.rsb_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`rsb_mapping_offset`][Self::rsb_mapping_offset].
pub fn rsb_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.rsb_mapping_offset().resolve(data)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hvar<'a> {
fn type_name(&self) -> &str {
"Hvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"item_variation_store_offset",
FieldType::offset(
self.item_variation_store_offset(),
self.item_variation_store(),
),
)),
2usize => Some(Field::new(
"advance_width_mapping_offset",
FieldType::offset(
self.advance_width_mapping_offset(),
self.advance_width_mapping(),
),
)),
3usize => Some(Field::new(
"lsb_mapping_offset",
FieldType::offset(self.lsb_mapping_offset(), self.lsb_mapping()),
)),
4usize => Some(Field::new(
"rsb_mapping_offset",
FieldType::offset(self.rsb_mapping_offset(), self.rsb_mapping()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Hvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
File diff suppressed because it is too large Load Diff
+787
View File
@@ -0,0 +1,787 @@
// 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::*;
/// The OpenType [kerning](https://learn.microsoft.com/en-us/typography/opentype/spec/kern) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct OtKernMarker {
subtable_data_byte_len: usize,
}
impl OtKernMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn n_tables_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn subtable_data_byte_range(&self) -> Range<usize> {
let start = self.n_tables_byte_range().end;
start..start + self.subtable_data_byte_len
}
}
impl MinByteRange for OtKernMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.subtable_data_byte_range().end
}
}
impl<'a> FontRead<'a> for OtKern<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let subtable_data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(subtable_data_byte_len);
cursor.finish(OtKernMarker {
subtable_data_byte_len,
})
}
}
/// The OpenType [kerning](https://learn.microsoft.com/en-us/typography/opentype/spec/kern) table.
pub type OtKern<'a> = TableRef<'a, OtKernMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> OtKern<'a> {
/// Table version number—set to 0.
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of subtables in the kerning table.
pub fn n_tables(&self) -> u16 {
let range = self.shape.n_tables_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Data for subtables, immediately following the header.
pub fn subtable_data(&self) -> &'a [u8] {
let range = self.shape.subtable_data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for OtKern<'a> {
fn type_name(&self) -> &str {
"OtKern"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("n_tables", self.n_tables())),
2usize => Some(Field::new("subtable_data", self.subtable_data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for OtKern<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The Apple Advanced Typography [kerning](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct AatKernMarker {
subtable_data_byte_len: usize,
}
impl AatKernMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn n_tables_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn subtable_data_byte_range(&self) -> Range<usize> {
let start = self.n_tables_byte_range().end;
start..start + self.subtable_data_byte_len
}
}
impl MinByteRange for AatKernMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.subtable_data_byte_range().end
}
}
impl<'a> FontRead<'a> for AatKern<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<u32>();
let subtable_data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(subtable_data_byte_len);
cursor.finish(AatKernMarker {
subtable_data_byte_len,
})
}
}
/// The Apple Advanced Typography [kerning](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html) table.
pub type AatKern<'a> = TableRef<'a, AatKernMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> AatKern<'a> {
/// The version number of the kerning table (0x00010000 for the current version).
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of subtables included in the kerning table.
pub fn n_tables(&self) -> u32 {
let range = self.shape.n_tables_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Data for subtables, immediately following the header.
pub fn subtable_data(&self) -> &'a [u8] {
let range = self.shape.subtable_data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for AatKern<'a> {
fn type_name(&self) -> &str {
"AatKern"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("n_tables", self.n_tables())),
2usize => Some(Field::new("subtable_data", self.subtable_data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for AatKern<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// A subtable in an OT `kern` table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct OtSubtableMarker {
data_byte_len: usize,
}
impl OtSubtableMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn length_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn coverage_byte_range(&self) -> Range<usize> {
let start = self.length_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.coverage_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for OtSubtableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for OtSubtable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
let data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(OtSubtableMarker { data_byte_len })
}
}
/// A subtable in an OT `kern` table.
pub type OtSubtable<'a> = TableRef<'a, OtSubtableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> OtSubtable<'a> {
/// Kern subtable version number-- set to 0.
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The length of this subtable in bytes, including this header.
pub fn length(&self) -> u16 {
let range = self.shape.length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Circumstances under which this table is used.
pub fn coverage(&self) -> u16 {
let range = self.shape.coverage_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Subtable specific data.
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for OtSubtable<'a> {
fn type_name(&self) -> &str {
"OtSubtable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("length", self.length())),
2usize => Some(Field::new("coverage", self.coverage())),
3usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for OtSubtable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// A subtable in an AAT `kern` table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct AatSubtableMarker {
data_byte_len: usize,
}
impl AatSubtableMarker {
pub fn length_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn coverage_byte_range(&self) -> Range<usize> {
let start = self.length_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn tuple_index_byte_range(&self) -> Range<usize> {
let start = self.coverage_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.tuple_index_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for AatSubtableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for AatSubtable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
cursor.advance::<u16>();
cursor.advance::<u16>();
let data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(AatSubtableMarker { data_byte_len })
}
}
/// A subtable in an AAT `kern` table.
pub type AatSubtable<'a> = TableRef<'a, AatSubtableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> AatSubtable<'a> {
/// The length of this subtable in bytes, including this header.
pub fn length(&self) -> u32 {
let range = self.shape.length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Circumstances under which this table is used.
pub fn coverage(&self) -> u16 {
let range = self.shape.coverage_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The tuple index (used for variations fonts). This value specifies which tuple this subtable covers.
pub fn tuple_index(&self) -> u16 {
let range = self.shape.tuple_index_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Subtable specific data.
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for AatSubtable<'a> {
fn type_name(&self) -> &str {
"AatSubtable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("coverage", self.coverage())),
2usize => Some(Field::new("tuple_index", self.tuple_index())),
3usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for AatSubtable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The type 0 `kern` subtable.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Subtable0Marker {
pairs_byte_len: usize,
}
impl Subtable0Marker {
pub fn n_pairs_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn search_range_byte_range(&self) -> Range<usize> {
let start = self.n_pairs_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn entry_selector_byte_range(&self) -> Range<usize> {
let start = self.search_range_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn range_shift_byte_range(&self) -> Range<usize> {
let start = self.entry_selector_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn pairs_byte_range(&self) -> Range<usize> {
let start = self.range_shift_byte_range().end;
start..start + self.pairs_byte_len
}
}
impl MinByteRange for Subtable0Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.pairs_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable0<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let n_pairs: u16 = cursor.read()?;
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.advance::<u16>();
let pairs_byte_len = (n_pairs as usize)
.checked_mul(Subtable0Pair::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(pairs_byte_len);
cursor.finish(Subtable0Marker { pairs_byte_len })
}
}
/// The type 0 `kern` subtable.
pub type Subtable0<'a> = TableRef<'a, Subtable0Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable0<'a> {
/// The number of kerning pairs in this subtable.
pub fn n_pairs(&self) -> u16 {
let range = self.shape.n_pairs_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The largest power of two less than or equal to the value of nPairs, multiplied by the size in bytes of an entry in the subtable.
pub fn search_range(&self) -> u16 {
let range = self.shape.search_range_byte_range();
self.data.read_at(range.start).unwrap()
}
/// This is calculated as log2 of the largest power of two less than or equal to the value of nPairs. This value indicates how many iterations of the search loop have to be made. For example, in a list of eight items, there would be three iterations of the loop.
pub fn entry_selector(&self) -> u16 {
let range = self.shape.entry_selector_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The value of nPairs minus the largest power of two less than or equal to nPairs. This is multiplied by the size in bytes of an entry in the table.
pub fn range_shift(&self) -> u16 {
let range = self.shape.range_shift_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Kerning records.
pub fn pairs(&self) -> &'a [Subtable0Pair] {
let range = self.shape.pairs_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable0<'a> {
fn type_name(&self) -> &str {
"Subtable0"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("n_pairs", self.n_pairs())),
1usize => Some(Field::new("search_range", self.search_range())),
2usize => Some(Field::new("entry_selector", self.entry_selector())),
3usize => Some(Field::new("range_shift", self.range_shift())),
4usize => Some(Field::new(
"pairs",
traversal::FieldType::array_of_records(
stringify!(Subtable0Pair),
self.pairs(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable0<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Class table for the type 2 `kern` subtable.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Subtable2ClassTableMarker {
offsets_byte_len: usize,
}
impl Subtable2ClassTableMarker {
pub fn first_glyph_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + GlyphId16::RAW_BYTE_LEN
}
pub fn n_glyphs_byte_range(&self) -> Range<usize> {
let start = self.first_glyph_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn offsets_byte_range(&self) -> Range<usize> {
let start = self.n_glyphs_byte_range().end;
start..start + self.offsets_byte_len
}
}
impl MinByteRange for Subtable2ClassTableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.offsets_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable2ClassTable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<GlyphId16>();
let n_glyphs: u16 = cursor.read()?;
let offsets_byte_len = (n_glyphs as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(offsets_byte_len);
cursor.finish(Subtable2ClassTableMarker { offsets_byte_len })
}
}
/// Class table for the type 2 `kern` subtable.
pub type Subtable2ClassTable<'a> = TableRef<'a, Subtable2ClassTableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable2ClassTable<'a> {
/// First glyph in class range.
pub fn first_glyph(&self) -> GlyphId16 {
let range = self.shape.first_glyph_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of glyph in class range.
pub fn n_glyphs(&self) -> u16 {
let range = self.shape.n_glyphs_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The offsets array for all of the glyphs in the range.
pub fn offsets(&self) -> &'a [BigEndian<u16>] {
let range = self.shape.offsets_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable2ClassTable<'a> {
fn type_name(&self) -> &str {
"Subtable2ClassTable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("first_glyph", self.first_glyph())),
1usize => Some(Field::new("n_glyphs", self.n_glyphs())),
2usize => Some(Field::new("offsets", self.offsets())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable2ClassTable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The type 3 'kern' subtable.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Subtable3Marker {
kern_value_byte_len: usize,
left_class_byte_len: usize,
right_class_byte_len: usize,
kern_index_byte_len: usize,
}
impl Subtable3Marker {
pub fn glyph_count_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn kern_value_count_byte_range(&self) -> Range<usize> {
let start = self.glyph_count_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn left_class_count_byte_range(&self) -> Range<usize> {
let start = self.kern_value_count_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn right_class_count_byte_range(&self) -> Range<usize> {
let start = self.left_class_count_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.right_class_count_byte_range().end;
start..start + u8::RAW_BYTE_LEN
}
pub fn kern_value_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + self.kern_value_byte_len
}
pub fn left_class_byte_range(&self) -> Range<usize> {
let start = self.kern_value_byte_range().end;
start..start + self.left_class_byte_len
}
pub fn right_class_byte_range(&self) -> Range<usize> {
let start = self.left_class_byte_range().end;
start..start + self.right_class_byte_len
}
pub fn kern_index_byte_range(&self) -> Range<usize> {
let start = self.right_class_byte_range().end;
start..start + self.kern_index_byte_len
}
}
impl MinByteRange for Subtable3Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.kern_index_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable3<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let glyph_count: u16 = cursor.read()?;
let kern_value_count: u8 = cursor.read()?;
let left_class_count: u8 = cursor.read()?;
let right_class_count: u8 = cursor.read()?;
cursor.advance::<u8>();
let kern_value_byte_len = (kern_value_count as usize)
.checked_mul(i16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(kern_value_byte_len);
let left_class_byte_len = (glyph_count as usize)
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(left_class_byte_len);
let right_class_byte_len = (glyph_count as usize)
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(right_class_byte_len);
let kern_index_byte_len =
(transforms::add_multiply(left_class_count, 0_usize, right_class_count))
.checked_mul(u8::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(kern_index_byte_len);
cursor.finish(Subtable3Marker {
kern_value_byte_len,
left_class_byte_len,
right_class_byte_len,
kern_index_byte_len,
})
}
}
/// The type 3 'kern' subtable.
pub type Subtable3<'a> = TableRef<'a, Subtable3Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable3<'a> {
/// The number of glyphs in this font.
pub fn glyph_count(&self) -> u16 {
let range = self.shape.glyph_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of kerning values.
pub fn kern_value_count(&self) -> u8 {
let range = self.shape.kern_value_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of left-hand classes.
pub fn left_class_count(&self) -> u8 {
let range = self.shape.left_class_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of right-hand classes.
pub fn right_class_count(&self) -> u8 {
let range = self.shape.right_class_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Set to zero (reserved for future use).
pub fn flags(&self) -> u8 {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The kerning values.
pub fn kern_value(&self) -> &'a [BigEndian<i16>] {
let range = self.shape.kern_value_byte_range();
self.data.read_array(range).unwrap()
}
/// The left-hand classes.
pub fn left_class(&self) -> &'a [u8] {
let range = self.shape.left_class_byte_range();
self.data.read_array(range).unwrap()
}
/// The right-hand classes.
pub fn right_class(&self) -> &'a [u8] {
let range = self.shape.right_class_byte_range();
self.data.read_array(range).unwrap()
}
/// The indices into the kernValue array.
pub fn kern_index(&self) -> &'a [u8] {
let range = self.shape.kern_index_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable3<'a> {
fn type_name(&self) -> &str {
"Subtable3"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("glyph_count", self.glyph_count())),
1usize => Some(Field::new("kern_value_count", self.kern_value_count())),
2usize => Some(Field::new("left_class_count", self.left_class_count())),
3usize => Some(Field::new("right_class_count", self.right_class_count())),
4usize => Some(Field::new("flags", self.flags())),
5usize => Some(Field::new("kern_value", self.kern_value())),
6usize => Some(Field::new("left_class", self.left_class())),
7usize => Some(Field::new("right_class", self.right_class())),
8usize => Some(Field::new("kern_index", self.kern_index())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable3<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+385
View File
@@ -0,0 +1,385 @@
// 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::*;
/// The [kerx (Extended Kerning)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct KerxMarker {
subtables_byte_len: usize,
}
impl KerxMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn padding_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn n_tables_byte_range(&self) -> Range<usize> {
let start = self.padding_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn subtables_byte_range(&self) -> Range<usize> {
let start = self.n_tables_byte_range().end;
start..start + self.subtables_byte_len
}
}
impl MinByteRange for KerxMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.subtables_byte_range().end
}
}
impl TopLevelTable for Kerx<'_> {
/// `kerx`
const TAG: Tag = Tag::new(b"kerx");
}
impl<'a> FontRead<'a> for Kerx<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let n_tables: u32 = cursor.read()?;
let subtables_byte_len = {
let data = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
<Subtable as VarSize>::total_len_for_count(data, n_tables as usize)?
};
cursor.advance_by(subtables_byte_len);
cursor.finish(KerxMarker { subtables_byte_len })
}
}
/// The [kerx (Extended Kerning)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html) table.
pub type Kerx<'a> = TableRef<'a, KerxMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Kerx<'a> {
/// The version number of the extended kerning table (currently 2, 3, or 4)
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of subtables included in the extended kerning table.
pub fn n_tables(&self) -> u32 {
let range = self.shape.n_tables_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn subtables(&self) -> VarLenArray<'a, Subtable<'a>> {
let range = self.shape.subtables_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Kerx<'a> {
fn type_name(&self) -> &str {
"Kerx"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("n_tables", self.n_tables())),
2usize => Some(Field::new(
"subtables",
traversal::FieldType::var_array("Subtable", self.subtables(), self.offset_data()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Kerx<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// A subtable in a `kerx` table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SubtableMarker {
data_byte_len: usize,
}
impl SubtableMarker {
pub fn length_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn coverage_byte_range(&self) -> Range<usize> {
let start = self.length_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn tuple_count_byte_range(&self) -> Range<usize> {
let start = self.coverage_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.tuple_count_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for SubtableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable<'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_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(SubtableMarker { data_byte_len })
}
}
/// A subtable in a `kerx` table.
pub type Subtable<'a> = TableRef<'a, SubtableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable<'a> {
/// The length of this subtable in bytes, including this header.
pub fn length(&self) -> u32 {
let range = self.shape.length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Circumstances under which this table is used.
pub fn coverage(&self) -> u32 {
let range = self.shape.coverage_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The tuple count. This value is only used with variation fonts and should be 0 for all other fonts. The subtable's tupleCount will be ignored if the 'kerx' table version is less than 4.
pub fn tuple_count(&self) -> u32 {
let range = self.shape.tuple_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Subtable specific data.
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable<'a> {
fn type_name(&self) -> &str {
"Subtable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("coverage", self.coverage())),
2usize => Some(Field::new("tuple_count", self.tuple_count())),
3usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The type 0 `kerx` subtable.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Subtable0Marker {
pairs_byte_len: usize,
}
impl Subtable0Marker {
pub fn n_pairs_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn search_range_byte_range(&self) -> Range<usize> {
let start = self.n_pairs_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn entry_selector_byte_range(&self) -> Range<usize> {
let start = self.search_range_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn range_shift_byte_range(&self) -> Range<usize> {
let start = self.entry_selector_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn pairs_byte_range(&self) -> Range<usize> {
let start = self.range_shift_byte_range().end;
start..start + self.pairs_byte_len
}
}
impl MinByteRange for Subtable0Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.pairs_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable0<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let n_pairs: u32 = cursor.read()?;
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u32>();
let pairs_byte_len = (n_pairs as usize)
.checked_mul(Subtable0Pair::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(pairs_byte_len);
cursor.finish(Subtable0Marker { pairs_byte_len })
}
}
/// The type 0 `kerx` subtable.
pub type Subtable0<'a> = TableRef<'a, Subtable0Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable0<'a> {
/// The number of kerning pairs in this subtable.
pub fn n_pairs(&self) -> u32 {
let range = self.shape.n_pairs_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The largest power of two less than or equal to the value of nPairs, multiplied by the size in bytes of an entry in the subtable.
pub fn search_range(&self) -> u32 {
let range = self.shape.search_range_byte_range();
self.data.read_at(range.start).unwrap()
}
/// This is calculated as log2 of the largest power of two less than or equal to the value of nPairs. This value indicates how many iterations of the search loop have to be made. For example, in a list of eight items, there would be three iterations of the loop.
pub fn entry_selector(&self) -> u32 {
let range = self.shape.entry_selector_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The value of nPairs minus the largest power of two less than or equal to nPairs. This is multiplied by the size in bytes of an entry in the table.
pub fn range_shift(&self) -> u32 {
let range = self.shape.range_shift_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Kerning records.
pub fn pairs(&self) -> &'a [Subtable0Pair] {
let range = self.shape.pairs_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable0<'a> {
fn type_name(&self) -> &str {
"Subtable0"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("n_pairs", self.n_pairs())),
1usize => Some(Field::new("search_range", self.search_range())),
2usize => Some(Field::new("entry_selector", self.entry_selector())),
3usize => Some(Field::new("range_shift", self.range_shift())),
4usize => Some(Field::new(
"pairs",
traversal::FieldType::array_of_records(
stringify!(Subtable0Pair),
self.pairs(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable0<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The type 0 `kerx` subtable kerning record.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct Subtable0Pair {
/// The glyph index for the lefthand glyph in the kerning pair.
pub left: BigEndian<GlyphId16>,
/// The glyph index for the righthand glyph in the kerning pair.
pub right: BigEndian<GlyphId16>,
/// Kerning value.
pub value: BigEndian<i16>,
}
impl Subtable0Pair {
/// The glyph index for the lefthand glyph in the kerning pair.
pub fn left(&self) -> GlyphId16 {
self.left.get()
}
/// The glyph index for the righthand glyph in the kerning pair.
pub fn right(&self) -> GlyphId16 {
self.right.get()
}
/// Kerning value.
pub fn value(&self) -> i16 {
self.value.get()
}
}
impl FixedSize for Subtable0Pair {
const RAW_BYTE_LEN: usize =
GlyphId16::RAW_BYTE_LEN + GlyphId16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for Subtable0Pair {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "Subtable0Pair",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("left", self.left())),
1usize => Some(Field::new("right", self.right())),
2usize => Some(Field::new("value", self.value())),
_ => None,
}),
data,
}
}
}
File diff suppressed because it is too large Load Diff
+165
View File
@@ -0,0 +1,165 @@
// 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::*;
/// The [language tag](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct LtagMarker {
tag_ranges_byte_len: usize,
}
impl LtagMarker {
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 num_tags_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn tag_ranges_byte_range(&self) -> Range<usize> {
let start = self.num_tags_byte_range().end;
start..start + self.tag_ranges_byte_len
}
}
impl MinByteRange for LtagMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.tag_ranges_byte_range().end
}
}
impl TopLevelTable for Ltag<'_> {
/// `ltag`
const TAG: Tag = Tag::new(b"ltag");
}
impl<'a> FontRead<'a> for Ltag<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
cursor.advance::<u32>();
let num_tags: u32 = cursor.read()?;
let tag_ranges_byte_len = (num_tags as usize)
.checked_mul(FTStringRange::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(tag_ranges_byte_len);
cursor.finish(LtagMarker {
tag_ranges_byte_len,
})
}
}
/// The [language tag](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html) table.
pub type Ltag<'a> = TableRef<'a, LtagMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Ltag<'a> {
/// Table version; currently 1.
pub fn version(&self) -> u32 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Table flags; currently none defined.
pub fn flags(&self) -> u32 {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of language tags which follow.
pub fn num_tags(&self) -> u32 {
let range = self.shape.num_tags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Range of each tag's string.
pub fn tag_ranges(&self) -> &'a [FTStringRange] {
let range = self.shape.tag_ranges_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Ltag<'a> {
fn type_name(&self) -> &str {
"Ltag"
}
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("num_tags", self.num_tags())),
3usize => Some(Field::new(
"tag_ranges",
traversal::FieldType::array_of_records(
stringify!(FTStringRange),
self.tag_ranges(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Ltag<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Offset and length of string in `ltag` table.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct FTStringRange {
/// Offset from the start of the table to the beginning of the string.
pub offset: BigEndian<u16>,
/// String length (in bytes).
pub length: BigEndian<u16>,
}
impl FTStringRange {
/// Offset from the start of the table to the beginning of the string.
pub fn offset(&self) -> u16 {
self.offset.get()
}
/// String length (in bytes).
pub fn length(&self) -> u16 {
self.length.get()
}
}
impl FixedSize for FTStringRange {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for FTStringRange {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "FTStringRange",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("offset", self.offset())),
1usize => Some(Field::new("length", self.length())),
_ => None,
}),
data,
}
}
}
+398
View File
@@ -0,0 +1,398 @@
// 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::*;
/// [`maxp`](https://docs.microsoft.com/en-us/typography/opentype/spec/maxp)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MaxpMarker {
max_points_byte_start: Option<usize>,
max_contours_byte_start: Option<usize>,
max_composite_points_byte_start: Option<usize>,
max_composite_contours_byte_start: Option<usize>,
max_zones_byte_start: Option<usize>,
max_twilight_points_byte_start: Option<usize>,
max_storage_byte_start: Option<usize>,
max_function_defs_byte_start: Option<usize>,
max_instruction_defs_byte_start: Option<usize>,
max_stack_elements_byte_start: Option<usize>,
max_size_of_instructions_byte_start: Option<usize>,
max_component_elements_byte_start: Option<usize>,
max_component_depth_byte_start: Option<usize>,
}
impl MaxpMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + Version16Dot16::RAW_BYTE_LEN
}
pub fn num_glyphs_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn max_points_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_points_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_contours_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_contours_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_composite_points_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_composite_points_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_composite_contours_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_composite_contours_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_zones_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_zones_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_twilight_points_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_twilight_points_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_storage_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_storage_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_function_defs_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_function_defs_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_instruction_defs_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_instruction_defs_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_stack_elements_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_stack_elements_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_size_of_instructions_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_size_of_instructions_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_component_elements_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_component_elements_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn max_component_depth_byte_range(&self) -> Option<Range<usize>> {
let start = self.max_component_depth_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
}
impl MinByteRange for MaxpMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.num_glyphs_byte_range().end
}
}
impl TopLevelTable for Maxp<'_> {
/// `maxp`
const TAG: Tag = Tag::new(b"maxp");
}
impl<'a> FontRead<'a> for Maxp<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: Version16Dot16 = cursor.read()?;
cursor.advance::<u16>();
let max_points_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_contours_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_composite_points_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_composite_contours_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_zones_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_twilight_points_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_storage_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_function_defs_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_instruction_defs_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_stack_elements_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_size_of_instructions_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_component_elements_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
let max_component_depth_byte_start = version
.compatible((1u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 0u16))
.then(|| cursor.advance::<u16>());
cursor.finish(MaxpMarker {
max_points_byte_start,
max_contours_byte_start,
max_composite_points_byte_start,
max_composite_contours_byte_start,
max_zones_byte_start,
max_twilight_points_byte_start,
max_storage_byte_start,
max_function_defs_byte_start,
max_instruction_defs_byte_start,
max_stack_elements_byte_start,
max_size_of_instructions_byte_start,
max_component_elements_byte_start,
max_component_depth_byte_start,
})
}
}
/// [`maxp`](https://docs.microsoft.com/en-us/typography/opentype/spec/maxp)
pub type Maxp<'a> = TableRef<'a, MaxpMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Maxp<'a> {
/// The version: 0x00005000 for version 0.5, 0x00010000 for version 1.0.
pub fn version(&self) -> Version16Dot16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of glyphs in the font.
pub fn num_glyphs(&self) -> u16 {
let range = self.shape.num_glyphs_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum points in a non-composite glyph.
pub fn max_points(&self) -> Option<u16> {
let range = self.shape.max_points_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum contours in a non-composite glyph.
pub fn max_contours(&self) -> Option<u16> {
let range = self.shape.max_contours_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum points in a composite glyph.
pub fn max_composite_points(&self) -> Option<u16> {
let range = self.shape.max_composite_points_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum contours in a composite glyph.
pub fn max_composite_contours(&self) -> Option<u16> {
let range = self.shape.max_composite_contours_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// 1 if instructions do not use the twilight zone (Z0), or 2 if
/// instructions do use Z0; should be set to 2 in most cases.
pub fn max_zones(&self) -> Option<u16> {
let range = self.shape.max_zones_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum points used in Z0.
pub fn max_twilight_points(&self) -> Option<u16> {
let range = self.shape.max_twilight_points_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Number of Storage Area locations.
pub fn max_storage(&self) -> Option<u16> {
let range = self.shape.max_storage_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Number of FDEFs, equal to the highest function number + 1.
pub fn max_function_defs(&self) -> Option<u16> {
let range = self.shape.max_function_defs_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Number of IDEFs.
pub fn max_instruction_defs(&self) -> Option<u16> {
let range = self.shape.max_instruction_defs_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum stack depth across Font Program ('fpgm' table), CVT
/// Program ('prep' table) and all glyph instructions (in the
/// 'glyf' table).
pub fn max_stack_elements(&self) -> Option<u16> {
let range = self.shape.max_stack_elements_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum byte count for glyph instructions.
pub fn max_size_of_instructions(&self) -> Option<u16> {
let range = self.shape.max_size_of_instructions_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum number of components referenced at “top level” for
/// any composite glyph.
pub fn max_component_elements(&self) -> Option<u16> {
let range = self.shape.max_component_elements_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Maximum levels of recursion; 1 for simple components.
pub fn max_component_depth(&self) -> Option<u16> {
let range = self.shape.max_component_depth_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Maxp<'a> {
fn type_name(&self) -> &str {
"Maxp"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("num_glyphs", self.num_glyphs())),
2usize if version.compatible((1u16, 0u16)) => {
Some(Field::new("max_points", self.max_points().unwrap()))
}
3usize if version.compatible((1u16, 0u16)) => {
Some(Field::new("max_contours", self.max_contours().unwrap()))
}
4usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_composite_points",
self.max_composite_points().unwrap(),
)),
5usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_composite_contours",
self.max_composite_contours().unwrap(),
)),
6usize if version.compatible((1u16, 0u16)) => {
Some(Field::new("max_zones", self.max_zones().unwrap()))
}
7usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_twilight_points",
self.max_twilight_points().unwrap(),
)),
8usize if version.compatible((1u16, 0u16)) => {
Some(Field::new("max_storage", self.max_storage().unwrap()))
}
9usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_function_defs",
self.max_function_defs().unwrap(),
)),
10usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_instruction_defs",
self.max_instruction_defs().unwrap(),
)),
11usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_stack_elements",
self.max_stack_elements().unwrap(),
)),
12usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_size_of_instructions",
self.max_size_of_instructions().unwrap(),
)),
13usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_component_elements",
self.max_component_elements().unwrap(),
)),
14usize if version.compatible((1u16, 0u16)) => Some(Field::new(
"max_component_depth",
self.max_component_depth().unwrap(),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Maxp<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+186
View File
@@ -0,0 +1,186 @@
// 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 MinByteRange for MetaMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_maps_byte_range().end
}
}
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>;
#[allow(clippy::needless_lifetimes)]
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")]
#[allow(clippy::needless_lifetimes)]
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,
}
}
}
+521
View File
@@ -0,0 +1,521 @@
// 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::*;
/// The [morx (Extended Glyph Metamorphosis)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MorxMarker {
chains_byte_len: usize,
}
impl MorxMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn unused_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn n_chains_byte_range(&self) -> Range<usize> {
let start = self.unused_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn chains_byte_range(&self) -> Range<usize> {
let start = self.n_chains_byte_range().end;
start..start + self.chains_byte_len
}
}
impl MinByteRange for MorxMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.chains_byte_range().end
}
}
impl TopLevelTable for Morx<'_> {
/// `morx`
const TAG: Tag = Tag::new(b"morx");
}
impl<'a> FontRead<'a> for Morx<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let n_chains: u32 = cursor.read()?;
let chains_byte_len = {
let data = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
<Chain as VarSize>::total_len_for_count(data, n_chains as usize)?
};
cursor.advance_by(chains_byte_len);
cursor.finish(MorxMarker { chains_byte_len })
}
}
/// The [morx (Extended Glyph Metamorphosis)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html) table.
pub type Morx<'a> = TableRef<'a, MorxMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Morx<'a> {
/// Version number of the extended glyph metamorphosis table (either 2 or 3).
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of metamorphosis chains contained in this table.
pub fn n_chains(&self) -> u32 {
let range = self.shape.n_chains_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn chains(&self) -> VarLenArray<'a, Chain<'a>> {
let range = self.shape.chains_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Morx<'a> {
fn type_name(&self) -> &str {
"Morx"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("n_chains", self.n_chains())),
2usize => Some(Field::new(
"chains",
traversal::FieldType::var_array("Chain", self.chains(), self.offset_data()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Morx<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// A chain in a `morx` table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct ChainMarker {
features_byte_len: usize,
subtables_byte_len: usize,
}
impl ChainMarker {
pub fn default_flags_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn chain_length_byte_range(&self) -> Range<usize> {
let start = self.default_flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn n_feature_entries_byte_range(&self) -> Range<usize> {
let start = self.chain_length_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn n_subtables_byte_range(&self) -> Range<usize> {
let start = self.n_feature_entries_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn features_byte_range(&self) -> Range<usize> {
let start = self.n_subtables_byte_range().end;
start..start + self.features_byte_len
}
pub fn subtables_byte_range(&self) -> Range<usize> {
let start = self.features_byte_range().end;
start..start + self.subtables_byte_len
}
}
impl MinByteRange for ChainMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.subtables_byte_range().end
}
}
impl<'a> FontRead<'a> for Chain<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
cursor.advance::<u32>();
let n_feature_entries: u32 = cursor.read()?;
let n_subtables: u32 = cursor.read()?;
let features_byte_len = (n_feature_entries as usize)
.checked_mul(Feature::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(features_byte_len);
let subtables_byte_len = {
let data = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
<Subtable as VarSize>::total_len_for_count(data, n_subtables as usize)?
};
cursor.advance_by(subtables_byte_len);
cursor.finish(ChainMarker {
features_byte_len,
subtables_byte_len,
})
}
}
/// A chain in a `morx` table.
pub type Chain<'a> = TableRef<'a, ChainMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Chain<'a> {
/// The default specification for subtables.
pub fn default_flags(&self) -> u32 {
let range = self.shape.default_flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Total byte count, including this header; must be a multiple of 4.
pub fn chain_length(&self) -> u32 {
let range = self.shape.chain_length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of feature subtable entries.
pub fn n_feature_entries(&self) -> u32 {
let range = self.shape.n_feature_entries_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of subtables in the chain.
pub fn n_subtables(&self) -> u32 {
let range = self.shape.n_subtables_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Feature entries for this chain.
pub fn features(&self) -> &'a [Feature] {
let range = self.shape.features_byte_range();
self.data.read_array(range).unwrap()
}
/// Array of chain subtables.
pub fn subtables(&self) -> VarLenArray<'a, Subtable<'a>> {
let range = self.shape.subtables_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Chain<'a> {
fn type_name(&self) -> &str {
"Chain"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("default_flags", self.default_flags())),
1usize => Some(Field::new("chain_length", self.chain_length())),
2usize => Some(Field::new("n_feature_entries", self.n_feature_entries())),
3usize => Some(Field::new("n_subtables", self.n_subtables())),
4usize => Some(Field::new(
"features",
traversal::FieldType::array_of_records(
stringify!(Feature),
self.features(),
self.offset_data(),
),
)),
5usize => Some(Field::new(
"subtables",
traversal::FieldType::var_array("Subtable", self.subtables(), self.offset_data()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Chain<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Used to compute the sub-feature flags for a list of requested features and settings.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct Feature {
/// The type of feature.
pub feature_type: BigEndian<u16>,
/// The feature's setting (aka selector).
pub feature_settings: BigEndian<u16>,
/// Flags for the settings that this feature and setting enables.
pub enable_flags: BigEndian<u32>,
/// Complement of flags for the settings that this feature and setting disable.
pub disable_flags: BigEndian<u32>,
}
impl Feature {
/// The type of feature.
pub fn feature_type(&self) -> u16 {
self.feature_type.get()
}
/// The feature's setting (aka selector).
pub fn feature_settings(&self) -> u16 {
self.feature_settings.get()
}
/// Flags for the settings that this feature and setting enables.
pub fn enable_flags(&self) -> u32 {
self.enable_flags.get()
}
/// Complement of flags for the settings that this feature and setting disable.
pub fn disable_flags(&self) -> u32 {
self.disable_flags.get()
}
}
impl FixedSize for Feature {
const RAW_BYTE_LEN: usize =
u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for Feature {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "Feature",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("feature_type", self.feature_type())),
1usize => Some(Field::new("feature_settings", self.feature_settings())),
2usize => Some(Field::new("enable_flags", self.enable_flags())),
3usize => Some(Field::new("disable_flags", self.disable_flags())),
_ => None,
}),
data,
}
}
}
/// A subtable in a `morx` chain.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SubtableMarker {
data_byte_len: usize,
}
impl SubtableMarker {
pub fn length_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn coverage_byte_range(&self) -> Range<usize> {
let start = self.length_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn sub_feature_flags_byte_range(&self) -> Range<usize> {
let start = self.coverage_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.sub_feature_flags_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for SubtableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for Subtable<'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_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(SubtableMarker { data_byte_len })
}
}
/// A subtable in a `morx` chain.
pub type Subtable<'a> = TableRef<'a, SubtableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Subtable<'a> {
/// Total subtable length, including this header.
pub fn length(&self) -> u32 {
let range = self.shape.length_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Coverage flags and subtable type.
pub fn coverage(&self) -> u32 {
let range = self.shape.coverage_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The 32-bit mask identifying which subtable this is (the subtable being executed if the AND of this value and the processed defaultFlags is nonzero).
pub fn sub_feature_flags(&self) -> u32 {
let range = self.shape.sub_feature_flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Data for specific subtable.
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Subtable<'a> {
fn type_name(&self) -> &str {
"Subtable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("coverage", self.coverage())),
2usize => Some(Field::new("sub_feature_flags", self.sub_feature_flags())),
3usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Subtable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Entry payload in a contextual subtable state machine.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct ContextualEntryData {
/// Index of the substitution table for the marked glyph (use 0xFFFF for
/// none).
pub mark_index: BigEndian<u16>,
/// Index of the substitution table for the current glyph (use 0xFFFF for
/// none)
pub current_index: BigEndian<u16>,
}
impl ContextualEntryData {
/// Index of the substitution table for the marked glyph (use 0xFFFF for
/// none).
pub fn mark_index(&self) -> u16 {
self.mark_index.get()
}
/// Index of the substitution table for the current glyph (use 0xFFFF for
/// none)
pub fn current_index(&self) -> u16 {
self.current_index.get()
}
}
impl FixedSize for ContextualEntryData {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ContextualEntryData {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "ContextualEntryData",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("mark_index", self.mark_index())),
1usize => Some(Field::new("current_index", self.current_index())),
_ => None,
}),
data,
}
}
}
/// Entry payload in an insertion subtable state machine.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct InsertionEntryData {
/// Zero-based index into the insertion glyph table. The number of glyphs
/// to be inserted is contained in the currentInsertCount field in the
/// flags (see below). A value of 0xFFFF indicates no insertion is to be done.
pub current_insert_index: BigEndian<u16>,
/// Zero-based index into the insertion glyph table. The number of glyphs
/// to be inserted is contained in the markedInsertCount field in the
/// flags (see below). A value of 0xFFFF indicates no insertion is to be
/// done.
pub marked_insert_index: BigEndian<u16>,
}
impl InsertionEntryData {
/// Zero-based index into the insertion glyph table. The number of glyphs
/// to be inserted is contained in the currentInsertCount field in the
/// flags (see below). A value of 0xFFFF indicates no insertion is to be done.
pub fn current_insert_index(&self) -> u16 {
self.current_insert_index.get()
}
/// Zero-based index into the insertion glyph table. The number of glyphs
/// to be inserted is contained in the markedInsertCount field in the
/// flags (see below). A value of 0xFFFF indicates no insertion is to be
/// done.
pub fn marked_insert_index(&self) -> u16 {
self.marked_insert_index.get()
}
}
impl FixedSize for InsertionEntryData {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for InsertionEntryData {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "InsertionEntryData",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new(
"current_insert_index",
self.current_insert_index(),
)),
1usize => Some(Field::new(
"marked_insert_index",
self.marked_insert_index(),
)),
_ => None,
}),
data,
}
}
}
+211
View File
@@ -0,0 +1,211 @@
// 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::*;
/// The [MVAR (Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/mvar) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MvarMarker {
value_records_byte_len: usize,
}
impl MvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn _reserved_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn value_record_size_byte_range(&self) -> Range<usize> {
let start = self._reserved_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn value_record_count_byte_range(&self) -> Range<usize> {
let start = self.value_record_size_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn item_variation_store_offset_byte_range(&self) -> Range<usize> {
let start = self.value_record_count_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn value_records_byte_range(&self) -> Range<usize> {
let start = self.item_variation_store_offset_byte_range().end;
start..start + self.value_records_byte_len
}
}
impl MinByteRange for MvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.value_records_byte_range().end
}
}
impl TopLevelTable for Mvar<'_> {
/// `MVAR`
const TAG: Tag = Tag::new(b"MVAR");
}
impl<'a> FontRead<'a> for Mvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<u16>();
cursor.advance::<u16>();
let value_record_count: u16 = cursor.read()?;
cursor.advance::<Offset16>();
let value_records_byte_len = (value_record_count as usize)
.checked_mul(ValueRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(value_records_byte_len);
cursor.finish(MvarMarker {
value_records_byte_len,
})
}
}
/// The [MVAR (Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/mvar) table
pub type Mvar<'a> = TableRef<'a, MvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Mvar<'a> {
/// Major version number of the horizontal metrics variations table — set to 1.
/// Minor version number of the horizontal metrics variations table — set to 0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The size in bytes of each value record — must be greater than zero.
pub fn value_record_size(&self) -> u16 {
let range = self.shape.value_record_size_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of value records — may be zero.
pub fn value_record_count(&self) -> u16 {
let range = self.shape.value_record_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset in bytes from the start of this table to the item variation store table. If valueRecordCount is zero, set to zero; if valueRecordCount is greater than zero, must be greater than zero.
pub fn item_variation_store_offset(&self) -> Nullable<Offset16> {
let range = self.shape.item_variation_store_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`item_variation_store_offset`][Self::item_variation_store_offset].
pub fn item_variation_store(&self) -> Option<Result<ItemVariationStore<'a>, ReadError>> {
let data = self.data;
self.item_variation_store_offset().resolve(data)
}
/// Array of value records that identify target items and the associated delta-set index for each. The valueTag records must be in binary order of their valueTag field.
pub fn value_records(&self) -> &'a [ValueRecord] {
let range = self.shape.value_records_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Mvar<'a> {
fn type_name(&self) -> &str {
"Mvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("value_record_size", self.value_record_size())),
2usize => Some(Field::new("value_record_count", self.value_record_count())),
3usize => Some(Field::new(
"item_variation_store_offset",
FieldType::offset(
self.item_variation_store_offset(),
self.item_variation_store(),
),
)),
4usize => Some(Field::new(
"value_records",
traversal::FieldType::array_of_records(
stringify!(ValueRecord),
self.value_records(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Mvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [ValueRecord](https://learn.microsoft.com/en-us/typography/opentype/spec/mvar#table-formats) metrics variation record
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct ValueRecord {
/// Four-byte tag identifying a font-wide measure.
pub value_tag: BigEndian<Tag>,
/// A delta-set outer index — used to select an item variation data subtable within the item variation store.
pub delta_set_outer_index: BigEndian<u16>,
/// A delta-set inner index — used to select a delta-set row within an item variation data subtable.
pub delta_set_inner_index: BigEndian<u16>,
}
impl ValueRecord {
/// Four-byte tag identifying a font-wide measure.
pub fn value_tag(&self) -> Tag {
self.value_tag.get()
}
/// A delta-set outer index — used to select an item variation data subtable within the item variation store.
pub fn delta_set_outer_index(&self) -> u16 {
self.delta_set_outer_index.get()
}
/// A delta-set inner index — used to select a delta-set row within an item variation data subtable.
pub fn delta_set_inner_index(&self) -> u16 {
self.delta_set_inner_index.get()
}
}
impl FixedSize for ValueRecord {
const RAW_BYTE_LEN: usize = Tag::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ValueRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "ValueRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("value_tag", self.value_tag())),
1usize => Some(Field::new(
"delta_set_outer_index",
self.delta_set_outer_index(),
)),
2usize => Some(Field::new(
"delta_set_inner_index",
self.delta_set_inner_index(),
)),
_ => None,
}),
data,
}
}
}
+307
View File
@@ -0,0 +1,307 @@
// 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::*;
/// [Naming table version 1](https://docs.microsoft.com/en-us/typography/opentype/spec/name#naming-table-version-1)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct NameMarker {
name_record_byte_len: usize,
lang_tag_count_byte_start: Option<usize>,
lang_tag_record_byte_start: Option<usize>,
lang_tag_record_byte_len: Option<usize>,
}
impl NameMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn storage_offset_byte_range(&self) -> Range<usize> {
let start = self.count_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn name_record_byte_range(&self) -> Range<usize> {
let start = self.storage_offset_byte_range().end;
start..start + self.name_record_byte_len
}
pub fn lang_tag_count_byte_range(&self) -> Option<Range<usize>> {
let start = self.lang_tag_count_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn lang_tag_record_byte_range(&self) -> Option<Range<usize>> {
let start = self.lang_tag_record_byte_start?;
Some(start..start + self.lang_tag_record_byte_len?)
}
}
impl MinByteRange for NameMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.name_record_byte_range().end
}
}
impl TopLevelTable for Name<'_> {
/// `name`
const TAG: Tag = Tag::new(b"name");
}
impl<'a> FontRead<'a> for Name<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: u16 = cursor.read()?;
let count: u16 = cursor.read()?;
cursor.advance::<u16>();
let name_record_byte_len = (count as usize)
.checked_mul(NameRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(name_record_byte_len);
let lang_tag_count_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
let lang_tag_count = version
.compatible(1u16)
.then(|| cursor.read::<u16>())
.transpose()?
.unwrap_or_default();
let lang_tag_record_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
let lang_tag_record_byte_len = version.compatible(1u16).then_some(
(lang_tag_count as usize)
.checked_mul(LangTagRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = lang_tag_record_byte_len {
cursor.advance_by(value);
}
cursor.finish(NameMarker {
name_record_byte_len,
lang_tag_count_byte_start,
lang_tag_record_byte_start,
lang_tag_record_byte_len,
})
}
}
/// [Naming table version 1](https://docs.microsoft.com/en-us/typography/opentype/spec/name#naming-table-version-1)
pub type Name<'a> = TableRef<'a, NameMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Name<'a> {
/// Table version number (0 or 1)
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of name records.
pub fn count(&self) -> u16 {
let range = self.shape.count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset to start of string storage (from start of table).
pub fn storage_offset(&self) -> u16 {
let range = self.shape.storage_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The name records where count is the number of records.
pub fn name_record(&self) -> &'a [NameRecord] {
let range = self.shape.name_record_byte_range();
self.data.read_array(range).unwrap()
}
/// Number of language-tag records.
pub fn lang_tag_count(&self) -> Option<u16> {
let range = self.shape.lang_tag_count_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// The language-tag records where langTagCount is the number of records.
pub fn lang_tag_record(&self) -> Option<&'a [LangTagRecord]> {
let range = self.shape.lang_tag_record_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Name<'a> {
fn type_name(&self) -> &str {
"Name"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("count", self.count())),
2usize => Some(Field::new("storage_offset", self.storage_offset())),
3usize => Some(Field::new(
"name_record",
traversal::FieldType::array_of_records(
stringify!(NameRecord),
self.name_record(),
self.string_data(),
),
)),
4usize if version.compatible(1u16) => {
Some(Field::new("lang_tag_count", self.lang_tag_count().unwrap()))
}
5usize if version.compatible(1u16) => Some(Field::new(
"lang_tag_record",
traversal::FieldType::array_of_records(
stringify!(LangTagRecord),
self.lang_tag_record().unwrap(),
self.string_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Name<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Part of [Name]
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct LangTagRecord {
/// Language-tag string length (in bytes)
pub length: BigEndian<u16>,
/// Language-tag string offset from start of storage area (in
/// bytes).
pub lang_tag_offset: BigEndian<Offset16>,
}
impl LangTagRecord {
/// Language-tag string length (in bytes)
pub fn length(&self) -> u16 {
self.length.get()
}
/// Language-tag string offset from start of storage area (in
/// bytes).
pub fn lang_tag_offset(&self) -> Offset16 {
self.lang_tag_offset.get()
}
}
impl FixedSize for LangTagRecord {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + Offset16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for LangTagRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "LangTagRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("lang_tag_offset", self.traverse_lang_tag(_data))),
_ => None,
}),
data,
}
}
}
///[Name Records](https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-records)
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct NameRecord {
/// Platform ID.
pub platform_id: BigEndian<u16>,
/// Platform-specific encoding ID.
pub encoding_id: BigEndian<u16>,
/// Language ID.
pub language_id: BigEndian<u16>,
/// Name ID.
pub name_id: BigEndian<NameId>,
/// String length (in bytes).
pub length: BigEndian<u16>,
/// String offset from start of storage area (in bytes).
pub string_offset: BigEndian<Offset16>,
}
impl NameRecord {
/// Platform ID.
pub fn platform_id(&self) -> u16 {
self.platform_id.get()
}
/// Platform-specific encoding ID.
pub fn encoding_id(&self) -> u16 {
self.encoding_id.get()
}
/// Language ID.
pub fn language_id(&self) -> u16 {
self.language_id.get()
}
/// Name ID.
pub fn name_id(&self) -> NameId {
self.name_id.get()
}
/// String length (in bytes).
pub fn length(&self) -> u16 {
self.length.get()
}
/// String offset from start of storage area (in bytes).
pub fn string_offset(&self) -> Offset16 {
self.string_offset.get()
}
}
impl FixedSize for NameRecord {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ NameId::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN
+ Offset16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for NameRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "NameRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("platform_id", self.platform_id())),
1usize => Some(Field::new("encoding_id", self.encoding_id())),
2usize => Some(Field::new("language_id", self.language_id())),
3usize => Some(Field::new("name_id", self.name_id())),
4usize => Some(Field::new("length", self.length())),
5usize => Some(Field::new("string_offset", self.traverse_string(_data))),
_ => None,
}),
data,
}
}
}
File diff suppressed because it is too large Load Diff
+281
View File
@@ -0,0 +1,281 @@
// 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::*;
/// [post (PostScript)](https://docs.microsoft.com/en-us/typography/opentype/spec/post#header) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct PostMarker {
num_glyphs_byte_start: Option<usize>,
glyph_name_index_byte_start: Option<usize>,
glyph_name_index_byte_len: Option<usize>,
string_data_byte_start: Option<usize>,
string_data_byte_len: Option<usize>,
}
impl PostMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + Version16Dot16::RAW_BYTE_LEN
}
pub fn italic_angle_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Fixed::RAW_BYTE_LEN
}
pub fn underline_position_byte_range(&self) -> Range<usize> {
let start = self.italic_angle_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn underline_thickness_byte_range(&self) -> Range<usize> {
let start = self.underline_position_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn is_fixed_pitch_byte_range(&self) -> Range<usize> {
let start = self.underline_thickness_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn min_mem_type42_byte_range(&self) -> Range<usize> {
let start = self.is_fixed_pitch_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn max_mem_type42_byte_range(&self) -> Range<usize> {
let start = self.min_mem_type42_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn min_mem_type1_byte_range(&self) -> Range<usize> {
let start = self.max_mem_type42_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn max_mem_type1_byte_range(&self) -> Range<usize> {
let start = self.min_mem_type1_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn num_glyphs_byte_range(&self) -> Option<Range<usize>> {
let start = self.num_glyphs_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn glyph_name_index_byte_range(&self) -> Option<Range<usize>> {
let start = self.glyph_name_index_byte_start?;
Some(start..start + self.glyph_name_index_byte_len?)
}
pub fn string_data_byte_range(&self) -> Option<Range<usize>> {
let start = self.string_data_byte_start?;
Some(start..start + self.string_data_byte_len?)
}
}
impl MinByteRange for PostMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.max_mem_type1_byte_range().end
}
}
impl TopLevelTable for Post<'_> {
/// `post`
const TAG: Tag = Tag::new(b"post");
}
impl<'a> FontRead<'a> for Post<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: Version16Dot16 = cursor.read()?;
cursor.advance::<Fixed>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u32>();
cursor.advance::<u32>();
let num_glyphs_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
let num_glyphs = version
.compatible((2u16, 0u16))
.then(|| cursor.read::<u16>())
.transpose()?
.unwrap_or_default();
let glyph_name_index_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
let glyph_name_index_byte_len = version.compatible((2u16, 0u16)).then_some(
(num_glyphs as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = glyph_name_index_byte_len {
cursor.advance_by(value);
}
let string_data_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
let string_data_byte_len = version
.compatible((2u16, 0u16))
.then_some(cursor.remaining_bytes());
if let Some(value) = string_data_byte_len {
cursor.advance_by(value);
}
cursor.finish(PostMarker {
num_glyphs_byte_start,
glyph_name_index_byte_start,
glyph_name_index_byte_len,
string_data_byte_start,
string_data_byte_len,
})
}
}
/// [post (PostScript)](https://docs.microsoft.com/en-us/typography/opentype/spec/post#header) table
pub type Post<'a> = TableRef<'a, PostMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Post<'a> {
/// 0x00010000 for version 1.0 0x00020000 for version 2.0
/// 0x00025000 for version 2.5 (deprecated) 0x00030000 for version
/// 3.0
pub fn version(&self) -> Version16Dot16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Italic angle in counter-clockwise degrees from the vertical.
/// Zero for upright text, negative for text that leans to the
/// right (forward).
pub fn italic_angle(&self) -> Fixed {
let range = self.shape.italic_angle_byte_range();
self.data.read_at(range.start).unwrap()
}
/// This is the suggested distance of the top of the underline from
/// the baseline (negative values indicate below baseline). The
/// PostScript definition of this FontInfo dictionary key (the y
/// coordinate of the center of the stroke) is not used for
/// historical reasons. The value of the PostScript key may be
/// calculated by subtracting half the underlineThickness from the
/// value of this field.
pub fn underline_position(&self) -> FWord {
let range = self.shape.underline_position_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Suggested values for the underline thickness. In general, the
/// underline thickness should match the thickness of the
/// underscore character (U+005F LOW LINE), and should also match
/// the strikeout thickness, which is specified in the OS/2 table.
pub fn underline_thickness(&self) -> FWord {
let range = self.shape.underline_thickness_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Set to 0 if the font is proportionally spaced, non-zero if the
/// font is not proportionally spaced (i.e. monospaced).
pub fn is_fixed_pitch(&self) -> u32 {
let range = self.shape.is_fixed_pitch_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum memory usage when an OpenType font is downloaded.
pub fn min_mem_type42(&self) -> u32 {
let range = self.shape.min_mem_type42_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum memory usage when an OpenType font is downloaded.
pub fn max_mem_type42(&self) -> u32 {
let range = self.shape.max_mem_type42_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum memory usage when an OpenType font is downloaded as a
/// Type 1 font.
pub fn min_mem_type1(&self) -> u32 {
let range = self.shape.min_mem_type1_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum memory usage when an OpenType font is downloaded as a
/// Type 1 font.
pub fn max_mem_type1(&self) -> u32 {
let range = self.shape.max_mem_type1_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of glyphs (this should be the same as numGlyphs in
/// 'maxp' table).
pub fn num_glyphs(&self) -> Option<u16> {
let range = self.shape.num_glyphs_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Array of indices into the string data. See below for details.
pub fn glyph_name_index(&self) -> Option<&'a [BigEndian<u16>]> {
let range = self.shape.glyph_name_index_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
/// Storage for the string data.
pub fn string_data(&self) -> Option<VarLenArray<'a, PString<'a>>> {
let range = self.shape.string_data_byte_range()?;
Some(VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Post<'a> {
fn type_name(&self) -> &str {
"Post"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("italic_angle", self.italic_angle())),
2usize => Some(Field::new("underline_position", self.underline_position())),
3usize => Some(Field::new(
"underline_thickness",
self.underline_thickness(),
)),
4usize => Some(Field::new("is_fixed_pitch", self.is_fixed_pitch())),
5usize => Some(Field::new("min_mem_type42", self.min_mem_type42())),
6usize => Some(Field::new("max_mem_type42", self.max_mem_type42())),
7usize => Some(Field::new("min_mem_type1", self.min_mem_type1())),
8usize => Some(Field::new("max_mem_type1", self.max_mem_type1())),
9usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("num_glyphs", self.num_glyphs().unwrap()))
}
10usize if version.compatible((2u16, 0u16)) => Some(Field::new(
"glyph_name_index",
self.glyph_name_index().unwrap(),
)),
11usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("string_data", self.traverse_string_data()))
}
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Post<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
File diff suppressed because it is too large Load Diff
+679
View File
@@ -0,0 +1,679 @@
// 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::*;
/// Sbix header flags.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct HeaderFlags {
bits: u16,
}
impl HeaderFlags {
/// Bit 0: Set to 1.
pub const ALWAYS_SET: Self = Self { bits: 0x0001 };
/// Bit 1: Draw outlines.
pub const DRAW_OUTLINES: Self = Self { bits: 0x0002 };
}
impl HeaderFlags {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::ALWAYS_SET.bits | Self::DRAW_OUTLINES.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for HeaderFlags {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: HeaderFlags) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for HeaderFlags {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for HeaderFlags {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for HeaderFlags {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for HeaderFlags {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for HeaderFlags {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for HeaderFlags {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for HeaderFlags {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for HeaderFlags {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for HeaderFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[
("ALWAYS_SET", Self::ALWAYS_SET),
("DRAW_OUTLINES", Self::DRAW_OUTLINES),
];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for HeaderFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for HeaderFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for HeaderFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for HeaderFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for HeaderFlags {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<HeaderFlags> for FieldType<'a> {
fn from(src: HeaderFlags) -> FieldType<'a> {
src.bits().into()
}
}
/// The [sbix (Standard Bitmap Graphics)](https://docs.microsoft.com/en-us/typography/opentype/spec/sbix) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SbixMarker {
num_glyphs: u16,
strike_offsets_byte_len: usize,
}
impl SbixMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + HeaderFlags::RAW_BYTE_LEN
}
pub fn num_strikes_byte_range(&self) -> Range<usize> {
let start = self.flags_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn strike_offsets_byte_range(&self) -> Range<usize> {
let start = self.num_strikes_byte_range().end;
start..start + self.strike_offsets_byte_len
}
}
impl MinByteRange for SbixMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.strike_offsets_byte_range().end
}
}
impl TopLevelTable for Sbix<'_> {
/// `sbix`
const TAG: Tag = Tag::new(b"sbix");
}
impl ReadArgs for Sbix<'_> {
type Args = u16;
}
impl<'a> FontReadWithArgs<'a> for Sbix<'a> {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let num_glyphs = *args;
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<HeaderFlags>();
let num_strikes: u32 = cursor.read()?;
let strike_offsets_byte_len = (num_strikes as usize)
.checked_mul(Offset32::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(strike_offsets_byte_len);
cursor.finish(SbixMarker {
num_glyphs,
strike_offsets_byte_len,
})
}
}
impl<'a> Sbix<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(data: FontData<'a>, num_glyphs: u16) -> Result<Self, ReadError> {
let args = num_glyphs;
Self::read_with_args(data, &args)
}
}
/// The [sbix (Standard Bitmap Graphics)](https://docs.microsoft.com/en-us/typography/opentype/spec/sbix) table
pub type Sbix<'a> = TableRef<'a, SbixMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Sbix<'a> {
/// Table version number — set to 1.
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Bit 0: Set to 1.
/// Bit 1: Draw outlines.
/// Bits 2 to 15: reserved (set to 0).
pub fn flags(&self) -> HeaderFlags {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of bitmap strikes.
pub fn num_strikes(&self) -> u32 {
let range = self.shape.num_strikes_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offsets from the beginning of the 'sbix' table to data for each individual bitmap strike.
pub fn strike_offsets(&self) -> &'a [BigEndian<Offset32>] {
let range = self.shape.strike_offsets_byte_range();
self.data.read_array(range).unwrap()
}
/// A dynamically resolving wrapper for [`strike_offsets`][Self::strike_offsets].
pub fn strikes(&self) -> ArrayOfOffsets<'a, Strike<'a>, Offset32> {
let data = self.data;
let offsets = self.strike_offsets();
let args = self.num_glyphs();
ArrayOfOffsets::new(offsets, data, args)
}
pub(crate) fn num_glyphs(&self) -> u16 {
self.shape.num_glyphs
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Sbix<'a> {
fn type_name(&self) -> &str {
"Sbix"
}
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("num_strikes", self.num_strikes())),
3usize => Some({
let data = self.data;
let args = self.num_glyphs();
Field::new(
"strike_offsets",
FieldType::array_of_offsets(
better_type_name::<Strike>(),
self.strike_offsets(),
move |off| {
let target = off.get().resolve_with_args::<Strike>(data, &args);
FieldType::offset(off.get(), target)
},
),
)
}),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Sbix<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [Strike](https://learn.microsoft.com/en-us/typography/opentype/spec/sbix#strikes) header table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct StrikeMarker {
glyph_data_offsets_byte_len: usize,
}
impl StrikeMarker {
pub fn ppem_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn ppi_byte_range(&self) -> Range<usize> {
let start = self.ppem_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn glyph_data_offsets_byte_range(&self) -> Range<usize> {
let start = self.ppi_byte_range().end;
start..start + self.glyph_data_offsets_byte_len
}
}
impl MinByteRange for StrikeMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.glyph_data_offsets_byte_range().end
}
}
impl ReadArgs for Strike<'_> {
type Args = u16;
}
impl<'a> FontReadWithArgs<'a> for Strike<'a> {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let num_glyphs = *args;
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
let glyph_data_offsets_byte_len = (transforms::add(num_glyphs, 1_usize))
.checked_mul(u32::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(glyph_data_offsets_byte_len);
cursor.finish(StrikeMarker {
glyph_data_offsets_byte_len,
})
}
}
impl<'a> Strike<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(data: FontData<'a>, num_glyphs: u16) -> Result<Self, ReadError> {
let args = num_glyphs;
Self::read_with_args(data, &args)
}
}
/// [Strike](https://learn.microsoft.com/en-us/typography/opentype/spec/sbix#strikes) header table
pub type Strike<'a> = TableRef<'a, StrikeMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Strike<'a> {
/// The PPEM size for which this strike was designed.
pub fn ppem(&self) -> u16 {
let range = self.shape.ppem_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The device pixel density (in PPI) for which this strike was designed. (E.g., 96 PPI, 192 PPI.)
pub fn ppi(&self) -> u16 {
let range = self.shape.ppi_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the beginning of the strike data header to bitmap data for an individual glyph ID.
pub fn glyph_data_offsets(&self) -> &'a [BigEndian<u32>] {
let range = self.shape.glyph_data_offsets_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Strike<'a> {
fn type_name(&self) -> &str {
"Strike"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("ppem", self.ppem())),
1usize => Some(Field::new("ppi", self.ppi())),
2usize => Some(Field::new("glyph_data_offsets", self.glyph_data_offsets())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Strike<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [Glyph data](https://learn.microsoft.com/en-us/typography/opentype/spec/sbix#glyph-data) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GlyphDataMarker {
data_byte_len: usize,
}
impl GlyphDataMarker {
pub fn origin_offset_x_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + i16::RAW_BYTE_LEN
}
pub fn origin_offset_y_byte_range(&self) -> Range<usize> {
let start = self.origin_offset_x_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn graphic_type_byte_range(&self) -> Range<usize> {
let start = self.origin_offset_y_byte_range().end;
start..start + Tag::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.graphic_type_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for GlyphDataMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for GlyphData<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<Tag>();
let data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(GlyphDataMarker { data_byte_len })
}
}
/// [Glyph data](https://learn.microsoft.com/en-us/typography/opentype/spec/sbix#glyph-data) table
pub type GlyphData<'a> = TableRef<'a, GlyphDataMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> GlyphData<'a> {
/// The horizontal (x-axis) position of the left edge of the bitmap graphic in relation to the glyph design space origin.
pub fn origin_offset_x(&self) -> i16 {
let range = self.shape.origin_offset_x_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The vertical (y-axis) position of the bottom edge of the bitmap graphic in relation to the glyph design space origin.
pub fn origin_offset_y(&self) -> i16 {
let range = self.shape.origin_offset_y_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Indicates the format of the embedded graphic data: one of 'jpg ', 'png ' or 'tiff', or the special format 'dupe'.
pub fn graphic_type(&self) -> Tag {
let range = self.shape.graphic_type_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The actual embedded graphic data. The total length is inferred from sequential entries in the glyphDataOffsets array and the fixed size (8 bytes) of the preceding fields.
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for GlyphData<'a> {
fn type_name(&self) -> &str {
"GlyphData"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("origin_offset_x", self.origin_offset_x())),
1usize => Some(Field::new("origin_offset_y", self.origin_offset_y())),
2usize => Some(Field::new("graphic_type", self.graphic_type())),
3usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for GlyphData<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
File diff suppressed because it is too large Load Diff
+246
View File
@@ -0,0 +1,246 @@
// 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::*;
/// The [SVG](https://learn.microsoft.com/en-us/typography/opentype/spec/svg) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SvgMarker {}
impl SvgMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn svg_document_list_offset_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn _reserved_byte_range(&self) -> Range<usize> {
let start = self.svg_document_list_offset_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for SvgMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self._reserved_byte_range().end
}
}
impl TopLevelTable for Svg<'_> {
/// `SVG `
const TAG: Tag = Tag::new(b"SVG ");
}
impl<'a> FontRead<'a> for Svg<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<Offset32>();
cursor.advance::<u16>();
cursor.finish(SvgMarker {})
}
}
/// The [SVG](https://learn.microsoft.com/en-us/typography/opentype/spec/svg) table
pub type Svg<'a> = TableRef<'a, SvgMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Svg<'a> {
/// Table version (starting at 0). Set to 0.
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset to the SVGDocumentList, from the start of the SVG table.
/// Must be non-zero.
pub fn svg_document_list_offset(&self) -> Offset32 {
let range = self.shape.svg_document_list_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`svg_document_list_offset`][Self::svg_document_list_offset].
pub fn svg_document_list(&self) -> Result<SVGDocumentList<'a>, ReadError> {
let data = self.data;
self.svg_document_list_offset().resolve(data)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Svg<'a> {
fn type_name(&self) -> &str {
"Svg"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"svg_document_list_offset",
FieldType::offset(self.svg_document_list_offset(), self.svg_document_list()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Svg<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [SVGDocumentList](https://learn.microsoft.com/en-us/typography/opentype/spec/svg)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SVGDocumentListMarker {
document_records_byte_len: usize,
}
impl SVGDocumentListMarker {
pub fn num_entries_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn document_records_byte_range(&self) -> Range<usize> {
let start = self.num_entries_byte_range().end;
start..start + self.document_records_byte_len
}
}
impl MinByteRange for SVGDocumentListMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.document_records_byte_range().end
}
}
impl<'a> FontRead<'a> for SVGDocumentList<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let num_entries: u16 = cursor.read()?;
let document_records_byte_len = (num_entries as usize)
.checked_mul(SVGDocumentRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(document_records_byte_len);
cursor.finish(SVGDocumentListMarker {
document_records_byte_len,
})
}
}
/// [SVGDocumentList](https://learn.microsoft.com/en-us/typography/opentype/spec/svg)
pub type SVGDocumentList<'a> = TableRef<'a, SVGDocumentListMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> SVGDocumentList<'a> {
/// Number of SVGDocumentRecords. Must be non-zero.
pub fn num_entries(&self) -> u16 {
let range = self.shape.num_entries_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Array of SVGDocumentRecords.
pub fn document_records(&self) -> &'a [SVGDocumentRecord] {
let range = self.shape.document_records_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SVGDocumentList<'a> {
fn type_name(&self) -> &str {
"SVGDocumentList"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("num_entries", self.num_entries())),
1usize => Some(Field::new(
"document_records",
traversal::FieldType::array_of_records(
stringify!(SVGDocumentRecord),
self.document_records(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for SVGDocumentList<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// [SVGDocumentRecord](https://learn.microsoft.com/en-us/typography/opentype/spec/svg)
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct SVGDocumentRecord {
/// The first glyph ID for the range covered by this record.
pub start_glyph_id: BigEndian<GlyphId16>,
/// The last glyph ID for the range covered by this record.
pub end_glyph_id: BigEndian<GlyphId16>,
/// Offset from the beginning of the SVGDocumentList to an SVG
/// document. Must be non-zero.
pub svg_doc_offset: BigEndian<u32>,
/// Length of the SVG document data. Must be non-zero.
pub svg_doc_length: BigEndian<u32>,
}
impl SVGDocumentRecord {
/// The first glyph ID for the range covered by this record.
pub fn start_glyph_id(&self) -> GlyphId16 {
self.start_glyph_id.get()
}
/// The last glyph ID for the range covered by this record.
pub fn end_glyph_id(&self) -> GlyphId16 {
self.end_glyph_id.get()
}
/// Offset from the beginning of the SVGDocumentList to an SVG
/// document. Must be non-zero.
pub fn svg_doc_offset(&self) -> u32 {
self.svg_doc_offset.get()
}
/// Length of the SVG document data. Must be non-zero.
pub fn svg_doc_length(&self) -> u32 {
self.svg_doc_length.get()
}
}
impl FixedSize for SVGDocumentRecord {
const RAW_BYTE_LEN: usize =
GlyphId16::RAW_BYTE_LEN + GlyphId16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SVGDocumentRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "SVGDocumentRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("start_glyph_id", self.start_glyph_id())),
1usize => Some(Field::new("end_glyph_id", self.end_glyph_id())),
2usize => Some(Field::new("svg_doc_offset", self.svg_doc_offset())),
3usize => Some(Field::new("svg_doc_length", self.svg_doc_length())),
_ => None,
}),
data,
}
}
}
+724
View File
@@ -0,0 +1,724 @@
// 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::*;
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MajorMinorVersionMarker {
if_11_byte_start: Option<usize>,
if_20_byte_start: Option<usize>,
}
impl MajorMinorVersionMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn always_present_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn if_11_byte_range(&self) -> Option<Range<usize>> {
let start = self.if_11_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn if_20_byte_range(&self) -> Option<Range<usize>> {
let start = self.if_20_byte_start?;
Some(start..start + u32::RAW_BYTE_LEN)
}
}
impl MinByteRange for MajorMinorVersionMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.always_present_byte_range().end
}
}
impl<'a> FontRead<'a> for MajorMinorVersion<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: MajorMinor = cursor.read()?;
cursor.advance::<u16>();
let if_11_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 1u16))
.then(|| cursor.advance::<u16>());
let if_20_byte_start = version
.compatible((2u16, 0u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((2u16, 0u16))
.then(|| cursor.advance::<u32>());
cursor.finish(MajorMinorVersionMarker {
if_11_byte_start,
if_20_byte_start,
})
}
}
pub type MajorMinorVersion<'a> = TableRef<'a, MajorMinorVersionMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> MajorMinorVersion<'a> {
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn always_present(&self) -> u16 {
let range = self.shape.always_present_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn if_11(&self) -> Option<u16> {
let range = self.shape.if_11_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn if_20(&self) -> Option<u32> {
let range = self.shape.if_20_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for MajorMinorVersion<'a> {
fn type_name(&self) -> &str {
"MajorMinorVersion"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("always_present", self.always_present())),
2usize if version.compatible((1u16, 1u16)) => {
Some(Field::new("if_11", self.if_11().unwrap()))
}
3usize if version.compatible((2u16, 0u16)) => {
Some(Field::new("if_20", self.if_20().unwrap()))
}
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for MajorMinorVersion<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct GotFlags {
bits: u16,
}
impl GotFlags {
pub const FOO: Self = Self { bits: 0x0001 };
pub const BAR: Self = Self { bits: 0x0002 };
pub const BAZ: Self = Self { bits: 0x0004 };
}
impl GotFlags {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::FOO.bits | Self::BAR.bits | Self::BAZ.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for GotFlags {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: GotFlags) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for GotFlags {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for GotFlags {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for GotFlags {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for GotFlags {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for GotFlags {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for GotFlags {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for GotFlags {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for GotFlags {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for GotFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] =
&[("FOO", Self::FOO), ("BAR", Self::BAR), ("BAZ", Self::BAZ)];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for GotFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for GotFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for GotFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for GotFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for GotFlags {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<GotFlags> for FieldType<'a> {
fn from(src: GotFlags) -> FieldType<'a> {
src.bits().into()
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct FlagDayMarker {
foo_byte_start: Option<usize>,
bar_byte_start: Option<usize>,
baz_byte_start: Option<usize>,
}
impl FlagDayMarker {
pub fn volume_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn flags_byte_range(&self) -> Range<usize> {
let start = self.volume_byte_range().end;
start..start + GotFlags::RAW_BYTE_LEN
}
pub fn foo_byte_range(&self) -> Option<Range<usize>> {
let start = self.foo_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn bar_byte_range(&self) -> Option<Range<usize>> {
let start = self.bar_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn baz_byte_range(&self) -> Option<Range<usize>> {
let start = self.baz_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
}
impl MinByteRange for FlagDayMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.flags_byte_range().end
}
}
impl<'a> FontRead<'a> for FlagDay<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
let flags: GotFlags = cursor.read()?;
let foo_byte_start = flags
.contains(GotFlags::FOO)
.then(|| cursor.position())
.transpose()?;
flags
.contains(GotFlags::FOO)
.then(|| cursor.advance::<u16>());
let bar_byte_start = flags
.contains(GotFlags::BAR)
.then(|| cursor.position())
.transpose()?;
flags
.contains(GotFlags::BAR)
.then(|| cursor.advance::<u16>());
let baz_byte_start = flags
.intersects(GotFlags::BAZ | GotFlags::FOO)
.then(|| cursor.position())
.transpose()?;
flags
.intersects(GotFlags::BAZ | GotFlags::FOO)
.then(|| cursor.advance::<u16>());
cursor.finish(FlagDayMarker {
foo_byte_start,
bar_byte_start,
baz_byte_start,
})
}
}
pub type FlagDay<'a> = TableRef<'a, FlagDayMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> FlagDay<'a> {
pub fn volume(&self) -> u16 {
let range = self.shape.volume_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn flags(&self) -> GotFlags {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn foo(&self) -> Option<u16> {
let range = self.shape.foo_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn bar(&self) -> Option<u16> {
let range = self.shape.bar_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn baz(&self) -> Option<u16> {
let range = self.shape.baz_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for FlagDay<'a> {
fn type_name(&self) -> &str {
"FlagDay"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let flags = self.flags();
match idx {
0usize => Some(Field::new("volume", self.volume())),
1usize => Some(Field::new("flags", self.flags())),
2usize if flags.contains(GotFlags::FOO) => Some(Field::new("foo", self.foo().unwrap())),
3usize if flags.contains(GotFlags::BAR) => Some(Field::new("bar", self.bar().unwrap())),
4usize if flags.intersects(GotFlags::BAZ | GotFlags::FOO) => {
Some(Field::new("baz", self.baz().unwrap()))
}
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for FlagDay<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct FieldsAfterConditionalsMarker {
foo_byte_start: Option<usize>,
bar_byte_start: Option<usize>,
baz_byte_start: Option<usize>,
}
impl FieldsAfterConditionalsMarker {
pub fn flags_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + GotFlags::RAW_BYTE_LEN
}
pub fn foo_byte_range(&self) -> Option<Range<usize>> {
let start = self.foo_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn always_here_byte_range(&self) -> Range<usize> {
let start = self
.foo_byte_range()
.map(|range| range.end)
.unwrap_or_else(|| self.flags_byte_range().end);
start..start + u16::RAW_BYTE_LEN
}
pub fn bar_byte_range(&self) -> Option<Range<usize>> {
let start = self.bar_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn baz_byte_range(&self) -> Option<Range<usize>> {
let start = self.baz_byte_start?;
Some(start..start + u16::RAW_BYTE_LEN)
}
pub fn also_always_here_byte_range(&self) -> Range<usize> {
let start = self
.baz_byte_range()
.map(|range| range.end)
.unwrap_or_else(|| {
self.bar_byte_range()
.map(|range| range.end)
.unwrap_or_else(|| self.always_here_byte_range().end)
});
start..start + u16::RAW_BYTE_LEN
}
pub fn and_me_too_byte_range(&self) -> Range<usize> {
let start = self.also_always_here_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for FieldsAfterConditionalsMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.and_me_too_byte_range().end
}
}
impl<'a> FontRead<'a> for FieldsAfterConditionals<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let flags: GotFlags = cursor.read()?;
let foo_byte_start = flags
.contains(GotFlags::FOO)
.then(|| cursor.position())
.transpose()?;
flags
.contains(GotFlags::FOO)
.then(|| cursor.advance::<u16>());
cursor.advance::<u16>();
let bar_byte_start = flags
.contains(GotFlags::BAR)
.then(|| cursor.position())
.transpose()?;
flags
.contains(GotFlags::BAR)
.then(|| cursor.advance::<u16>());
let baz_byte_start = flags
.contains(GotFlags::BAZ)
.then(|| cursor.position())
.transpose()?;
flags
.contains(GotFlags::BAZ)
.then(|| cursor.advance::<u16>());
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(FieldsAfterConditionalsMarker {
foo_byte_start,
bar_byte_start,
baz_byte_start,
})
}
}
pub type FieldsAfterConditionals<'a> = TableRef<'a, FieldsAfterConditionalsMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> FieldsAfterConditionals<'a> {
pub fn flags(&self) -> GotFlags {
let range = self.shape.flags_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn foo(&self) -> Option<u16> {
let range = self.shape.foo_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn always_here(&self) -> u16 {
let range = self.shape.always_here_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn bar(&self) -> Option<u16> {
let range = self.shape.bar_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn baz(&self) -> Option<u16> {
let range = self.shape.baz_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
pub fn also_always_here(&self) -> u16 {
let range = self.shape.also_always_here_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn and_me_too(&self) -> u16 {
let range = self.shape.and_me_too_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for FieldsAfterConditionals<'a> {
fn type_name(&self) -> &str {
"FieldsAfterConditionals"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let flags = self.flags();
match idx {
0usize => Some(Field::new("flags", self.flags())),
1usize if flags.contains(GotFlags::FOO) => Some(Field::new("foo", self.foo().unwrap())),
2usize => Some(Field::new("always_here", self.always_here())),
3usize if flags.contains(GotFlags::BAR) => Some(Field::new("bar", self.bar().unwrap())),
4usize if flags.contains(GotFlags::BAZ) => Some(Field::new("baz", self.baz().unwrap())),
5usize => Some(Field::new("also_always_here", self.also_always_here())),
6usize => Some(Field::new("and_me_too", self.and_me_too())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for FieldsAfterConditionals<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+148
View File
@@ -0,0 +1,148 @@
// 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::*;
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CountAll16Marker {
remainder_byte_len: usize,
}
impl CountAll16Marker {
pub fn some_field_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn remainder_byte_range(&self) -> Range<usize> {
let start = self.some_field_byte_range().end;
start..start + self.remainder_byte_len
}
}
impl MinByteRange for CountAll16Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.remainder_byte_range().end
}
}
impl<'a> FontRead<'a> for CountAll16<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
let remainder_byte_len = cursor.remaining_bytes() / u16::RAW_BYTE_LEN * u16::RAW_BYTE_LEN;
cursor.advance_by(remainder_byte_len);
cursor.finish(CountAll16Marker { remainder_byte_len })
}
}
pub type CountAll16<'a> = TableRef<'a, CountAll16Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> CountAll16<'a> {
pub fn some_field(&self) -> u16 {
let range = self.shape.some_field_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn remainder(&self) -> &'a [BigEndian<u16>] {
let range = self.shape.remainder_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CountAll16<'a> {
fn type_name(&self) -> &str {
"CountAll16"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("some_field", self.some_field())),
1usize => Some(Field::new("remainder", self.remainder())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CountAll16<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CountAll32Marker {
remainder_byte_len: usize,
}
impl CountAll32Marker {
pub fn some_field_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn remainder_byte_range(&self) -> Range<usize> {
let start = self.some_field_byte_range().end;
start..start + self.remainder_byte_len
}
}
impl MinByteRange for CountAll32Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.remainder_byte_range().end
}
}
impl<'a> FontRead<'a> for CountAll32<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
let remainder_byte_len = cursor.remaining_bytes() / u32::RAW_BYTE_LEN * u32::RAW_BYTE_LEN;
cursor.advance_by(remainder_byte_len);
cursor.finish(CountAll32Marker { remainder_byte_len })
}
}
pub type CountAll32<'a> = TableRef<'a, CountAll32Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> CountAll32<'a> {
pub fn some_field(&self) -> u16 {
let range = self.shape.some_field_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn remainder(&self) -> &'a [BigEndian<u32>] {
let range = self.shape.remainder_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CountAll32<'a> {
fn type_name(&self) -> &str {
"CountAll32"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("some_field", self.some_field())),
1usize => Some(Field::new("remainder", self.remainder())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CountAll32<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+134
View File
@@ -0,0 +1,134 @@
// 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::*;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u16)]
#[allow(clippy::manual_non_exhaustive)]
pub enum MyEnum1 {
/// doc me baby
/// docington bear
#[default]
ItsAZero = 0,
ItsAOne = 1,
#[doc(hidden)]
/// If font data is malformed we will map unknown values to this variant
Unknown,
}
impl MyEnum1 {
/// Create from a raw scalar.
///
/// This will never fail; unknown values will be mapped to the `Unknown` variant
pub fn new(raw: u16) -> Self {
match raw {
0 => Self::ItsAZero,
1 => Self::ItsAOne,
_ => Self::Unknown,
}
}
}
impl font_types::Scalar for MyEnum1 {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
(self as u16).to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::new(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<MyEnum1> for FieldType<'a> {
fn from(src: MyEnum1) -> FieldType<'a> {
(src as u16).into()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u16)]
#[allow(clippy::manual_non_exhaustive)]
pub enum MyEnum2 {
ItsATwo = 2,
/// A very important three
#[default]
ItsAThree = 3,
#[doc(hidden)]
/// If font data is malformed we will map unknown values to this variant
Unknown,
}
impl MyEnum2 {
/// Create from a raw scalar.
///
/// This will never fail; unknown values will be mapped to the `Unknown` variant
pub fn new(raw: u16) -> Self {
match raw {
2 => Self::ItsATwo,
3 => Self::ItsAThree,
_ => Self::Unknown,
}
}
}
impl font_types::Scalar for MyEnum2 {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
(self as u16).to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::new(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<MyEnum2> for FieldType<'a> {
fn from(src: MyEnum2) -> FieldType<'a> {
(src as u16).into()
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct MyRecord {
pub my_enum1: BigEndian<MyEnum1>,
pub my_enum2: BigEndian<MyEnum2>,
}
impl MyRecord {
pub fn my_enum1(&self) -> MyEnum1 {
self.my_enum1.get()
}
pub fn my_enum2(&self) -> MyEnum2 {
self.my_enum2.get()
}
}
impl FixedSize for MyRecord {
const RAW_BYTE_LEN: usize = MyEnum1::RAW_BYTE_LEN + MyEnum2::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for MyRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "MyRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("my_enum1", self.my_enum1())),
1usize => Some(Field::new("my_enum2", self.my_enum2())),
_ => None,
}),
data,
}
}
}
+314
View File
@@ -0,0 +1,314 @@
// 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::*;
/// Some flags!
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct ValueFormat {
bits: u16,
}
impl ValueFormat {
/// Includes horizontal adjustment for placement
pub const X_PLACEMENT: Self = Self { bits: 0x0001 };
/// Includes vertical adjustment for placement
pub const Y_PLACEMENT: Self = Self { bits: 0x0002 };
}
impl ValueFormat {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
Self { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
Self {
bits: Self::X_PLACEMENT.bits | Self::Y_PLACEMENT.bits,
}
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> u16 {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: u16) -> Option<Self> {
if (bits & !Self::all().bits()) == 0 {
Some(Self { bits })
} else {
None
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: u16) -> Self {
Self {
bits: bits & Self::all().bits,
}
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
self.bits() == Self::empty().bits()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
!(Self {
bits: self.bits & other.bits,
})
.is_empty()
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.bits & other.bits) == other.bits
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: Self) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: Self) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: Self) {
self.bits ^= other.bits;
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Specifically, the returned set contains only the flags which are
/// present in *both* `self` *and* `other`.
///
/// This is equivalent to using the `&` operator (e.g.
/// [`ops::BitAnd`]), as in `flags & other`.
///
/// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags which are
/// present in *either* `self` *or* `other`, including any which are
/// present in both.
///
/// This is equivalent to using the `|` operator (e.g.
/// [`ops::BitOr`]), as in `flags | other`.
///
/// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
bits: self.bits | other.bits,
}
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Specifically, the returned set contains all flags present in
/// `self`, except for the ones present in `other`.
///
/// It is also conceptually equivalent to the "bit-clear" operation:
/// `flags & !other` (and this syntax is also supported).
///
/// This is equivalent to using the `-` operator (e.g.
/// [`ops::Sub`]), as in `flags - other`.
///
/// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::BitOr for ValueFormat {
type Output = Self;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: ValueFormat) -> Self {
Self {
bits: self.bits | other.bits,
}
}
}
impl std::ops::BitOrAssign for ValueFormat {
/// Adds the set of flags.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.bits |= other.bits;
}
}
impl std::ops::BitXor for ValueFormat {
type Output = Self;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: Self) -> Self {
Self {
bits: self.bits ^ other.bits,
}
}
}
impl std::ops::BitXorAssign for ValueFormat {
/// Toggles the set of flags.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.bits ^= other.bits;
}
}
impl std::ops::BitAnd for ValueFormat {
type Output = Self;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: Self) -> Self {
Self {
bits: self.bits & other.bits,
}
}
}
impl std::ops::BitAndAssign for ValueFormat {
/// Disables all flags disabled in the set.
#[inline]
fn bitand_assign(&mut self, other: Self) {
self.bits &= other.bits;
}
}
impl std::ops::Sub for ValueFormat {
type Output = Self;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: Self) -> Self {
Self {
bits: self.bits & !other.bits,
}
}
}
impl std::ops::SubAssign for ValueFormat {
/// Disables all flags enabled in the set.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.bits &= !other.bits;
}
}
impl std::ops::Not for ValueFormat {
type Output = Self;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> Self {
Self { bits: !self.bits } & Self::all()
}
}
impl std::fmt::Debug for ValueFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let members: &[(&str, Self)] = &[
("X_PLACEMENT", Self::X_PLACEMENT),
("Y_PLACEMENT", Self::Y_PLACEMENT),
];
let mut first = true;
for (name, value) in members {
if self.contains(*value) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(name)?;
}
}
if first {
f.write_str("(empty)")?;
}
Ok(())
}
}
impl std::fmt::Binary for ValueFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Binary::fmt(&self.bits, f)
}
}
impl std::fmt::Octal for ValueFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Octal::fmt(&self.bits, f)
}
}
impl std::fmt::LowerHex for ValueFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.bits, f)
}
}
impl std::fmt::UpperHex for ValueFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::UpperHex::fmt(&self.bits, f)
}
}
impl font_types::Scalar for ValueFormat {
type Raw = <u16 as font_types::Scalar>::Raw;
fn to_raw(self) -> Self::Raw {
self.bits().to_raw()
}
fn from_raw(raw: Self::Raw) -> Self {
let t = <u16>::from_raw(raw);
Self::from_bits_truncate(t)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> From<ValueFormat> for FieldType<'a> {
fn from(src: ValueFormat) -> FieldType<'a> {
src.bits().into()
}
}
+327
View File
@@ -0,0 +1,327 @@
// 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::*;
impl Format<u16> for Table1Marker {
const FORMAT: u16 = 1;
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Table1Marker {}
impl Table1Marker {
pub fn format_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn heft_byte_range(&self) -> Range<usize> {
let start = self.format_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn flex_byte_range(&self) -> Range<usize> {
let start = self.heft_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for Table1Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.flex_byte_range().end
}
}
impl<'a> FontRead<'a> for Table1<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u32>();
cursor.advance::<u16>();
cursor.finish(Table1Marker {})
}
}
pub type Table1<'a> = TableRef<'a, Table1Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Table1<'a> {
pub fn format(&self) -> u16 {
let range = self.shape.format_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn heft(&self) -> u32 {
let range = self.shape.heft_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn flex(&self) -> u16 {
let range = self.shape.flex_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Table1<'a> {
fn type_name(&self) -> &str {
"Table1"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("format", self.format())),
1usize => Some(Field::new("heft", self.heft())),
2usize => Some(Field::new("flex", self.flex())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Table1<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
impl Format<u16> for Table2Marker {
const FORMAT: u16 = 2;
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Table2Marker {
values_byte_len: usize,
}
impl Table2Marker {
pub fn format_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn value_count_byte_range(&self) -> Range<usize> {
let start = self.format_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn values_byte_range(&self) -> Range<usize> {
let start = self.value_count_byte_range().end;
start..start + self.values_byte_len
}
}
impl MinByteRange for Table2Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.values_byte_range().end
}
}
impl<'a> FontRead<'a> for Table2<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
let value_count: u16 = cursor.read()?;
let values_byte_len = (value_count as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(values_byte_len);
cursor.finish(Table2Marker { values_byte_len })
}
}
pub type Table2<'a> = TableRef<'a, Table2Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Table2<'a> {
pub fn format(&self) -> u16 {
let range = self.shape.format_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn value_count(&self) -> u16 {
let range = self.shape.value_count_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn values(&self) -> &'a [BigEndian<u16>] {
let range = self.shape.values_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Table2<'a> {
fn type_name(&self) -> &str {
"Table2"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("format", self.format())),
1usize => Some(Field::new("value_count", self.value_count())),
2usize => Some(Field::new("values", self.values())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Table2<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
impl Format<u16> for Table3Marker {
const FORMAT: u16 = 3;
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct Table3Marker {}
impl Table3Marker {
pub fn format_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn something_byte_range(&self) -> Range<usize> {
let start = self.format_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for Table3Marker {
fn min_byte_range(&self) -> Range<usize> {
0..self.something_byte_range().end
}
}
impl<'a> FontRead<'a> for Table3<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(Table3Marker {})
}
}
pub type Table3<'a> = TableRef<'a, Table3Marker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Table3<'a> {
pub fn format(&self) -> u16 {
let range = self.shape.format_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn something(&self) -> u16 {
let range = self.shape.something_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Table3<'a> {
fn type_name(&self) -> &str {
"Table3"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("format", self.format())),
1usize => Some(Field::new("something", self.something())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Table3<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone)]
pub enum MyTable<'a> {
Format1(Table1<'a>),
MyFormat22(Table2<'a>),
Format3(Table3<'a>),
}
impl<'a> MyTable<'a> {
///Return the `FontData` used to resolve offsets for this table.
pub fn offset_data(&self) -> FontData<'a> {
match self {
Self::Format1(item) => item.offset_data(),
Self::MyFormat22(item) => item.offset_data(),
Self::Format3(item) => item.offset_data(),
}
}
pub fn format(&self) -> u16 {
match self {
Self::Format1(item) => item.format(),
Self::MyFormat22(item) => item.format(),
Self::Format3(item) => item.format(),
}
}
}
impl<'a> FontRead<'a> for MyTable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let format: u16 = data.read_at(0usize)?;
match format {
Table1Marker::FORMAT => Ok(Self::Format1(FontRead::read(data)?)),
Table2Marker::FORMAT => Ok(Self::MyFormat22(FontRead::read(data)?)),
Table3Marker::FORMAT => Ok(Self::Format3(FontRead::read(data)?)),
other => Err(ReadError::InvalidFormat(other.into())),
}
}
}
impl MinByteRange for MyTable<'_> {
fn min_byte_range(&self) -> Range<usize> {
match self {
Self::Format1(item) => item.min_byte_range(),
Self::MyFormat22(item) => item.min_byte_range(),
Self::Format3(item) => item.min_byte_range(),
}
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> MyTable<'a> {
fn dyn_inner<'b>(&'b self) -> &'b dyn SomeTable<'a> {
match self {
Self::Format1(table) => table,
Self::MyFormat22(table) => table,
Self::Format3(table) => table,
}
}
}
#[cfg(feature = "experimental_traverse")]
impl std::fmt::Debug for MyTable<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.dyn_inner().fmt(f)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for MyTable<'a> {
fn type_name(&self) -> &str {
self.dyn_inner().type_name()
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
self.dyn_inner().get_field(idx)
}
}
@@ -0,0 +1,890 @@
// 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::*;
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct KindsOfOffsetsMarker {
versioned_nullable_record_array_offset_byte_start: Option<usize>,
versioned_nonnullable_offset_byte_start: Option<usize>,
versioned_nullable_offset_byte_start: Option<usize>,
}
impl KindsOfOffsetsMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn nonnullable_offset_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn nullable_offset_byte_range(&self) -> Range<usize> {
let start = self.nonnullable_offset_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn array_offset_count_byte_range(&self) -> Range<usize> {
let start = self.nullable_offset_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn array_offset_byte_range(&self) -> Range<usize> {
let start = self.array_offset_count_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn record_array_offset_byte_range(&self) -> Range<usize> {
let start = self.array_offset_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn versioned_nullable_record_array_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_nullable_record_array_offset_byte_start?;
Some(start..start + Offset16::RAW_BYTE_LEN)
}
pub fn versioned_nonnullable_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_nonnullable_offset_byte_start?;
Some(start..start + Offset16::RAW_BYTE_LEN)
}
pub fn versioned_nullable_offset_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_nullable_offset_byte_start?;
Some(start..start + Offset32::RAW_BYTE_LEN)
}
}
impl MinByteRange for KindsOfOffsetsMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.record_array_offset_byte_range().end
}
}
impl<'a> FontRead<'a> for KindsOfOffsets<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: MajorMinor = cursor.read()?;
cursor.advance::<Offset16>();
cursor.advance::<Offset16>();
cursor.advance::<u16>();
cursor.advance::<Offset16>();
cursor.advance::<Offset16>();
let versioned_nullable_record_array_offset_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 1u16))
.then(|| cursor.advance::<Offset16>());
let versioned_nonnullable_offset_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 1u16))
.then(|| cursor.advance::<Offset16>());
let versioned_nullable_offset_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
version
.compatible((1u16, 1u16))
.then(|| cursor.advance::<Offset32>());
cursor.finish(KindsOfOffsetsMarker {
versioned_nullable_record_array_offset_byte_start,
versioned_nonnullable_offset_byte_start,
versioned_nullable_offset_byte_start,
})
}
}
pub type KindsOfOffsets<'a> = TableRef<'a, KindsOfOffsetsMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> KindsOfOffsets<'a> {
/// The major/minor version of the GDEF table
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// A normal offset
pub fn nonnullable_offset(&self) -> Offset16 {
let range = self.shape.nonnullable_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`nonnullable_offset`][Self::nonnullable_offset].
pub fn nonnullable(&self) -> Result<Dummy<'a>, ReadError> {
let data = self.data;
self.nonnullable_offset().resolve(data)
}
/// An offset that is nullable, but always present
pub fn nullable_offset(&self) -> Nullable<Offset16> {
let range = self.shape.nullable_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`nullable_offset`][Self::nullable_offset].
pub fn nullable(&self) -> Option<Result<Dummy<'a>, ReadError>> {
let data = self.data;
self.nullable_offset().resolve(data)
}
/// count of the array at array_offset
pub fn array_offset_count(&self) -> u16 {
let range = self.shape.array_offset_count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// An offset to an array:
pub fn array_offset(&self) -> Offset16 {
let range = self.shape.array_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`array_offset`][Self::array_offset].
pub fn array(&self) -> Result<&'a [BigEndian<u16>], ReadError> {
let data = self.data;
let args = self.array_offset_count();
self.array_offset().resolve_with_args(data, &args)
}
/// An offset to an array of records
pub fn record_array_offset(&self) -> Offset16 {
let range = self.shape.record_array_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`record_array_offset`][Self::record_array_offset].
pub fn record_array(&self) -> Result<&'a [Shmecord], ReadError> {
let data = self.data;
let args = self.array_offset_count();
self.record_array_offset().resolve_with_args(data, &args)
}
/// A nullable, versioned offset to an array of records
pub fn versioned_nullable_record_array_offset(&self) -> Option<Nullable<Offset16>> {
let range = self
.shape
.versioned_nullable_record_array_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`versioned_nullable_record_array_offset`][Self::versioned_nullable_record_array_offset].
pub fn versioned_nullable_record_array(&self) -> Option<Result<&'a [Shmecord], ReadError>> {
let data = self.data;
let args = self.array_offset_count();
self.versioned_nullable_record_array_offset()
.map(|x| x.resolve_with_args(data, &args))?
}
/// A normal offset that is versioned
pub fn versioned_nonnullable_offset(&self) -> Option<Offset16> {
let range = self.shape.versioned_nonnullable_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`versioned_nonnullable_offset`][Self::versioned_nonnullable_offset].
pub fn versioned_nonnullable(&self) -> Option<Result<Dummy<'a>, ReadError>> {
let data = self.data;
self.versioned_nonnullable_offset().map(|x| x.resolve(data))
}
/// An offset that is nullable and versioned
pub fn versioned_nullable_offset(&self) -> Option<Nullable<Offset32>> {
let range = self.shape.versioned_nullable_offset_byte_range()?;
Some(self.data.read_at(range.start).unwrap())
}
/// Attempt to resolve [`versioned_nullable_offset`][Self::versioned_nullable_offset].
pub fn versioned_nullable(&self) -> Option<Result<Dummy<'a>, ReadError>> {
let data = self.data;
self.versioned_nullable_offset().map(|x| x.resolve(data))?
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for KindsOfOffsets<'a> {
fn type_name(&self) -> &str {
"KindsOfOffsets"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"nonnullable_offset",
FieldType::offset(self.nonnullable_offset(), self.nonnullable()),
)),
2usize => Some(Field::new(
"nullable_offset",
FieldType::offset(self.nullable_offset(), self.nullable()),
)),
3usize => Some(Field::new("array_offset_count", self.array_offset_count())),
4usize => Some(Field::new(
"array_offset",
FieldType::offset_to_array_of_scalars(self.array_offset(), self.array()),
)),
5usize => Some(Field::new(
"record_array_offset",
traversal::FieldType::offset_to_array_of_records(
self.record_array_offset(),
self.record_array(),
stringify!(Shmecord),
self.offset_data(),
),
)),
6usize if version.compatible((1u16, 1u16)) => Some(Field::new(
"versioned_nullable_record_array_offset",
traversal::FieldType::offset_to_array_of_records(
self.versioned_nullable_record_array_offset().unwrap(),
self.versioned_nullable_record_array(),
stringify!(Shmecord),
self.offset_data(),
),
)),
7usize if version.compatible((1u16, 1u16)) => Some(Field::new(
"versioned_nonnullable_offset",
FieldType::offset(
self.versioned_nonnullable_offset().unwrap(),
self.versioned_nonnullable().unwrap(),
),
)),
8usize if version.compatible((1u16, 1u16)) => Some(Field::new(
"versioned_nullable_offset",
FieldType::offset(
self.versioned_nullable_offset().unwrap(),
self.versioned_nullable(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for KindsOfOffsets<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct KindsOfArraysOfOffsetsMarker {
nonnullable_offsets_byte_len: usize,
nullable_offsets_byte_len: usize,
versioned_nonnullable_offsets_byte_start: Option<usize>,
versioned_nonnullable_offsets_byte_len: Option<usize>,
versioned_nullable_offsets_byte_start: Option<usize>,
versioned_nullable_offsets_byte_len: Option<usize>,
}
impl KindsOfArraysOfOffsetsMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn nonnullable_offsets_byte_range(&self) -> Range<usize> {
let start = self.count_byte_range().end;
start..start + self.nonnullable_offsets_byte_len
}
pub fn nullable_offsets_byte_range(&self) -> Range<usize> {
let start = self.nonnullable_offsets_byte_range().end;
start..start + self.nullable_offsets_byte_len
}
pub fn versioned_nonnullable_offsets_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_nonnullable_offsets_byte_start?;
Some(start..start + self.versioned_nonnullable_offsets_byte_len?)
}
pub fn versioned_nullable_offsets_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_nullable_offsets_byte_start?;
Some(start..start + self.versioned_nullable_offsets_byte_len?)
}
}
impl MinByteRange for KindsOfArraysOfOffsetsMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.nullable_offsets_byte_range().end
}
}
impl<'a> FontRead<'a> for KindsOfArraysOfOffsets<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: MajorMinor = cursor.read()?;
let count: u16 = cursor.read()?;
let nonnullable_offsets_byte_len = (count as usize)
.checked_mul(Offset16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(nonnullable_offsets_byte_len);
let nullable_offsets_byte_len = (count as usize)
.checked_mul(Offset16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(nullable_offsets_byte_len);
let versioned_nonnullable_offsets_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
let versioned_nonnullable_offsets_byte_len = version.compatible((1u16, 1u16)).then_some(
(count as usize)
.checked_mul(Offset16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = versioned_nonnullable_offsets_byte_len {
cursor.advance_by(value);
}
let versioned_nullable_offsets_byte_start = version
.compatible((1u16, 1u16))
.then(|| cursor.position())
.transpose()?;
let versioned_nullable_offsets_byte_len = version.compatible((1u16, 1u16)).then_some(
(count as usize)
.checked_mul(Offset16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = versioned_nullable_offsets_byte_len {
cursor.advance_by(value);
}
cursor.finish(KindsOfArraysOfOffsetsMarker {
nonnullable_offsets_byte_len,
nullable_offsets_byte_len,
versioned_nonnullable_offsets_byte_start,
versioned_nonnullable_offsets_byte_len,
versioned_nullable_offsets_byte_start,
versioned_nullable_offsets_byte_len,
})
}
}
pub type KindsOfArraysOfOffsets<'a> = TableRef<'a, KindsOfArraysOfOffsetsMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> KindsOfArraysOfOffsets<'a> {
/// The version
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The number of items in each array
pub fn count(&self) -> u16 {
let range = self.shape.count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// A normal array offset
pub fn nonnullable_offsets(&self) -> &'a [BigEndian<Offset16>] {
let range = self.shape.nonnullable_offsets_byte_range();
self.data.read_array(range).unwrap()
}
/// A dynamically resolving wrapper for [`nonnullable_offsets`][Self::nonnullable_offsets].
pub fn nonnullables(&self) -> ArrayOfOffsets<'a, Dummy<'a>, Offset16> {
let data = self.data;
let offsets = self.nonnullable_offsets();
ArrayOfOffsets::new(offsets, data, ())
}
/// An offset that is nullable, but always present
pub fn nullable_offsets(&self) -> &'a [BigEndian<Nullable<Offset16>>] {
let range = self.shape.nullable_offsets_byte_range();
self.data.read_array(range).unwrap()
}
/// A dynamically resolving wrapper for [`nullable_offsets`][Self::nullable_offsets].
pub fn nullables(&self) -> ArrayOfNullableOffsets<'a, Dummy<'a>, Offset16> {
let data = self.data;
let offsets = self.nullable_offsets();
ArrayOfNullableOffsets::new(offsets, data, ())
}
/// A normal offset that is versioned
pub fn versioned_nonnullable_offsets(&self) -> Option<&'a [BigEndian<Offset16>]> {
let range = self.shape.versioned_nonnullable_offsets_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
/// A dynamically resolving wrapper for [`versioned_nonnullable_offsets`][Self::versioned_nonnullable_offsets].
pub fn versioned_nonnullables(&self) -> Option<ArrayOfOffsets<'a, Dummy<'a>, Offset16>> {
let data = self.data;
let offsets = self.versioned_nonnullable_offsets();
offsets.map(|offsets| ArrayOfOffsets::new(offsets, data, ()))
}
/// An offset that is nullable and versioned
pub fn versioned_nullable_offsets(&self) -> Option<&'a [BigEndian<Nullable<Offset16>>]> {
let range = self.shape.versioned_nullable_offsets_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
/// A dynamically resolving wrapper for [`versioned_nullable_offsets`][Self::versioned_nullable_offsets].
pub fn versioned_nullables(&self) -> Option<ArrayOfNullableOffsets<'a, Dummy<'a>, Offset16>> {
let data = self.data;
let offsets = self.versioned_nullable_offsets();
offsets.map(|offsets| ArrayOfNullableOffsets::new(offsets, data, ()))
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for KindsOfArraysOfOffsets<'a> {
fn type_name(&self) -> &str {
"KindsOfArraysOfOffsets"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("count", self.count())),
2usize => Some({
let data = self.data;
Field::new(
"nonnullable_offsets",
FieldType::array_of_offsets(
better_type_name::<Dummy>(),
self.nonnullable_offsets(),
move |off| {
let target = off.get().resolve::<Dummy>(data);
FieldType::offset(off.get(), target)
},
),
)
}),
3usize => Some({
let data = self.data;
Field::new(
"nullable_offsets",
FieldType::array_of_offsets(
better_type_name::<Dummy>(),
self.nullable_offsets(),
move |off| {
let target = off.get().resolve::<Dummy>(data);
FieldType::offset(off.get(), target)
},
),
)
}),
4usize if version.compatible((1u16, 1u16)) => Some({
let data = self.data;
Field::new(
"versioned_nonnullable_offsets",
FieldType::array_of_offsets(
better_type_name::<Dummy>(),
self.versioned_nonnullable_offsets().unwrap(),
move |off| {
let target = off.get().resolve::<Dummy>(data);
FieldType::offset(off.get(), target)
},
),
)
}),
5usize if version.compatible((1u16, 1u16)) => Some({
let data = self.data;
Field::new(
"versioned_nullable_offsets",
FieldType::array_of_offsets(
better_type_name::<Dummy>(),
self.versioned_nullable_offsets().unwrap(),
move |off| {
let target = off.get().resolve::<Dummy>(data);
FieldType::offset(off.get(), target)
},
),
)
}),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for KindsOfArraysOfOffsets<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct KindsOfArraysMarker {
scalars_byte_len: usize,
records_byte_len: usize,
versioned_scalars_byte_start: Option<usize>,
versioned_scalars_byte_len: Option<usize>,
versioned_records_byte_start: Option<usize>,
versioned_records_byte_len: Option<usize>,
}
impl KindsOfArraysMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn count_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn scalars_byte_range(&self) -> Range<usize> {
let start = self.count_byte_range().end;
start..start + self.scalars_byte_len
}
pub fn records_byte_range(&self) -> Range<usize> {
let start = self.scalars_byte_range().end;
start..start + self.records_byte_len
}
pub fn versioned_scalars_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_scalars_byte_start?;
Some(start..start + self.versioned_scalars_byte_len?)
}
pub fn versioned_records_byte_range(&self) -> Option<Range<usize>> {
let start = self.versioned_records_byte_start?;
Some(start..start + self.versioned_records_byte_len?)
}
}
impl MinByteRange for KindsOfArraysMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.records_byte_range().end
}
}
impl<'a> FontRead<'a> for KindsOfArrays<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let version: u16 = cursor.read()?;
let count: u16 = cursor.read()?;
let scalars_byte_len = (count as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(scalars_byte_len);
let records_byte_len = (count as usize)
.checked_mul(Shmecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(records_byte_len);
let versioned_scalars_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
let versioned_scalars_byte_len = version.compatible(1u16).then_some(
(count as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = versioned_scalars_byte_len {
cursor.advance_by(value);
}
let versioned_records_byte_start = version
.compatible(1u16)
.then(|| cursor.position())
.transpose()?;
let versioned_records_byte_len = version.compatible(1u16).then_some(
(count as usize)
.checked_mul(Shmecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
);
if let Some(value) = versioned_records_byte_len {
cursor.advance_by(value);
}
cursor.finish(KindsOfArraysMarker {
scalars_byte_len,
records_byte_len,
versioned_scalars_byte_start,
versioned_scalars_byte_len,
versioned_records_byte_start,
versioned_records_byte_len,
})
}
}
pub type KindsOfArrays<'a> = TableRef<'a, KindsOfArraysMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> KindsOfArrays<'a> {
pub fn version(&self) -> u16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// the number of items in each array
pub fn count(&self) -> u16 {
let range = self.shape.count_byte_range();
self.data.read_at(range.start).unwrap()
}
/// an array of scalars
pub fn scalars(&self) -> &'a [BigEndian<u16>] {
let range = self.shape.scalars_byte_range();
self.data.read_array(range).unwrap()
}
/// an array of records
pub fn records(&self) -> &'a [Shmecord] {
let range = self.shape.records_byte_range();
self.data.read_array(range).unwrap()
}
/// a versioned array of scalars
pub fn versioned_scalars(&self) -> Option<&'a [BigEndian<u16>]> {
let range = self.shape.versioned_scalars_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
/// a versioned array of scalars
pub fn versioned_records(&self) -> Option<&'a [Shmecord]> {
let range = self.shape.versioned_records_byte_range()?;
Some(self.data.read_array(range).unwrap())
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for KindsOfArrays<'a> {
fn type_name(&self) -> &str {
"KindsOfArrays"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
let version = self.version();
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("count", self.count())),
2usize => Some(Field::new("scalars", self.scalars())),
3usize => Some(Field::new(
"records",
traversal::FieldType::array_of_records(
stringify!(Shmecord),
self.records(),
self.offset_data(),
),
)),
4usize if version.compatible(1u16) => Some(Field::new(
"versioned_scalars",
self.versioned_scalars().unwrap(),
)),
5usize if version.compatible(1u16) => Some(Field::new(
"versioned_records",
traversal::FieldType::array_of_records(
stringify!(Shmecord),
self.versioned_records().unwrap(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for KindsOfArrays<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VarLenHaverMarker {
var_len_byte_len: usize,
}
impl VarLenHaverMarker {
pub fn count_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn var_len_byte_range(&self) -> Range<usize> {
let start = self.count_byte_range().end;
start..start + self.var_len_byte_len
}
pub fn other_field_byte_range(&self) -> Range<usize> {
let start = self.var_len_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
}
impl MinByteRange for VarLenHaverMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.other_field_byte_range().end
}
}
impl<'a> FontRead<'a> for VarLenHaver<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let count: u16 = cursor.read()?;
let var_len_byte_len = {
let data = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
<VarSizeDummy as VarSize>::total_len_for_count(data, count as usize)?
};
cursor.advance_by(var_len_byte_len);
cursor.advance::<u32>();
cursor.finish(VarLenHaverMarker { var_len_byte_len })
}
}
pub type VarLenHaver<'a> = TableRef<'a, VarLenHaverMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> VarLenHaver<'a> {
pub fn count(&self) -> u16 {
let range = self.shape.count_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn var_len(&self) -> VarLenArray<'a, VarSizeDummy> {
let range = self.shape.var_len_byte_range();
VarLenArray::read(self.data.split_off(range.start).unwrap()).unwrap()
}
pub fn other_field(&self) -> u32 {
let range = self.shape.other_field_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for VarLenHaver<'a> {
fn type_name(&self) -> &str {
"VarLenHaver"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("count", self.count())),
1usize => Some(Field::new("var_len", traversal::FieldType::Unknown)),
2usize => Some(Field::new("other_field", self.other_field())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for VarLenHaver<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct DummyMarker {}
impl DummyMarker {
pub fn value_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn _reserved_byte_range(&self) -> Range<usize> {
let start = self.value_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for DummyMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self._reserved_byte_range().end
}
}
impl<'a> FontRead<'a> for Dummy<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u16>();
cursor.advance::<u16>();
cursor.finish(DummyMarker {})
}
}
pub type Dummy<'a> = TableRef<'a, DummyMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Dummy<'a> {
pub fn value(&self) -> u16 {
let range = self.shape.value_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Dummy<'a> {
fn type_name(&self) -> &str {
"Dummy"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("value", self.value())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Dummy<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct Shmecord {
pub length: BigEndian<u16>,
pub breadth: BigEndian<u32>,
}
impl Shmecord {
pub fn length(&self) -> u16 {
self.length.get()
}
pub fn breadth(&self) -> u32 {
self.breadth.get()
}
}
impl FixedSize for Shmecord {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for Shmecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "Shmecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("breadth", self.breadth())),
_ => None,
}),
data,
}
}
}
+408
View File
@@ -0,0 +1,408 @@
// 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::*;
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct BasicTableMarker {
simple_records_byte_len: usize,
array_records_byte_len: usize,
}
impl BasicTableMarker {
pub fn simple_count_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn simple_records_byte_range(&self) -> Range<usize> {
let start = self.simple_count_byte_range().end;
start..start + self.simple_records_byte_len
}
pub fn arrays_inner_count_byte_range(&self) -> Range<usize> {
let start = self.simple_records_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn array_records_count_byte_range(&self) -> Range<usize> {
let start = self.arrays_inner_count_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn array_records_byte_range(&self) -> Range<usize> {
let start = self.array_records_count_byte_range().end;
start..start + self.array_records_byte_len
}
}
impl MinByteRange for BasicTableMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.array_records_byte_range().end
}
}
impl<'a> FontRead<'a> for BasicTable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let simple_count: u16 = cursor.read()?;
let simple_records_byte_len = (simple_count as usize)
.checked_mul(SimpleRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(simple_records_byte_len);
let arrays_inner_count: u16 = cursor.read()?;
let array_records_count: u32 = cursor.read()?;
let array_records_byte_len = (array_records_count as usize)
.checked_mul(<ContainsArrays as ComputeSize>::compute_size(
&arrays_inner_count,
)?)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(array_records_byte_len);
cursor.finish(BasicTableMarker {
simple_records_byte_len,
array_records_byte_len,
})
}
}
pub type BasicTable<'a> = TableRef<'a, BasicTableMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> BasicTable<'a> {
pub fn simple_count(&self) -> u16 {
let range = self.shape.simple_count_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn simple_records(&self) -> &'a [SimpleRecord] {
let range = self.shape.simple_records_byte_range();
self.data.read_array(range).unwrap()
}
pub fn arrays_inner_count(&self) -> u16 {
let range = self.shape.arrays_inner_count_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn array_records_count(&self) -> u32 {
let range = self.shape.array_records_count_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn array_records(&self) -> ComputedArray<'a, ContainsArrays<'a>> {
let range = self.shape.array_records_byte_range();
self.data
.read_with_args(range, &self.arrays_inner_count())
.unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for BasicTable<'a> {
fn type_name(&self) -> &str {
"BasicTable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("simple_count", self.simple_count())),
1usize => Some(Field::new(
"simple_records",
traversal::FieldType::array_of_records(
stringify!(SimpleRecord),
self.simple_records(),
self.offset_data(),
),
)),
2usize => Some(Field::new("arrays_inner_count", self.arrays_inner_count())),
3usize => Some(Field::new(
"array_records_count",
self.array_records_count(),
)),
4usize => Some(Field::new(
"array_records",
traversal::FieldType::computed_array(
"ContainsArrays",
self.array_records(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for BasicTable<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct SimpleRecord {
pub val1: BigEndian<u16>,
pub va2: BigEndian<u32>,
}
impl SimpleRecord {
pub fn val1(&self) -> u16 {
self.val1.get()
}
pub fn va2(&self) -> u32 {
self.va2.get()
}
}
impl FixedSize for SimpleRecord {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SimpleRecord {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "SimpleRecord",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("val1", self.val1())),
1usize => Some(Field::new("va2", self.va2())),
_ => None,
}),
data,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContainsArrays<'a> {
pub scalars: &'a [BigEndian<u16>],
pub records: &'a [SimpleRecord],
}
impl<'a> ContainsArrays<'a> {
pub fn scalars(&self) -> &'a [BigEndian<u16>] {
self.scalars
}
pub fn records(&self) -> &'a [SimpleRecord] {
self.records
}
}
impl ReadArgs for ContainsArrays<'_> {
type Args = u16;
}
impl ComputeSize for ContainsArrays<'_> {
#[allow(clippy::needless_question_mark)]
fn compute_size(args: &u16) -> Result<usize, ReadError> {
let array_len = *args;
let mut result = 0usize;
result = result
.checked_add(
(array_len as usize)
.checked_mul(u16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
)
.ok_or(ReadError::OutOfBounds)?;
result = result
.checked_add(
(array_len as usize)
.checked_mul(SimpleRecord::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?,
)
.ok_or(ReadError::OutOfBounds)?;
Ok(result)
}
}
impl<'a> FontReadWithArgs<'a> for ContainsArrays<'a> {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let array_len = *args;
Ok(Self {
scalars: cursor.read_array(array_len as usize)?,
records: cursor.read_array(array_len as usize)?,
})
}
}
#[allow(clippy::needless_lifetimes)]
impl<'a> ContainsArrays<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(data: FontData<'a>, array_len: u16) -> Result<Self, ReadError> {
let args = array_len;
Self::read_with_args(data, &args)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ContainsArrays<'a> {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "ContainsArrays",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("scalars", self.scalars())),
1usize => Some(Field::new(
"records",
traversal::FieldType::array_of_records(
stringify!(SimpleRecord),
self.records(),
_data,
),
)),
_ => None,
}),
data,
}
}
}
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct ContainsOffsets {
pub off_array_count: BigEndian<u16>,
pub array_offset: BigEndian<Offset16>,
pub other_offset: BigEndian<Offset32>,
}
impl ContainsOffsets {
pub fn off_array_count(&self) -> u16 {
self.off_array_count.get()
}
pub fn array_offset(&self) -> Offset16 {
self.array_offset.get()
}
///
/// The `data` argument should be retrieved from the parent table
/// By calling its `offset_data` method.
pub fn array<'a>(&self, data: FontData<'a>) -> Result<&'a [SimpleRecord], ReadError> {
let args = self.off_array_count();
self.array_offset().resolve_with_args(data, &args)
}
pub fn other_offset(&self) -> Offset32 {
self.other_offset.get()
}
///
/// The `data` argument should be retrieved from the parent table
/// By calling its `offset_data` method.
pub fn other<'a>(&self, data: FontData<'a>) -> Result<BasicTable<'a>, ReadError> {
self.other_offset().resolve(data)
}
}
impl FixedSize for ContainsOffsets {
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + Offset16::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ContainsOffsets {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "ContainsOffsets",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("off_array_count", self.off_array_count())),
1usize => Some(Field::new(
"array_offset",
traversal::FieldType::offset_to_array_of_records(
self.array_offset(),
self.array(_data),
stringify!(SimpleRecord),
_data,
),
)),
2usize => Some(Field::new(
"other_offset",
FieldType::offset(self.other_offset(), self.other(_data)),
)),
_ => None,
}),
data,
}
}
}
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VarLenItemMarker {
data_byte_len: usize,
}
impl VarLenItemMarker {
pub fn length_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u32::RAW_BYTE_LEN
}
pub fn data_byte_range(&self) -> Range<usize> {
let start = self.length_byte_range().end;
start..start + self.data_byte_len
}
}
impl MinByteRange for VarLenItemMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.data_byte_range().end
}
}
impl<'a> FontRead<'a> for VarLenItem<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<u32>();
let data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
cursor.advance_by(data_byte_len);
cursor.finish(VarLenItemMarker { data_byte_len })
}
}
pub type VarLenItem<'a> = TableRef<'a, VarLenItemMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> VarLenItem<'a> {
pub fn length(&self) -> u32 {
let range = self.shape.length_byte_range();
self.data.read_at(range.start).unwrap()
}
pub fn data(&self) -> &'a [u8] {
let range = self.shape.data_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for VarLenItem<'a> {
fn type_name(&self) -> &str {
"VarLenItem"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("length", self.length())),
1usize => Some(Field::new("data", self.data())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for VarLenItem<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+295
View File
@@ -0,0 +1,295 @@
// 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::*;
/// The [tracking (trak)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TrakMarker {}
impl TrakMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn format_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn horiz_offset_byte_range(&self) -> Range<usize> {
let start = self.format_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn vert_offset_byte_range(&self) -> Range<usize> {
let start = self.horiz_offset_byte_range().end;
start..start + Offset16::RAW_BYTE_LEN
}
pub fn reserved_byte_range(&self) -> Range<usize> {
let start = self.vert_offset_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for TrakMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.reserved_byte_range().end
}
}
impl TopLevelTable for Trak<'_> {
/// `trak`
const TAG: Tag = Tag::new(b"trak");
}
impl<'a> FontRead<'a> for Trak<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<u16>();
cursor.advance::<Offset16>();
cursor.advance::<Offset16>();
cursor.advance::<u16>();
cursor.finish(TrakMarker {})
}
}
/// The [tracking (trak)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html) table.
pub type Trak<'a> = TableRef<'a, TrakMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Trak<'a> {
/// Version number of the tracking table (0x00010000 for the current version).
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Format of the tracking table (set to 0).
pub fn format(&self) -> u16 {
let range = self.shape.format_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from start of tracking table to TrackData for horizontal text (or 0 if none).
pub fn horiz_offset(&self) -> Nullable<Offset16> {
let range = self.shape.horiz_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`horiz_offset`][Self::horiz_offset].
pub fn horiz(&self) -> Option<Result<TrackData<'a>, ReadError>> {
let data = self.data;
self.horiz_offset().resolve(data)
}
/// Offset from start of tracking table to TrackData for vertical text (or 0 if none).
pub fn vert_offset(&self) -> Nullable<Offset16> {
let range = self.shape.vert_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`vert_offset`][Self::vert_offset].
pub fn vert(&self) -> Option<Result<TrackData<'a>, ReadError>> {
let data = self.data;
self.vert_offset().resolve(data)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Trak<'a> {
fn type_name(&self) -> &str {
"Trak"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("format", self.format())),
2usize => Some(Field::new(
"horiz_offset",
FieldType::offset(self.horiz_offset(), self.horiz()),
)),
3usize => Some(Field::new(
"vert_offset",
FieldType::offset(self.vert_offset(), self.vert()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Trak<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// The tracking data table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TrackDataMarker {
track_table_byte_len: usize,
}
impl TrackDataMarker {
pub fn n_tracks_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + u16::RAW_BYTE_LEN
}
pub fn n_sizes_byte_range(&self) -> Range<usize> {
let start = self.n_tracks_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn size_table_offset_byte_range(&self) -> Range<usize> {
let start = self.n_sizes_byte_range().end;
start..start + u32::RAW_BYTE_LEN
}
pub fn track_table_byte_range(&self) -> Range<usize> {
let start = self.size_table_offset_byte_range().end;
start..start + self.track_table_byte_len
}
}
impl MinByteRange for TrackDataMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.track_table_byte_range().end
}
}
impl<'a> FontRead<'a> for TrackData<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let n_tracks: u16 = cursor.read()?;
cursor.advance::<u16>();
cursor.advance::<u32>();
let track_table_byte_len = (n_tracks as usize)
.checked_mul(TrackTableEntry::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(track_table_byte_len);
cursor.finish(TrackDataMarker {
track_table_byte_len,
})
}
}
/// The tracking data table.
pub type TrackData<'a> = TableRef<'a, TrackDataMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> TrackData<'a> {
/// Number of separate tracks included in this table.
pub fn n_tracks(&self) -> u16 {
let range = self.shape.n_tracks_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of point sizes included in this table.
pub fn n_sizes(&self) -> u16 {
let range = self.shape.n_sizes_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset from the start of the tracking table to the start of the size subtable.
pub fn size_table_offset(&self) -> u32 {
let range = self.shape.size_table_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Array of TrackTableEntry records.
pub fn track_table(&self) -> &'a [TrackTableEntry] {
let range = self.shape.track_table_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for TrackData<'a> {
fn type_name(&self) -> &str {
"TrackData"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("n_tracks", self.n_tracks())),
1usize => Some(Field::new("n_sizes", self.n_sizes())),
2usize => Some(Field::new("size_table_offset", self.size_table_offset())),
3usize => Some(Field::new(
"track_table",
traversal::FieldType::array_of_records(
stringify!(TrackTableEntry),
self.track_table(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for TrackData<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Single entry in a tracking table.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct TrackTableEntry {
/// Track value for this record.
pub track: BigEndian<Fixed>,
/// The 'name' table index for this track (a short word or phrase like \"loose\" or \"very tight\"). NameIndex has a value greater than 255 and less than 32768.
pub name_index: BigEndian<NameId>,
/// Offset from the start of the tracking table to per-size tracking values for this track.
pub offset: BigEndian<u16>,
}
impl TrackTableEntry {
/// Track value for this record.
pub fn track(&self) -> Fixed {
self.track.get()
}
/// The 'name' table index for this track (a short word or phrase like \"loose\" or \"very tight\"). NameIndex has a value greater than 255 and less than 32768.
pub fn name_index(&self) -> NameId {
self.name_index.get()
}
/// Offset from the start of the tracking table to per-size tracking values for this track.
pub fn offset(&self) -> u16 {
self.offset.get()
}
}
impl FixedSize for TrackTableEntry {
const RAW_BYTE_LEN: usize = Fixed::RAW_BYTE_LEN + NameId::RAW_BYTE_LEN + u16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for TrackTableEntry {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "TrackTableEntry",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("track", self.track())),
1usize => Some(Field::new("name_index", self.name_index())),
2usize => Some(Field::new("offset", self.offset())),
_ => None,
}),
data,
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+264
View File
@@ -0,0 +1,264 @@
// 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::*;
/// The [vhea](https://docs.microsoft.com/en-us/typography/opentype/spec/vhea) Vertical Header Table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VheaMarker {}
impl VheaMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + Version16Dot16::RAW_BYTE_LEN
}
pub fn ascender_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn descender_byte_range(&self) -> Range<usize> {
let start = self.ascender_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn line_gap_byte_range(&self) -> Range<usize> {
let start = self.descender_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn advance_height_max_byte_range(&self) -> Range<usize> {
let start = self.line_gap_byte_range().end;
start..start + UfWord::RAW_BYTE_LEN
}
pub fn min_top_side_bearing_byte_range(&self) -> Range<usize> {
let start = self.advance_height_max_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn min_bottom_side_bearing_byte_range(&self) -> Range<usize> {
let start = self.min_top_side_bearing_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn y_max_extent_byte_range(&self) -> Range<usize> {
let start = self.min_bottom_side_bearing_byte_range().end;
start..start + FWord::RAW_BYTE_LEN
}
pub fn caret_slope_rise_byte_range(&self) -> Range<usize> {
let start = self.y_max_extent_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn caret_slope_run_byte_range(&self) -> Range<usize> {
let start = self.caret_slope_rise_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn caret_offset_byte_range(&self) -> Range<usize> {
let start = self.caret_slope_run_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved1_byte_range(&self) -> Range<usize> {
let start = self.caret_offset_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved2_byte_range(&self) -> Range<usize> {
let start = self.reserved1_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved3_byte_range(&self) -> Range<usize> {
let start = self.reserved2_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn reserved4_byte_range(&self) -> Range<usize> {
let start = self.reserved3_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn metric_data_format_byte_range(&self) -> Range<usize> {
let start = self.reserved4_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn number_of_long_ver_metrics_byte_range(&self) -> Range<usize> {
let start = self.metric_data_format_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
}
impl MinByteRange for VheaMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.number_of_long_ver_metrics_byte_range().end
}
}
impl TopLevelTable for Vhea<'_> {
/// `vhea`
const TAG: Tag = Tag::new(b"vhea");
}
impl<'a> FontRead<'a> for Vhea<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<Version16Dot16>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<UfWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<FWord>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<i16>();
cursor.advance::<u16>();
cursor.finish(VheaMarker {})
}
}
/// The [vhea](https://docs.microsoft.com/en-us/typography/opentype/spec/vhea) Vertical Header Table
pub type Vhea<'a> = TableRef<'a, VheaMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Vhea<'a> {
/// The major/minor version (1, 1)
pub fn version(&self) -> Version16Dot16 {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic ascent.
pub fn ascender(&self) -> FWord {
let range = self.shape.ascender_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic descent.
pub fn descender(&self) -> FWord {
let range = self.shape.descender_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Typographic line gap. Negative LineGap values are treated as
/// zero in some legacy platform implementations.
pub fn line_gap(&self) -> FWord {
let range = self.shape.line_gap_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Maximum advance height value in 'vmtx' table.
pub fn advance_height_max(&self) -> UfWord {
let range = self.shape.advance_height_max_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum top sidebearing value in 'vmtx' table for glyphs with
/// contours (empty glyphs should be ignored).
pub fn min_top_side_bearing(&self) -> FWord {
let range = self.shape.min_top_side_bearing_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Minimum bottom sidebearing value
pub fn min_bottom_side_bearing(&self) -> FWord {
let range = self.shape.min_bottom_side_bearing_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Defined as max( tsb + (yMax-yMin)).
pub fn y_max_extent(&self) -> FWord {
let range = self.shape.y_max_extent_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Used to calculate the slope of the cursor (rise/run); 1 for
/// vertical caret, 0 for horizontal.
pub fn caret_slope_rise(&self) -> i16 {
let range = self.shape.caret_slope_rise_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for vertical caret, 1 for horizontal.
pub fn caret_slope_run(&self) -> i16 {
let range = self.shape.caret_slope_run_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The amount by which a slanted highlight on a glyph needs to be
/// shifted to produce the best appearance. Set to 0 for
/// non-slanted fonts
pub fn caret_offset(&self) -> i16 {
let range = self.shape.caret_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// 0 for current format.
pub fn metric_data_format(&self) -> i16 {
let range = self.shape.metric_data_format_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of advance heights in the vertical metrics (`vmtx`) table.
pub fn number_of_long_ver_metrics(&self) -> u16 {
let range = self.shape.number_of_long_ver_metrics_byte_range();
self.data.read_at(range.start).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Vhea<'a> {
fn type_name(&self) -> &str {
"Vhea"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new("ascender", self.ascender())),
2usize => Some(Field::new("descender", self.descender())),
3usize => Some(Field::new("line_gap", self.line_gap())),
4usize => Some(Field::new("advance_height_max", self.advance_height_max())),
5usize => Some(Field::new(
"min_top_side_bearing",
self.min_top_side_bearing(),
)),
6usize => Some(Field::new(
"min_bottom_side_bearing",
self.min_bottom_side_bearing(),
)),
7usize => Some(Field::new("y_max_extent", self.y_max_extent())),
8usize => Some(Field::new("caret_slope_rise", self.caret_slope_rise())),
9usize => Some(Field::new("caret_slope_run", self.caret_slope_run())),
10usize => Some(Field::new("caret_offset", self.caret_offset())),
11usize => Some(Field::new("metric_data_format", self.metric_data_format())),
12usize => Some(Field::new(
"number_of_long_ver_metrics",
self.number_of_long_ver_metrics(),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Vhea<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+124
View File
@@ -0,0 +1,124 @@
// 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::*;
/// The [vmtx (Vertical Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/vmtx) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VmtxMarker {
v_metrics_byte_len: usize,
top_side_bearings_byte_len: usize,
}
impl VmtxMarker {
pub fn v_metrics_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + self.v_metrics_byte_len
}
pub fn top_side_bearings_byte_range(&self) -> Range<usize> {
let start = self.v_metrics_byte_range().end;
start..start + self.top_side_bearings_byte_len
}
}
impl MinByteRange for VmtxMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.top_side_bearings_byte_range().end
}
}
impl TopLevelTable for Vmtx<'_> {
/// `vmtx`
const TAG: Tag = Tag::new(b"vmtx");
}
impl ReadArgs for Vmtx<'_> {
type Args = (u16, u16);
}
impl<'a> FontReadWithArgs<'a> for Vmtx<'a> {
fn read_with_args(data: FontData<'a>, args: &(u16, u16)) -> Result<Self, ReadError> {
let (number_of_long_ver_metrics, num_glyphs) = *args;
let mut cursor = data.cursor();
let v_metrics_byte_len = (number_of_long_ver_metrics as usize)
.checked_mul(LongMetric::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(v_metrics_byte_len);
let top_side_bearings_byte_len =
(transforms::subtract(num_glyphs, number_of_long_ver_metrics))
.checked_mul(i16::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(top_side_bearings_byte_len);
cursor.finish(VmtxMarker {
v_metrics_byte_len,
top_side_bearings_byte_len,
})
}
}
impl<'a> Vmtx<'a> {
/// A constructor that requires additional arguments.
///
/// This type requires some external state in order to be
/// parsed.
pub fn read(
data: FontData<'a>,
number_of_long_ver_metrics: u16,
num_glyphs: u16,
) -> Result<Self, ReadError> {
let args = (number_of_long_ver_metrics, num_glyphs);
Self::read_with_args(data, &args)
}
}
/// The [vmtx (Vertical Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/vmtx) table
pub type Vmtx<'a> = TableRef<'a, VmtxMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Vmtx<'a> {
/// Paired advance height and top side bearing values for each
/// glyph. Records are indexed by glyph ID.
pub fn v_metrics(&self) -> &'a [LongMetric] {
let range = self.shape.v_metrics_byte_range();
self.data.read_array(range).unwrap()
}
/// Top side bearings for glyph IDs greater than or equal to numberOfLongMetrics.
pub fn top_side_bearings(&self) -> &'a [BigEndian<i16>] {
let range = self.shape.top_side_bearings_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Vmtx<'a> {
fn type_name(&self) -> &str {
"Vmtx"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new(
"v_metrics",
traversal::FieldType::array_of_records(
stringify!(LongMetric),
self.v_metrics(),
self.offset_data(),
),
)),
1usize => Some(Field::new("top_side_bearings", self.top_side_bearings())),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Vmtx<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+173
View File
@@ -0,0 +1,173 @@
// 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::*;
/// The [VORG (Vertical Origin)](https://docs.microsoft.com/en-us/typography/opentype/spec/vorg) table.
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VorgMarker {
vert_origin_y_metrics_byte_len: usize,
}
impl VorgMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn default_vert_origin_y_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + i16::RAW_BYTE_LEN
}
pub fn num_vert_origin_y_metrics_byte_range(&self) -> Range<usize> {
let start = self.default_vert_origin_y_byte_range().end;
start..start + u16::RAW_BYTE_LEN
}
pub fn vert_origin_y_metrics_byte_range(&self) -> Range<usize> {
let start = self.num_vert_origin_y_metrics_byte_range().end;
start..start + self.vert_origin_y_metrics_byte_len
}
}
impl MinByteRange for VorgMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.vert_origin_y_metrics_byte_range().end
}
}
impl TopLevelTable for Vorg<'_> {
/// `VORG`
const TAG: Tag = Tag::new(b"VORG");
}
impl<'a> FontRead<'a> for Vorg<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<i16>();
let num_vert_origin_y_metrics: u16 = cursor.read()?;
let vert_origin_y_metrics_byte_len = (num_vert_origin_y_metrics as usize)
.checked_mul(VertOriginYMetrics::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
cursor.advance_by(vert_origin_y_metrics_byte_len);
cursor.finish(VorgMarker {
vert_origin_y_metrics_byte_len,
})
}
}
/// The [VORG (Vertical Origin)](https://docs.microsoft.com/en-us/typography/opentype/spec/vorg) table.
pub type Vorg<'a> = TableRef<'a, VorgMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Vorg<'a> {
/// Major/minor version number. Set to 1.0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// The y coordinate of a glyph’s vertical origin, in the font’s design
/// coordinate system, to be used if no entry is present for the glyph
/// in the vertOriginYMetrics array.
pub fn default_vert_origin_y(&self) -> i16 {
let range = self.shape.default_vert_origin_y_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Number of elements in the vertOriginYMetrics array.
pub fn num_vert_origin_y_metrics(&self) -> u16 {
let range = self.shape.num_vert_origin_y_metrics_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Array of VertOriginYMetrics records, sorted by glyph ID.
pub fn vert_origin_y_metrics(&self) -> &'a [VertOriginYMetrics] {
let range = self.shape.vert_origin_y_metrics_byte_range();
self.data.read_array(range).unwrap()
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Vorg<'a> {
fn type_name(&self) -> &str {
"Vorg"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"default_vert_origin_y",
self.default_vert_origin_y(),
)),
2usize => Some(Field::new(
"num_vert_origin_y_metrics",
self.num_vert_origin_y_metrics(),
)),
3usize => Some(Field::new(
"vert_origin_y_metrics",
traversal::FieldType::array_of_records(
stringify!(VertOriginYMetrics),
self.vert_origin_y_metrics(),
self.offset_data(),
),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Vorg<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
/// Vertical origin Y metrics record.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct VertOriginYMetrics {
/// Glyph index.
pub glyph_index: BigEndian<GlyphId16>,
/// Y coordinate, in the font’s design coordinate system, of the glyph’s vertical origin.
pub vert_origin_y: BigEndian<i16>,
}
impl VertOriginYMetrics {
/// Glyph index.
pub fn glyph_index(&self) -> GlyphId16 {
self.glyph_index.get()
}
/// Y coordinate, in the font’s design coordinate system, of the glyph’s vertical origin.
pub fn vert_origin_y(&self) -> i16 {
self.vert_origin_y.get()
}
}
impl FixedSize for VertOriginYMetrics {
const RAW_BYTE_LEN: usize = GlyphId16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for VertOriginYMetrics {
fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
RecordResolver {
name: "VertOriginYMetrics",
get_field: Box::new(move |idx, _data| match idx {
0usize => Some(Field::new("glyph_index", self.glyph_index())),
1usize => Some(Field::new("vert_origin_y", self.vert_origin_y())),
_ => None,
}),
data,
}
}
}
+187
View File
@@ -0,0 +1,187 @@
// 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::*;
/// The [VVAR (Vertical Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/vvar) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VvarMarker {}
impl VvarMarker {
pub fn version_byte_range(&self) -> Range<usize> {
let start = 0;
start..start + MajorMinor::RAW_BYTE_LEN
}
pub fn item_variation_store_offset_byte_range(&self) -> Range<usize> {
let start = self.version_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn advance_height_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.item_variation_store_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn tsb_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.advance_height_mapping_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn bsb_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.tsb_mapping_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
pub fn v_org_mapping_offset_byte_range(&self) -> Range<usize> {
let start = self.bsb_mapping_offset_byte_range().end;
start..start + Offset32::RAW_BYTE_LEN
}
}
impl MinByteRange for VvarMarker {
fn min_byte_range(&self) -> Range<usize> {
0..self.v_org_mapping_offset_byte_range().end
}
}
impl TopLevelTable for Vvar<'_> {
/// `VVAR`
const TAG: Tag = Tag::new(b"VVAR");
}
impl<'a> FontRead<'a> for Vvar<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
cursor.advance::<MajorMinor>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.advance::<Offset32>();
cursor.finish(VvarMarker {})
}
}
/// The [VVAR (Vertical Metrics Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/vvar) table
pub type Vvar<'a> = TableRef<'a, VvarMarker>;
#[allow(clippy::needless_lifetimes)]
impl<'a> Vvar<'a> {
/// Major version number of the horizontal metrics variations table — set to 1.
/// Minor version number of the horizontal metrics variations table — set to 0.
pub fn version(&self) -> MajorMinor {
let range = self.shape.version_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Offset in bytes from the start of this table to the item variation store table.
pub fn item_variation_store_offset(&self) -> Offset32 {
let range = self.shape.item_variation_store_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`item_variation_store_offset`][Self::item_variation_store_offset].
pub fn item_variation_store(&self) -> Result<ItemVariationStore<'a>, ReadError> {
let data = self.data;
self.item_variation_store_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for advance heights (may be NULL).
pub fn advance_height_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.advance_height_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`advance_height_mapping_offset`][Self::advance_height_mapping_offset].
pub fn advance_height_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.advance_height_mapping_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for top side bearings (may be NULL).
pub fn tsb_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.tsb_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`tsb_mapping_offset`][Self::tsb_mapping_offset].
pub fn tsb_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.tsb_mapping_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for bottom side bearings (may be NULL).
pub fn bsb_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.bsb_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`bsb_mapping_offset`][Self::bsb_mapping_offset].
pub fn bsb_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.bsb_mapping_offset().resolve(data)
}
/// Offset in bytes from the start of this table to the delta-set index mapping for Y coordinates of vertical origins (may be NULL).
pub fn v_org_mapping_offset(&self) -> Nullable<Offset32> {
let range = self.shape.v_org_mapping_offset_byte_range();
self.data.read_at(range.start).unwrap()
}
/// Attempt to resolve [`v_org_mapping_offset`][Self::v_org_mapping_offset].
pub fn v_org_mapping(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
let data = self.data;
self.v_org_mapping_offset().resolve(data)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Vvar<'a> {
fn type_name(&self) -> &str {
"Vvar"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
match idx {
0usize => Some(Field::new("version", self.version())),
1usize => Some(Field::new(
"item_variation_store_offset",
FieldType::offset(
self.item_variation_store_offset(),
self.item_variation_store(),
),
)),
2usize => Some(Field::new(
"advance_height_mapping_offset",
FieldType::offset(
self.advance_height_mapping_offset(),
self.advance_height_mapping(),
),
)),
3usize => Some(Field::new(
"tsb_mapping_offset",
FieldType::offset(self.tsb_mapping_offset(), self.tsb_mapping()),
)),
4usize => Some(Field::new(
"bsb_mapping_offset",
FieldType::offset(self.bsb_mapping_offset(), self.bsb_mapping()),
)),
5usize => Some(Field::new(
"v_org_mapping_offset",
FieldType::offset(self.v_org_mapping_offset(), self.v_org_mapping()),
)),
_ => None,
}
}
}
#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Vvar<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(self as &dyn SomeTable<'a>).fmt(f)
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Custom array types
#![deny(clippy::arithmetic_side_effects)]
use bytemuck::AnyBitPattern;
use font_types::FixedSize;
use crate::read::{ComputeSize, FontReadWithArgs, ReadArgs, VarSize};
use crate::{FontData, FontRead, ReadError};
/// An array whose items size is not known at compile time.
///
/// This requires the inner type to implement [`FontReadWithArgs`] as well as
/// [`ComputeSize`].
///
/// At runtime, `Args` are provided which will be used to compute the size
/// of each item; this size is then used to compute the positions of the items
/// within the underlying data, from which they will be read lazily.
#[derive(Clone)]
pub struct ComputedArray<'a, T: ReadArgs> {
// the length of each item
item_len: usize,
len: usize,
data: FontData<'a>,
args: T::Args,
}
impl<'a, T: ComputeSize> ComputedArray<'a, T> {
pub fn new(data: FontData<'a>, args: T::Args) -> Result<Self, ReadError> {
let item_len = T::compute_size(&args)?;
let len = data.len().checked_div(item_len).unwrap_or(0);
Ok(ComputedArray {
item_len,
len,
data,
args,
})
}
/// The number of items in the array
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
}
impl<T: ReadArgs> ReadArgs for ComputedArray<'_, T> {
type Args = T::Args;
}
impl<'a, T> FontReadWithArgs<'a> for ComputedArray<'a, T>
where
T: ComputeSize + FontReadWithArgs<'a>,
T::Args: Copy,
{
fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, ReadError> {
Self::new(data, *args)
}
}
impl<'a, T> ComputedArray<'a, T>
where
T: FontReadWithArgs<'a>,
T::Args: Copy + 'static,
{
pub fn iter(&self) -> impl Iterator<Item = Result<T, ReadError>> + 'a {
let mut i = 0;
let data = self.data;
let args = self.args;
let item_len = self.item_len;
let len = self.len;
std::iter::from_fn(move || {
if i == len {
return None;
}
let item_start = item_len.checked_mul(i)?;
i = i.checked_add(1)?;
let data = data.split_off(item_start)?;
Some(T::read_with_args(data, &args))
})
}
pub fn get(&self, idx: usize) -> Result<T, ReadError> {
let item_start = idx
.checked_mul(self.item_len)
.ok_or(ReadError::OutOfBounds)?;
self.data
.split_off(item_start)
.ok_or(ReadError::OutOfBounds)
.and_then(|data| T::read_with_args(data, &self.args))
}
}
impl<T: ReadArgs> std::fmt::Debug for ComputedArray<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("DynSizedArray")
.field("bytes", &self.data)
.finish()
}
}
/// An array of items of non-uniform length.
///
/// Random access into this array cannot be especially efficient, since it requires
/// a linear scan.
pub struct VarLenArray<'a, T> {
data: FontData<'a>,
phantom: std::marker::PhantomData<*const T>,
}
impl<'a, T: FontRead<'a> + VarSize> VarLenArray<'a, T> {
/// Return the item at the provided index.
///
/// # Performance
///
/// Determining the position of an item in this collection requires looking
/// at all the preceding items; that is, it is `O(n)` instead of `O(1)` as
/// it would be for a `Vec`.
///
/// As a consequence, calling this method in a loop could potentially be
/// very slow. If this is something you need to do, it will probably be
/// much faster to first collect all the items into a `Vec` beforehand,
/// and then fetch them from there.
pub fn get(&self, idx: usize) -> Option<Result<T, ReadError>> {
let mut pos = 0usize;
for _ in 0..idx {
pos = pos.checked_add(T::read_len_at(self.data, pos)?)?;
}
self.data.split_off(pos).map(T::read)
}
/// Return an iterator over this array's items.
pub fn iter(&self) -> impl Iterator<Item = Result<T, ReadError>> + 'a {
let mut data = self.data;
std::iter::from_fn(move || {
if data.is_empty() {
return None;
}
let item_len = T::read_len_at(data, 0)?;
// If the length is 0 then then it's not useful to continue
// iteration. The subsequent read will probably fail but if
// the user is skipping malformed elements (which is common)
// this this iterator will continue forever.
if item_len == 0 {
return None;
}
let item_data = data.slice(..item_len)?;
let next = T::read(item_data);
data = data.split_off(item_len)?;
Some(next)
})
}
}
impl<'a, T> FontRead<'a> for VarLenArray<'a, T> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
Ok(VarLenArray {
data,
phantom: core::marker::PhantomData,
})
}
}
impl<T: AnyBitPattern> ReadArgs for &[T] {
type Args = u16;
}
impl<'a, T: AnyBitPattern + FixedSize> FontReadWithArgs<'a> for &'a [T] {
fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
let len = (*args as usize)
.checked_mul(T::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
data.read_array(0..len)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codegen_test::records::VarLenItem;
use font_test_data::bebuffer::BeBuffer;
impl VarSize for VarLenItem<'_> {
type Size = u32;
fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
data.read_at::<u32>(pos).ok().map(|len| len as usize)
}
}
/// HB/HarfRuzz test "shlana_9_006" has a morx table containing a chain
/// with a length of 0. This caused the VarLenArray iterator to loop
/// indefinitely.
#[test]
fn var_len_iter_with_zero_length_item() {
// Create a buffer containing three elements where the last
// has zero length
let mut buf = BeBuffer::new();
buf = buf.push(8u32).extend([0u8; 4]);
buf = buf.push(18u32).extend([0u8; 14]);
buf = buf.push(0u32);
let arr: VarLenArray<VarLenItem> = VarLenArray::read(FontData::new(buf.data())).unwrap();
// Ensure we don't iterate forever and only read two elements (the
// take() exists so that the test fails rather than hanging if the
// code regresses in the future)
assert_eq!(arr.iter().take(10).count(), 2);
}
}
+338
View File
@@ -0,0 +1,338 @@
//! A module used to test codegen.
//!
//! This imports a single codegen output; while modifying the codegen crate,
//! this file can be regenerated to check that changes compile, without needing
//! to rebuild everything.
//!
//! To rebuild this input and test it, run:
//!
//! $ cargo run --bin=codegen resources/test_plan.toml && cargo test
pub mod records {
include!("../generated/generated_test_records.rs");
}
pub mod formats {
include!("../generated/generated_test_formats.rs");
}
pub mod offsets_arrays {
include!("../generated/generated_test_offsets_arrays.rs");
#[cfg(test)]
use font_test_data::bebuffer::BeBuffer;
pub struct VarSizeDummy<'a> {
#[allow(dead_code)]
count: u16,
pub bytes: &'a [u8],
}
impl VarSize for VarSizeDummy<'_> {
type Size = u16;
}
impl<'a> FontRead<'a> for VarSizeDummy<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let count: u16 = data.read_at(0)?;
let bytes = data
.as_bytes()
.get(2..2 + (count as usize))
.ok_or(ReadError::OutOfBounds)?;
Ok(Self { count, bytes })
}
}
#[test]
fn array_offsets() {
let builder = BeBuffer::new()
.push(MajorMinor::VERSION_1_0)
.push(12_u16) // offset to 0xdead
.push(0u16) // nullable
.push(2u16) // array len
.push(12u16) // array offset
.extend([0xdead_u16, 0xbeef]);
let table = KindsOfOffsets::read(builder.data().into()).unwrap();
assert_eq!(table.nonnullable().unwrap().value(), 0xdead);
let array = table.array().unwrap();
assert_eq!(array, &[0xdead, 0xbeef]);
}
#[test]
fn var_len_array_empty() {
let builder = BeBuffer::new().push(0u16).push(0xdeadbeef_u32);
let table = VarLenHaver::read(builder.data().into()).unwrap();
assert_eq!(table.other_field(), 0xdeadbeef);
}
#[test]
fn var_len_array_some() {
let builder = BeBuffer::new()
.push(3u16)
.push(0u16) // first item in array is empty
.push(2u16)
.extend([1u8, 1])
.push(5u16)
.extend([7u8, 7, 7, 7, 7])
.push(0xdeadbeef_u32);
let table = VarLenHaver::read(builder.data().into()).unwrap();
let kids = table
.var_len()
.iter()
.map(|x| x.unwrap())
.collect::<Vec<_>>();
assert!(kids[0].bytes.is_empty());
assert_eq!(kids[1].bytes, &[1, 1]);
assert_eq!(kids[2].bytes, &[7, 7, 7, 7, 7]);
assert_eq!(table.other_field(), 0xdeadbeef)
}
#[test]
#[cfg(feature = "experimental_traverse")]
fn array_offsets_traverse() {
let mut builder = BeBuffer::new()
.push(MajorMinor::VERSION_1_1)
.push(22_u16) // offset to [0xf00, 0xba4]
.push(0u16) // nullable
.push(2u16) // array len
.push(26u16) // offset to [69, 70]
.push(30u16) // record_array_offset
.push(0u16) // versioned_nullable_record_array_offset
.push(42u16) // versioned nonnullable offset
.push(0u32); // versioned nullable offset
//
let data_start = builder.len();
assert_eq!(data_start, 22);
builder = builder
.extend([0xf00u16, 0xba4])
.extend([69u16, 70])
.push(3u16) // shmecord[0]
.push(9u32)
.push(5u16) // shmecord[1]
.push(0xdead_beefu32)
.extend([0xb01du16, 0xface]); // versioned nonnullable offset;
let table = KindsOfOffsets::read(builder.data().into()).unwrap();
// traversal should not crash
let _ = format!("{table:?}");
assert_eq!(
table.versioned_nonnullable().unwrap().unwrap().value(),
0xb01d
);
}
}
pub mod flags {
include!("../generated/generated_test_flags.rs");
#[test]
fn basics() {
let all = ValueFormat::all();
let none = ValueFormat::empty();
assert!(all.contains(ValueFormat::X_PLACEMENT));
assert!(all.contains(ValueFormat::Y_PLACEMENT));
assert!(!none.contains(ValueFormat::X_PLACEMENT));
assert!(!none.contains(ValueFormat::Y_PLACEMENT));
assert_eq!(none, ValueFormat::default());
}
#[test]
fn formatting() {
let all = ValueFormat::all();
assert_eq!(format!("{all:?}"), "X_PLACEMENT | Y_PLACEMENT");
let none = ValueFormat::empty();
assert_eq!(format!("{none:?}"), "(empty)");
let xplace = ValueFormat::X_PLACEMENT;
assert_eq!(format!("{xplace:?}"), "X_PLACEMENT");
}
// not exactly a test, but this will fail to compile if these are missing
#[test]
fn impl_traits() {
fn impl_check<T: Copy + std::hash::Hash + Eq + Ord>() {}
impl_check::<ValueFormat>();
}
}
pub mod enums {
include!("../generated/generated_test_enum.rs");
}
pub mod count_all {
use crate::FontData;
include!("../generated/generated_test_count_all.rs");
/// Test for count(..) with element sizes > 1
#[test]
fn element_size_greater_than_one_with_padding() {
// Size of 13 ensures we have an extra padding byte
let bytes = [0u8; 13];
// Generated table has a 2 byte field above the array
let remainder_len = bytes.len() - 2;
let data = FontData::new(&bytes);
// Trailing array with 16-bit elements
assert!(remainder_len % 2 != 0);
let count16 = CountAll16::read(data).unwrap();
assert_eq!(count16.remainder().len(), remainder_len / 2);
// Trailing array with 32-bit elements
assert!(remainder_len % 4 != 0);
let count32 = CountAll32::read(data).unwrap();
assert_eq!(count32.remainder().len(), remainder_len / 4);
}
}
pub mod conditions {
#[cfg(test)]
use font_test_data::bebuffer::BeBuffer;
use font_types::MajorMinor;
include!("../generated/generated_test_conditions.rs");
#[test]
fn majorminor_1() {
let bytes = BeBuffer::new().push(MajorMinor::VERSION_1_0).push(0u16);
let table = MajorMinorVersion::read(bytes.data().into()).unwrap();
assert_eq!(table.always_present(), 0);
}
#[test]
fn majorminor_1_1() {
let bytes = BeBuffer::new().push(MajorMinor::VERSION_1_1).push(0u16);
// shouldn't parse, we're missing a field
assert!(MajorMinorVersion::read(bytes.data().into()).is_err());
let bytes = BeBuffer::new()
.push(MajorMinor::VERSION_1_1)
.push(0u16)
.push(1u16);
let table = MajorMinorVersion::read(bytes.data().into()).unwrap();
assert_eq!(table.if_11(), Some(1));
}
#[test]
fn major_minor_2() {
let bytes = BeBuffer::new().push(MajorMinor::VERSION_2_0).push(0u16);
// shouldn't parse, we're missing a field
assert!(MajorMinorVersion::read(bytes.data().into()).is_err());
let bytes = BeBuffer::new()
.push(MajorMinor::VERSION_2_0)
.push(0u16)
.push(2u32);
let table = MajorMinorVersion::read(bytes.data().into()).unwrap();
assert_eq!(table.if_11(), None);
assert_eq!(table.if_20(), Some(2));
}
#[cfg(test)]
fn make_flag_data(flags: GotFlags) -> BeBuffer {
let mut buf = BeBuffer::new().push(42u16).push(flags);
if flags.contains(GotFlags::FOO) {
buf = buf.push(0xf00_u16);
}
if flags.contains(GotFlags::BAR) {
buf = buf.push(0xba4_u16);
}
if flags.contains(GotFlags::FOO) || flags.contains(GotFlags::BAZ) {
buf = buf.push(0xba2_u16);
}
buf
}
#[test]
fn flags_none() {
let data = make_flag_data(GotFlags::empty());
let table = FlagDay::read(data.data().into()).unwrap();
assert!(table.foo().is_none());
assert!(table.bar().is_none());
}
#[test]
fn flags_foo() {
let data = make_flag_data(GotFlags::FOO);
let table = FlagDay::read(data.data().into()).unwrap();
assert_eq!(table.foo(), Some(0xf00));
assert!(table.bar().is_none());
assert_eq!(table.baz(), Some(0xba2));
}
#[test]
fn flags_bar() {
let data = make_flag_data(GotFlags::BAR);
let table = FlagDay::read(data.data().into()).unwrap();
assert!(table.foo().is_none());
assert_eq!(table.bar(), Some(0xba4));
assert!(table.baz().is_none());
}
#[test]
fn flags_baz() {
let data = make_flag_data(GotFlags::BAZ);
let table = FlagDay::read(data.data().into()).unwrap();
assert!(table.foo().is_none());
assert!(table.bar().is_none());
assert_eq!(table.baz(), Some(0xba2));
}
#[test]
fn flags_foobar() {
let data = make_flag_data(GotFlags::BAR | GotFlags::FOO);
let table = FlagDay::read(data.data().into()).unwrap();
assert_eq!(table.foo(), Some(0xf00));
assert_eq!(table.bar(), Some(0xba4));
assert_eq!(table.baz(), Some(0xba2));
}
#[test]
fn fields_after_conditions_all_none() {
let data = BeBuffer::new().push(GotFlags::empty()).extend([1u16, 2, 3]);
let table = FieldsAfterConditionals::read(data.data().into()).unwrap();
assert_eq!(table.always_here(), 1);
assert_eq!(table.also_always_here(), 2);
assert_eq!(table.and_me_too(), 3);
}
#[test]
#[should_panic(expected = "OutOfBounds")]
fn fields_after_conditions_wrong_len() {
let data = BeBuffer::new().push(GotFlags::FOO).extend([1u16, 2, 3]);
let _table = FieldsAfterConditionals::read(data.data().into()).unwrap();
}
#[test]
fn fields_after_conditionals_one_present() {
let data = BeBuffer::new()
.push(GotFlags::BAR)
.extend([1u16, 0xba4, 2, 3]);
let table = FieldsAfterConditionals::read(data.data().into()).unwrap();
assert_eq!(table.always_here(), 1);
assert_eq!(table.bar(), Some(0xba4));
assert_eq!(table.also_always_here(), 2);
assert!(table.foo().is_none() && table.baz().is_none());
assert_eq!(table.and_me_too(), 3);
}
#[test]
fn fields_after_conditions_all_present() {
let data = BeBuffer::new()
.push(GotFlags::FOO | GotFlags::BAR | GotFlags::BAZ)
.extend([0xf00u16, 1, 0xba4, 0xba2, 2, 3]);
let table = FieldsAfterConditionals::read(data.data().into()).unwrap();
assert_eq!(table.foo(), Some(0xf00));
assert_eq!(table.always_here(), 1);
assert_eq!(table.bar(), Some(0xba4));
assert_eq!(table.baz(), Some(0xba2));
assert_eq!(table.also_always_here(), 2);
assert_eq!(table.and_me_too(), 3);
}
}
+7
View File
@@ -0,0 +1,7 @@
//! Data structures useful for font work.
pub mod int_set;
pub use int_set::IntSet;
mod range_set;
pub use range_set::RangeSet;
+831
View File
@@ -0,0 +1,831 @@
//! Stores a page of bits, used inside of bitset's.
use std::{hash::Hash, ops::RangeInclusive};
// the integer type underlying our bit set
type Element = u64;
// the number of elements in a page
const PAGE_SIZE: u32 = 8;
// the length of an element in bytes
const ELEM_SIZE: u32 = std::mem::size_of::<Element>() as u32;
// the length of an element in bits
const ELEM_BITS: u32 = ELEM_SIZE * 8;
// mask out bits of a value not used to index into an element
const ELEM_MASK: u32 = ELEM_BITS - 1;
// the number of bits in a page
pub(crate) const PAGE_BITS: u32 = ELEM_BITS * PAGE_SIZE;
// mask out the bits of a value not used to index into a page
const PAGE_MASK: u32 = PAGE_BITS - 1;
/// A fixed size (512 bits wide) page of bits that records integer set membership from `[0, 511]`.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct BitPage {
storage: [Element; PAGE_SIZE as usize],
length: u32,
}
impl BitPage {
/// Create a new page with no bits set.
pub(crate) fn new_zeroes() -> Self {
Self {
storage: [0; PAGE_SIZE as usize],
length: 0,
}
}
pub(crate) fn recompute_length(&mut self) {
self.length = self.storage.iter().copied().map(u64::count_ones).sum();
}
/// Returns the number of members in this page.
pub(crate) fn len(&self) -> u32 {
self.length
}
/// Returns true if this page has no members.
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
// TODO(garretrieger): iterator that starts after some value (similar to next in hb).
// TODO(garretrieger): reverse iterator.
/// Iterator over the members of this page.
pub(crate) fn iter(&self) -> impl DoubleEndedIterator<Item = u32> + '_ {
self.storage
.iter()
.enumerate()
.filter(|(_, elem)| **elem != 0)
.flat_map(|(i, elem)| {
let base = i as u32 * ELEM_BITS;
Iter::new(*elem).map(move |idx| base + idx)
})
}
/// Iterator over the members of this page starting from value.
///
/// So value is included in the iterator if it's in the page.
pub(crate) fn iter_from(&self, value: u32) -> impl DoubleEndedIterator<Item = u32> + '_ {
let start_index = Self::element_index(value);
self.storage[start_index..]
.iter()
.enumerate()
.filter(|(_, elem)| **elem != 0)
.flat_map(move |(i, elem)| {
let i = i + start_index;
let base = i as u32 * ELEM_BITS;
let it = if start_index == i {
let index_in_elem = value & ELEM_MASK;
Iter::from(*elem, index_in_elem)
} else {
Iter::new(*elem)
};
it.map(move |idx| base + idx)
})
}
/// Iterator over the ranges in this page.
pub(crate) fn iter_ranges(&self) -> RangeIter<'_> {
RangeIter {
page: self,
next_value_to_check: 0,
}
}
/// Marks `(val % page width)` a member of this set and returns `true` if it is newly added.
pub(crate) fn insert(&mut self, val: u32) -> bool {
let el_mut = self.element_mut(val);
let mask = elem_index_bit_mask(val);
let is_new = (*el_mut & mask) == 0;
*el_mut |= mask;
self.length += is_new as u32;
is_new
}
/// Marks all values `[first, last]` as members of this set.
pub(crate) fn insert_range(&mut self, first: u32, last: u32) {
let first = first & PAGE_MASK;
let last = last & PAGE_MASK;
let first_elem_idx = first / ELEM_BITS;
let last_elem_idx = last / ELEM_BITS;
for elem_idx in first_elem_idx..=last_elem_idx {
let elem_start = first.max(elem_idx * ELEM_BITS) & ELEM_MASK;
let elem_last = last.min(((elem_idx + 1) * ELEM_BITS) - 1) & ELEM_MASK;
let end_shift = ELEM_BITS - elem_last - 1;
let mask = u64::MAX << (elem_start + end_shift);
let mask = mask >> end_shift;
self.storage[elem_idx as usize] |= mask;
}
self.recompute_length();
}
/// Marks all values `[first, last]` as not members of this set.
pub(crate) fn remove_range(&mut self, first: u32, last: u32) {
let first = first & PAGE_MASK;
let last = last & PAGE_MASK;
let first_elem_idx = first / ELEM_BITS;
let last_elem_idx = last / ELEM_BITS;
for elem_idx in first_elem_idx..=last_elem_idx {
let elem_start = first.max(elem_idx * ELEM_BITS) & ELEM_MASK;
let elem_last = last.min(((elem_idx + 1) * ELEM_BITS) - 1) & ELEM_MASK;
let end_shift = ELEM_BITS - elem_last - 1;
let mask = u64::MAX << (elem_start + end_shift);
let mask = !(mask >> end_shift);
self.storage[elem_idx as usize] &= mask;
}
self.recompute_length();
}
pub(crate) fn clear(&mut self) {
for elem in self.storage.iter_mut() {
*elem = 0;
}
self.length = 0;
}
/// Removes `(val % page width)` from this set.
pub(crate) fn remove(&mut self, val: u32) -> bool {
let ret = self.contains(val);
*self.element_mut(val) &= !elem_index_bit_mask(val);
self.length -= ret as u32;
ret
}
/// Return true if `(val % page width)` is a member of this set.
pub(crate) fn contains(&self, val: u32) -> bool {
(*self.element(val) & elem_index_bit_mask(val)) != 0
}
pub(crate) fn union(a: &BitPage, b: &BitPage) -> BitPage {
a.process(b, |a, b| a | b)
}
pub(crate) fn intersect(a: &BitPage, b: &BitPage) -> BitPage {
a.process(b, |a, b| a & b)
}
pub(crate) fn subtract(a: &BitPage, b: &BitPage) -> BitPage {
a.process(b, |a, b| a & !b)
}
fn process<Op>(&self, other: &BitPage, op: Op) -> BitPage
where
Op: Fn(Element, Element) -> Element,
{
let mut out = BitPage::new_zeroes();
for i in 0usize..(PAGE_SIZE as usize) {
out.storage[i] = op(self.storage[i], other.storage[i]);
}
out.recompute_length();
out
}
fn element(&self, value: u32) -> &Element {
&self.storage[Self::element_index(value)]
}
fn element_mut(&mut self, value: u32) -> &mut Element {
&mut self.storage[Self::element_index(value)]
}
const fn element_index(value: u32) -> usize {
(value as usize & PAGE_MASK as usize) / (ELEM_BITS as usize)
}
}
/// returns the bit to set in an element for this value
const fn elem_index_bit_mask(value: u32) -> Element {
1 << (value & ELEM_MASK)
}
struct Iter {
val: Element,
forward_index: i32,
backward_index: i32,
}
impl Iter {
fn new(elem: Element) -> Iter {
Iter {
val: elem,
forward_index: 0,
backward_index: ELEM_BITS as i32 - 1,
}
}
/// Construct an iterator that starts at `index`
///
/// Specifically if `index` bit is set it will be returned on the first call to `next()`.
fn from(elem: Element, index: u32) -> Iter {
Iter {
val: elem,
forward_index: index as i32, // index is at most 63
backward_index: ELEM_BITS as i32 - 1,
}
}
}
impl Iterator for Iter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.forward_index > self.backward_index {
return None;
}
let mask = (1u64 << self.forward_index) - 1;
let masked = self.val & !mask;
let next_index = masked.trailing_zeros() as i32;
if next_index > self.backward_index {
return None;
}
self.forward_index = next_index + 1;
Some(next_index as u32)
}
}
impl DoubleEndedIterator for Iter {
fn next_back(&mut self) -> Option<Self::Item> {
if self.backward_index < self.forward_index {
return None;
}
let mask = 1u64
.checked_shl(self.backward_index as u32 + 1)
.map(|v| v - 1)
.unwrap_or(Element::MAX);
let masked = self.val & mask;
let next_index = (ELEM_BITS as i32) - (masked.leading_zeros() as i32) - 1;
if next_index < self.forward_index {
return None;
}
self.backward_index = next_index - 1;
Some(next_index as u32)
}
}
pub(crate) struct RangeIter<'a> {
page: &'a BitPage,
next_value_to_check: u32,
}
impl RangeIter<'_> {
fn next_range_in_element(&self) -> Option<RangeInclusive<u32>> {
if self.next_value_to_check >= PAGE_BITS {
return None;
}
let element = self.page.element(self.next_value_to_check);
let element_bit = (self.next_value_to_check & ELEM_MASK) as u64;
let major = self.next_value_to_check & !ELEM_MASK;
let mask = !((1 << element_bit) - 1);
let range_start = (element & mask).trailing_zeros();
if range_start == ELEM_BITS {
// There's no remaining values in this element.
return None;
}
let mask = (1 << range_start) - 1;
let range_end = (element | mask).trailing_ones() - 1;
Some((major + range_start)..=(major + range_end))
}
}
impl Iterator for RangeIter<'_> {
type Item = RangeInclusive<u32>;
fn next(&mut self) -> Option<Self::Item> {
let mut current_range = self.next_range_in_element();
loop {
let element_end = (self.next_value_to_check & !ELEM_MASK) + ELEM_BITS - 1;
let Some(range) = current_range.clone() else {
// No more ranges in the current element, move to the next one.
self.next_value_to_check = element_end + 1;
if self.next_value_to_check < PAGE_BITS {
current_range = self.next_range_in_element();
continue;
} else {
return None;
}
};
self.next_value_to_check = range.end() + 1;
if *range.end() == element_end {
let continuation = self.next_range_in_element();
if let Some(continuation) = continuation {
if *continuation.start() == element_end + 1 {
current_range = Some(*range.start()..=*continuation.end());
continue;
}
}
}
break;
}
current_range
}
}
impl Default for BitPage {
fn default() -> Self {
Self::new_zeroes()
}
}
impl std::fmt::Debug for BitPage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
let values: Vec<_> = self.iter().collect();
std::fmt::Debug::fmt(&values, f)
}
}
impl Hash for BitPage {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.storage.hash(state);
}
}
impl std::cmp::PartialEq for BitPage {
fn eq(&self, other: &Self) -> bool {
self.storage == other.storage
}
}
impl std::cmp::Eq for BitPage {}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use super::*;
impl BitPage {
/// Create a new page with all bits set.
fn new_ones() -> Self {
Self {
storage: [Element::MAX; PAGE_SIZE as usize],
length: PAGE_SIZE * ELEM_BITS,
}
}
}
impl FromIterator<u32> for BitPage {
fn from_iter<I: IntoIterator<Item = u32>>(iter: I) -> Self {
let mut out = BitPage::new_zeroes();
for v in iter {
out.insert(v);
}
out
}
}
#[test]
fn test_iter_bit_indices() {
let items: Vec<_> = Iter::new(0).collect();
assert_eq!(items.len(), 0);
let items: Vec<_> = Iter::new(1).collect();
assert_eq!(items, vec![0]);
let items: Vec<_> = Iter::new(0b1100).collect();
assert_eq!(items, vec![2, 3]);
let items: Vec<_> = Iter::new(1 << 63).collect();
assert_eq!(items, vec![63]);
let items: Vec<_> = Iter::new((1 << 47) | (1 << 63)).collect();
assert_eq!(items, vec![47, 63]);
assert_eq!(Iter::new(Element::MAX).max(), Some(ELEM_BITS - 1));
assert_eq!(Iter::new(Element::MAX).min(), Some(0));
}
#[test]
fn test_iter_bit_indices_backwards() {
let mut it = Iter::new(0);
assert_eq!(None, it.next());
assert_eq!(None, it.next_back());
let mut it = Iter::new((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6));
assert_eq!(Some(1), it.next());
assert_eq!(Some(6), it.next_back());
assert_eq!(Some(5), it.next_back());
assert_eq!(Some(2), it.next());
assert_eq!(Some(3), it.next());
assert_eq!(Some(4), it.next());
assert_eq!(None, it.next());
assert_eq!(None, it.next_back());
let mut it = Iter::new(1);
assert_eq!(Some(0), it.next_back());
assert_eq!(None, it.next_back());
let mut it = Iter::new(1 << 63);
assert_eq!(Some(63), it.next_back());
assert_eq!(None, it.next_back());
let mut it = Iter::new((1 << 63) | (1 << 62));
assert_eq!(Some(63), it.next_back());
assert_eq!(Some(62), it.next_back());
assert_eq!(None, it.next_back());
let mut it = Iter::new((1 << 63) | (1 << 32));
assert_eq!(Some(63), it.next_back());
assert_eq!(Some(32), it.next_back());
assert_eq!(None, it.next_back());
}
#[test]
fn page_init() {
let page = BitPage::new_zeroes();
assert_eq!(page.len(), 0);
assert!(page.is_empty());
}
#[test]
fn page_init_ones() {
let page = BitPage::new_ones();
assert_eq!(page.len(), 512);
assert!(!page.is_empty());
}
#[test]
fn page_contains_empty() {
let page = BitPage::new_zeroes();
assert!(!page.contains(0));
assert!(!page.contains(1));
assert!(!page.contains(75475));
}
#[test]
fn page_contains_all() {
let page = BitPage::new_ones();
assert!(page.contains(0));
assert!(page.contains(1));
assert!(page.contains(75475));
}
#[test]
fn page_insert() {
for val in 0..=1025 {
let mut page = BitPage::new_zeroes();
assert!(!page.contains(val), "unexpected {val} (1)");
page.insert(val);
assert!(page.contains(val), "missing {val}");
assert!(!page.contains(val.wrapping_sub(1)), "unexpected {val} (2)");
}
}
#[test]
fn page_insert_range() {
fn page_for_range(first: u32, last: u32) -> BitPage {
let mut page = BitPage::new_zeroes();
for i in first..=last {
page.insert(i);
}
page
}
for range in [
(0, 0),
(0, 1),
(1, 15),
(5, 63),
(64, 67),
(69, 72),
(69, 127),
(32, 345),
(512 + 32, 512 + 345),
(0, 511),
] {
let mut page = BitPage::new_zeroes();
page.insert_range(range.0, range.1);
assert_eq!(page, page_for_range(range.0, range.1), "{range:?}");
}
}
#[test]
fn page_insert_return() {
let mut page = BitPage::new_zeroes();
assert!(page.insert(123));
assert!(!page.insert(123));
}
#[test]
fn page_remove() {
for val in 0..=1025 {
let mut page = BitPage::new_ones();
assert!(page.contains(val), "missing {val} (1)");
assert!(page.remove(val));
assert!(!page.remove(val));
assert!(!page.contains(val), "unexpected {val}");
assert!(page.contains(val.wrapping_sub(1)), "missing {val} (2)");
}
}
#[test]
fn page_remove_range() {
fn page_for_range(first: u32, last: u32) -> BitPage {
let mut page = BitPage::new_ones();
for i in first..=last {
page.remove(i);
}
page
}
for exclude_range in [
(0, 0),
(0, 1),
(1, 15),
(5, 63),
(64, 67),
(69, 72),
(69, 127),
(32, 345),
(0, 511),
(512 + 32, 512 + 345),
] {
let mut page = BitPage::new_ones();
page.remove_range(exclude_range.0, exclude_range.1);
assert_eq!(
page,
page_for_range(exclude_range.0, exclude_range.1),
"{exclude_range:?}"
);
}
}
#[test]
fn clear() {
let mut zeroes = BitPage::new_zeroes();
let mut ones = BitPage::new_ones();
zeroes.clear();
assert_eq!(zeroes.len(), 0);
assert_eq!(zeroes.iter().next(), None);
zeroes.insert_range(10, 300);
zeroes.clear();
assert_eq!(zeroes.len(), 0);
assert_eq!(zeroes.iter().next(), None);
ones.clear();
assert_eq!(ones.len(), 0);
assert_eq!(ones.iter().next(), None);
}
#[test]
fn remove_to_empty_page() {
let mut page = BitPage::new_zeroes();
page.insert(13);
assert!(!page.is_empty());
page.remove(13);
assert!(page.is_empty());
}
#[test]
fn page_iter() {
let mut page = BitPage::new_zeroes();
page.insert(0);
page.insert(12);
page.insert(13);
page.insert(63);
page.insert(64);
page.insert(511);
page.insert(23);
page.insert(400);
page.insert(78);
let items: Vec<_> = page.iter().collect();
assert_eq!(items, vec![0, 12, 13, 23, 63, 64, 78, 400, 511,])
}
#[test]
fn page_iter_overflow() {
let mut page = BitPage::new_zeroes();
page.insert(0);
let mut it = page.iter();
assert_eq!(Some(0), it.next_back());
assert_eq!(None, it.next());
}
#[test]
fn page_iter_from() {
let mut page = BitPage::new_zeroes();
let items: Vec<_> = page.iter_from(0).collect();
assert!(items.is_empty());
let items: Vec<_> = page.iter_from(256).collect();
assert!(items.is_empty());
page.insert(1);
page.insert(12);
page.insert(13);
page.insert(63);
page.insert(64);
page.insert(511);
page.insert(23);
page.insert(400);
page.insert(78);
let items: Vec<_> = page.iter_from(0).collect();
assert_eq!(items, vec![1, 12, 13, 23, 63, 64, 78, 400, 511,]);
page.insert(0);
let items: Vec<_> = page.iter_from(0).collect();
assert_eq!(items, vec![0, 1, 12, 13, 23, 63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(1).collect();
assert_eq!(items, vec![1, 12, 13, 23, 63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(2).collect();
assert_eq!(items, vec![12, 13, 23, 63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(63).collect();
assert_eq!(items, vec![63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(256).collect();
assert_eq!(items, vec![400, 511]);
let items: Vec<_> = page.iter_from(511).collect();
assert_eq!(items, vec![511]);
let items: Vec<_> = page.iter_from(512).collect(); // page has 511 values, so 512 wraps around and acts like '0'
assert_eq!(items, vec![0, 1, 12, 13, 23, 63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(515).collect(); // page has 511 values, so 515 wraps around and acts like '3'
assert_eq!(items, vec![12, 13, 23, 63, 64, 78, 400, 511,]);
let items: Vec<_> = page.iter_from(390).collect();
assert_eq!(items, vec![400, 511]);
let items: Vec<_> = page.iter_from(400).collect();
assert_eq!(items, vec![400, 511]);
let items: Vec<_> = page.iter_from(401).collect();
assert_eq!(items, vec![511]);
}
#[test]
fn page_iter_after_rev() {
let mut page = BitPage::new_zeroes();
let items: Vec<_> = page.iter_from(0).collect();
assert!(items.is_empty());
let items: Vec<_> = page.iter_from(256).collect();
assert!(items.is_empty());
page.insert(1);
page.insert(12);
page.insert(13);
page.insert(63);
page.insert(64);
page.insert(511);
page.insert(23);
page.insert(400);
page.insert(78);
let items: Vec<_> = page.iter_from(0).rev().collect();
assert_eq!(items, vec![511, 400, 78, 64, 63, 23, 13, 12, 1]);
page.insert(0);
let items: Vec<_> = page.iter_from(0).rev().collect();
assert_eq!(items, vec![511, 400, 78, 64, 63, 23, 13, 12, 1, 0]);
let items: Vec<_> = page.iter_from(1).rev().collect();
assert_eq!(items, vec![511, 400, 78, 64, 63, 23, 13, 12, 1]);
let items: Vec<_> = page.iter_from(63).rev().collect();
assert_eq!(items, vec![511, 400, 78, 64, 63]);
let items: Vec<_> = page.iter_from(256).rev().collect();
assert_eq!(items, vec![511, 400]);
let items: Vec<_> = page.iter_from(512).rev().collect();
assert_eq!(items, vec![511, 400, 78, 64, 63, 23, 13, 12, 1, 0]);
let items: Vec<_> = page.iter_from(390).rev().collect();
assert_eq!(items, vec![511, 400]);
let items: Vec<_> = page.iter_from(400).rev().collect();
assert_eq!(items, vec![511, 400]);
let items: Vec<_> = page.iter_from(401).rev().collect();
assert_eq!(items, vec![511]);
}
fn check_iter_ranges(ranges: Vec<RangeInclusive<u32>>) {
let mut page = BitPage::new_zeroes();
for range in ranges.iter() {
page.insert_range(*range.start(), *range.end());
}
let items: Vec<_> = page.iter_ranges().collect();
assert_eq!(items, ranges);
}
#[test]
fn iter_ranges() {
// basic
check_iter_ranges(vec![]);
check_iter_ranges(vec![0..=5]);
check_iter_ranges(vec![0..=0, 5..=5, 10..=10]);
check_iter_ranges(vec![0..=5, 12..=31]);
check_iter_ranges(vec![12..=31]);
check_iter_ranges(vec![71..=84]);
check_iter_ranges(vec![273..=284]);
check_iter_ranges(vec![0..=511]);
// end of boundary
check_iter_ranges(vec![511..=511]);
check_iter_ranges(vec![500..=511]);
check_iter_ranges(vec![400..=511]);
check_iter_ranges(vec![0..=511]);
// continuation ranges
check_iter_ranges(vec![64..=127]);
check_iter_ranges(vec![64..=127, 129..=135]);
check_iter_ranges(vec![64..=135]);
check_iter_ranges(vec![71..=135]);
check_iter_ranges(vec![71..=435]);
}
#[test]
fn union() {
let a = BitPage::new_zeroes();
let b = BitPage::from_iter([32, 400]);
let c = BitPage::from_iter([32, 200]);
let d = BitPage::from_iter([32, 200, 400]);
assert_eq!(BitPage::union(&a, &b), b);
assert_eq!(BitPage::union(&b, &a), b);
assert_eq!(BitPage::union(&b, &c), d);
assert_eq!(BitPage::union(&c, &b), d);
}
#[test]
fn intersect() {
let a = BitPage::new_zeroes();
let b = BitPage::from_iter([32, 400]);
let c = BitPage::from_iter([32, 200]);
let d = BitPage::from_iter([32]);
assert_eq!(BitPage::intersect(&a, &b), a);
assert_eq!(BitPage::intersect(&b, &a), a);
assert_eq!(BitPage::intersect(&b, &c), d);
assert_eq!(BitPage::intersect(&c, &b), d);
}
#[test]
fn subtract() {
let a = BitPage::new_zeroes();
let b = BitPage::from_iter([32, 400]);
let c = BitPage::from_iter([32, 200]);
let d = BitPage::from_iter([400]);
let e = BitPage::from_iter([200]);
assert_eq!(BitPage::subtract(&a, &b), a);
assert_eq!(BitPage::subtract(&b, &a), b);
assert_eq!(BitPage::subtract(&b, &c), d);
assert_eq!(BitPage::subtract(&c, &b), e);
}
#[test]
#[allow(clippy::mutable_key_type)]
fn hash_and_eq() {
let mut page1 = BitPage::new_zeroes();
let mut page2 = BitPage::new_zeroes();
let mut page3 = BitPage::new_zeroes();
page1.insert(12);
page1.insert(300);
page2.insert(300);
page2.insert(12);
page2.len();
page3.insert(300);
page3.insert(12);
page3.insert(23);
assert_eq!(page1, page2);
assert_ne!(page1, page3);
assert_ne!(page2, page3);
let set = HashSet::from([page1]);
assert!(set.contains(&page2));
assert!(!set.contains(&page3));
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,290 @@
//! Reads individual bits from a array of bytes.
use super::sparse_bit_set::BranchFactor;
pub(crate) struct InputBitStream<'a, const BF: u8> {
data: &'a [u8],
byte_index: usize,
sub_index: u32,
}
impl<const BF: u8> Iterator for InputBitStream<'_, BF> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
match BF {
2 | 4 => {
let mask = (1 << BF) - 1;
let byte = self.data.get(self.byte_index)?;
let val = (*byte as u32 & (mask << self.sub_index)) >> self.sub_index;
self.sub_index = (self.sub_index + BF as u32) % 8;
if self.sub_index == 0 {
self.byte_index += 1;
}
Some(val)
}
8 => {
let r = self.data.get(self.byte_index).map(|v| *v as u32)?;
self.byte_index += 1;
Some(r)
}
32 => {
let b1 = self.data.get(self.byte_index).map(|v| *v as u32)?;
let b2 = self.data.get(self.byte_index + 1).map(|v| *v as u32)?;
let b3 = self.data.get(self.byte_index + 2).map(|v| *v as u32)?;
let b4 = self.data.get(self.byte_index + 3).map(|v| *v as u32)?;
self.byte_index += 4;
Some(b1 | (b2 << 8) | (b3 << 16) | (b4 << 24))
}
_ => panic!("Unsupported branch factor."),
}
}
}
impl<'a, const BF: u8> InputBitStream<'a, BF> {
/// Decodes and returns the branch factor and height encoded in the header byte.
///
/// See: <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
/// Returns None if the stream does not have enough remaining bits.
#[allow(clippy::unusual_byte_groupings)] // Used to separate bit values into units used in the set encoding.
pub(crate) fn decode_header(data: &'a [u8]) -> Option<(BranchFactor, u8)> {
let first_byte = data.first()?;
let bf_bits = 0b0_00000_11 & first_byte;
let depth_bits = (0b0_11111_00 & first_byte) >> 2;
let branch_factor = match bf_bits {
0b00 => BranchFactor::Two,
0b01 => BranchFactor::Four,
0b10 => BranchFactor::Eight,
0b11 => BranchFactor::ThirtyTwo,
_ => panic!("Invalid branch factor encoding."),
};
Some((branch_factor, depth_bits))
}
pub(crate) fn from(data: &'a [u8]) -> Self {
Self {
data,
byte_index: 1,
sub_index: 0,
}
}
/// Skips the given number of nodes, returns true if this did not overrun the data buffer.
pub(crate) fn skip_nodes(&mut self, n: u32) -> bool {
match BF {
2 | 4 => {
let bit_index = self.sub_index + n * (BF as u32);
self.byte_index += (bit_index / 8) as usize;
self.sub_index = bit_index % 8;
}
8 => {
self.byte_index += n as usize;
}
32 => {
self.byte_index += 4 * (n as usize);
}
_ => panic!("Unsupported branch factor."),
};
self.bytes_consumed() <= self.data.len()
}
/// Returns the number of bytes consumed so far (including partially consumed).
pub(crate) fn bytes_consumed(&self) -> usize {
self.byte_index + if self.sub_index > 0 { 1 } else { 0 }
}
}
#[cfg(test)]
#[allow(clippy::unusual_byte_groupings)]
mod test {
use super::*;
#[test]
fn read_header() {
assert_eq!(
Some((BranchFactor::Two, 25u8)),
InputBitStream::<2>::decode_header(&[0b1_11001_00u8])
);
assert_eq!(
Some((BranchFactor::Four, 0u8)),
InputBitStream::<2>::decode_header(&[0b1_00000_01u8])
);
assert_eq!(
Some((BranchFactor::Eight, 31u8)),
InputBitStream::<2>::decode_header(&[0b1_11111_10u8])
);
assert_eq!(
Some((BranchFactor::ThirtyTwo, 9u8)),
InputBitStream::<2>::decode_header(&[0b1_01001_11u8])
);
}
#[test]
fn read_2() {
let mut stream = InputBitStream::<2>::from(&[0b00000000, 0b11_10_01_00, 0b00_01_10_11]);
assert_eq!(stream.bytes_consumed(), 1); // Initially one byte consumed for the header.
assert_eq!(stream.next(), Some(0b00));
assert_eq!(stream.bytes_consumed(), 2);
assert_eq!(stream.next(), Some(0b01));
assert_eq!(stream.next(), Some(0b10));
assert_eq!(stream.next(), Some(0b11));
assert_eq!(stream.bytes_consumed(), 2);
assert_eq!(stream.next(), Some(0b11));
assert_eq!(stream.bytes_consumed(), 3);
assert_eq!(stream.next(), Some(0b10));
assert_eq!(stream.next(), Some(0b01));
assert_eq!(stream.next(), Some(0b00));
assert_eq!(stream.bytes_consumed(), 3);
assert_eq!(stream.next(), None);
let mut stream = InputBitStream::<2>::from(&[]);
assert_eq!(stream.next(), None);
}
#[test]
fn skip_2() {
let mut stream = InputBitStream::<2>::from(&[0b00000000, 0b11_10_01_00, 0b00_01_10_11]);
assert_eq!(stream.bytes_consumed(), 1); // Initially one byte consumed for the header.
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(2));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 3);
assert!(stream.skip_nodes(3));
assert_eq!(stream.bytes_consumed(), 3);
assert!(!stream.skip_nodes(1));
}
#[test]
fn skip_2_unaligned() {
let mut stream = InputBitStream::<2>::from(&[0b00000000, 0b11_10_01_00, 0b00_01_10_11]);
assert_eq!(stream.bytes_consumed(), 1); // Initially one byte consumed for the header.
assert!(stream.skip_nodes(3));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(3));
assert_eq!(stream.bytes_consumed(), 3);
assert!(!stream.skip_nodes(3));
}
#[test]
fn read_4() {
let mut stream = InputBitStream::<4>::from(&[0b00000000, 0b1110_0100, 0b0001_1011]);
assert_eq!(stream.bytes_consumed(), 1);
assert_eq!(stream.next(), Some(0b0100));
assert_eq!(stream.bytes_consumed(), 2);
assert_eq!(stream.next(), Some(0b1110));
assert_eq!(stream.bytes_consumed(), 2);
assert_eq!(stream.next(), Some(0b1011));
assert_eq!(stream.bytes_consumed(), 3);
assert_eq!(stream.next(), Some(0b0001));
assert_eq!(stream.bytes_consumed(), 3);
assert_eq!(stream.next(), None);
let mut stream = InputBitStream::<4>::from(&[]);
assert_eq!(stream.next(), None);
}
#[test]
fn skip_4() {
let mut stream = InputBitStream::<4>::from(&[0b00000000, 0b1110_0100, 0b0001_1011]);
assert_eq!(stream.bytes_consumed(), 1); // Initially one byte consumed for the header.
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(2));
assert_eq!(stream.bytes_consumed(), 3);
assert!(!stream.skip_nodes(1));
}
#[test]
fn read_8() {
let mut stream = InputBitStream::<8>::from(&[0b00000000, 0b11100100, 0b00011011]);
assert_eq!(stream.bytes_consumed(), 1);
assert_eq!(stream.next(), Some(0b11100100));
assert_eq!(stream.bytes_consumed(), 2);
assert_eq!(stream.next(), Some(0b00011011));
assert_eq!(stream.bytes_consumed(), 3);
assert_eq!(stream.next(), None);
let mut stream = InputBitStream::<8>::from(&[]);
assert_eq!(stream.next(), None);
}
#[test]
fn skip_8() {
let mut stream = InputBitStream::<8>::from(&[0b00000000, 0b11100100, 0b00011011]);
assert_eq!(stream.bytes_consumed(), 1);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 2);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 3);
assert!(!stream.skip_nodes(1));
let mut stream = InputBitStream::<8>::from(&[0b00000000, 0b11100100, 0b00011011]);
assert_eq!(stream.bytes_consumed(), 1);
assert!(stream.skip_nodes(2));
assert_eq!(stream.bytes_consumed(), 3);
assert!(!stream.skip_nodes(1));
}
#[test]
fn read_32() {
let mut stream = InputBitStream::<32>::from(&[
0b00000000, 0b00000000, 0b11111111, 0b11100100, 0b00011011,
]);
assert_eq!(stream.bytes_consumed(), 1);
assert_eq!(stream.next(), Some(0b00011011_11100100_11111111_00000000));
assert_eq!(stream.bytes_consumed(), 5);
assert_eq!(stream.next(), None);
let mut stream = InputBitStream::<32>::from(&[
0b00000000, 0b00000000, 0b11111111, 0b11100100, 0b00011011, 0b00000001,
]);
assert_eq!(stream.next(), Some(0b00011011_11100100_11111111_00000000));
assert_eq!(stream.next(), None);
let mut stream = InputBitStream::<32>::from(&[]);
assert_eq!(stream.next(), None);
}
#[test]
fn skip_32() {
let mut stream = InputBitStream::<32>::from(&[
0b00000000, 0b00000000, 0b11111111, 0b11100100, 0b00011011,
]);
assert_eq!(stream.bytes_consumed(), 1);
assert!(stream.skip_nodes(1));
assert_eq!(stream.bytes_consumed(), 5);
assert!(!stream.skip_nodes(1));
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,172 @@
//! Writes individual bits to a vector of bytes.
use super::sparse_bit_set::BranchFactor;
pub(crate) struct OutputBitStream {
data: Vec<u8>,
sub_index: u32,
branch_factor: BranchFactor,
}
impl OutputBitStream {
pub(crate) const MAX_HEIGHT: u8 = 31;
pub(crate) fn new(branch_factor: BranchFactor, height: u8) -> OutputBitStream {
let mut out = OutputBitStream {
data: vec![],
sub_index: 0,
branch_factor,
};
if height > Self::MAX_HEIGHT {
panic!("Height value exceeds maximum for the branch factor.");
}
out.write_header(height);
out
}
pub fn into_bytes(self) -> Vec<u8> {
self.data
}
/// Writes a single node worth of bits to the stream.
///
/// `branch_factor` controls the node size.
pub fn write_node(&mut self, bits: u32) {
for byte_index in 0..self.branch_factor.bytes_per_node() {
if self.branch_factor.nodes_per_byte() == 1 || self.sub_index == 0 {
self.data.push(0);
}
let bits = (bits >> (byte_index * 8)) & self.branch_factor.byte_mask();
let bits = (bits << (self.sub_index * self.branch_factor.value())) as u8;
*self.data.last_mut().unwrap() |= bits;
if self.branch_factor.nodes_per_byte() > 1 {
self.sub_index = (self.sub_index + 1) % self.branch_factor.nodes_per_byte();
}
}
}
/// Writes the header byte for a sparse bit set.
///
/// See: <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
fn write_header(&mut self, height: u8) {
let byte = (height & 0b00011111) << 2;
let byte = byte | self.branch_factor.bit_id();
self.data.push(byte);
}
}
impl BranchFactor {
fn nodes_per_byte(&self) -> u32 {
match self {
BranchFactor::Two => 4,
BranchFactor::Four => 2,
BranchFactor::Eight => 1,
BranchFactor::ThirtyTwo => 1,
}
}
fn bytes_per_node(&self) -> u32 {
match self {
BranchFactor::Two => 1,
BranchFactor::Four => 1,
BranchFactor::Eight => 1,
BranchFactor::ThirtyTwo => 4,
}
}
fn bit_id(&self) -> u8 {
match self {
BranchFactor::Two => 0b00,
BranchFactor::Four => 0b01,
BranchFactor::Eight => 0b10,
BranchFactor::ThirtyTwo => 0b11,
}
}
}
#[cfg(test)]
#[allow(clippy::unusual_byte_groupings)]
mod test {
use super::*;
#[test]
fn init() {
let os = OutputBitStream::new(BranchFactor::Two, 13);
assert_eq!(os.into_bytes(), vec![0b0_01101_00]);
let os = OutputBitStream::new(BranchFactor::Four, 23);
assert_eq!(os.into_bytes(), vec![0b0_10111_01]);
let os = OutputBitStream::new(BranchFactor::Eight, 1);
assert_eq!(os.into_bytes(), vec![0b0_00001_10]);
let os = OutputBitStream::new(BranchFactor::ThirtyTwo, 31);
assert_eq!(os.into_bytes(), vec![0b0_11111_11]);
}
#[test]
fn bf2() {
let mut os = OutputBitStream::new(BranchFactor::Two, 13);
os.write_node(0b10);
os.write_node(0b00);
os.write_node(0b11);
os.write_node(0b01);
os.write_node(0b01);
os.write_node(0b11);
assert_eq!(
os.into_bytes(),
vec![0b0_01101_00, 0b01_11_00_10, 0b00_00_11_01,]
);
}
#[test]
fn bf4() {
let mut os = OutputBitStream::new(BranchFactor::Four, 23);
os.write_node(0b0010);
os.write_node(0b0111);
os.write_node(0b1101);
assert_eq!(
os.into_bytes(),
vec![0b0_10111_01, 0b0111_0010, 0b0000_1101,]
);
}
#[test]
fn bf8() {
let mut os = OutputBitStream::new(BranchFactor::Eight, 1);
os.write_node(0b01110010);
os.write_node(0b00001101);
assert_eq!(os.into_bytes(), vec![0b0_00001_10, 0b01110010, 0b00001101,]);
}
#[test]
fn bf32() {
let mut os = OutputBitStream::new(BranchFactor::ThirtyTwo, 31);
os.write_node(0b10000000_00000000_00001101_01110010);
assert_eq!(
os.into_bytes(),
vec![0b0_11111_11, 0b01110010, 0b00001101, 0b00000000, 0b10000000]
);
}
#[test]
fn truncating() {
let mut os = OutputBitStream::new(BranchFactor::Four, 23);
os.write_node(0b11110010);
assert_eq!(os.into_bytes(), vec![0b0_10111_01, 0b0000_0010]);
}
}
@@ -0,0 +1,920 @@
//! Provides serialization of [`IntSet`]'s to a highly compact bitset format as defined in the
//! IFT specification:
//!
//! <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
use std::collections::VecDeque;
use std::error::Error;
use std::fmt;
use super::bitset::BitSetBuilder;
use super::input_bit_stream::InputBitStream;
use super::output_bit_stream::OutputBitStream;
use super::BitSet;
use super::IntSet;
#[derive(Debug, PartialEq)]
pub struct DecodingError;
impl Error for DecodingError {}
impl fmt::Display for DecodingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"The input data stream was too short to be a valid sparse bit set."
)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum BranchFactor {
Two,
Four,
Eight,
ThirtyTwo,
}
impl IntSet<u32> {
/// Populate this set with the values obtained from decoding the provided sparse bit set bytes.
///
/// Sparse bit sets are a specialized, compact encoding of bit sets defined in the IFT specification:
/// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
pub fn from_sparse_bit_set(data: &[u8]) -> Result<IntSet<u32>, DecodingError> {
Self::from_sparse_bit_set_bounded(data, 0, u32::MAX).map(|(set, _)| set)
}
/// Populate this set with the values obtained from decoding the provided sparse bit set bytes.
///
/// During decoding bias will be added to each decoded set members value. The final set will not contain
/// any values larger than max_value: any encoded values larger than max_value after the bias is applied
/// are ignored.
///
/// Sparse bit sets are a specialized, compact encoding of bit sets defined in the IFT specification:
/// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
pub fn from_sparse_bit_set_bounded(
data: &[u8],
bias: u32,
max_value: u32,
) -> Result<(IntSet<u32>, &[u8]), DecodingError> {
// This is a direct port of the decoding algorithm from:
// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let Some((branch_factor, height)) = InputBitStream::<0>::decode_header(data) else {
return Err(DecodingError);
};
if height > branch_factor.max_height() {
// TODO(garretrieger): the spec says nothing about this depth limit, we need to update the spec
// to match.
return Err(DecodingError);
}
let result = match branch_factor {
BranchFactor::Two => {
Self::decode_sparse_bit_set_nodes::<2>(data, height, bias, max_value)
}
BranchFactor::Four => {
Self::decode_sparse_bit_set_nodes::<4>(data, height, bias, max_value)
}
BranchFactor::Eight => {
Self::decode_sparse_bit_set_nodes::<8>(data, height, bias, max_value)
}
BranchFactor::ThirtyTwo => {
Self::decode_sparse_bit_set_nodes::<32>(data, height, bias, max_value)
}
};
result.map(|(bitset, data)| (IntSet::<u32>::from_bitset(bitset), data))
}
fn decode_sparse_bit_set_nodes<const BF: u8>(
data: &[u8],
height: u8,
bias: u32,
max_value: u32,
) -> Result<(BitSet, &[u8]), DecodingError> {
let mut out = BitSet::empty();
if height == 0 {
// 1 byte was used for the header.
return Ok((out, &data[1..]));
}
let mut builder = BitSetBuilder::start(&mut out);
let mut bits = InputBitStream::<BF>::from(data);
// TODO(garretrieger): estimate initial capacity (maximum is a function of the number of nodes in the bit stream).
let mut queue = VecDeque::<NextNode>::new();
queue.push_back(NextNode { start: 0, depth: 1 });
'outer: while let Some(next) = queue.pop_front() {
let mut bits = bits.next().ok_or(DecodingError)?;
if bits == 0 {
// all bits were zeroes which is a special command to completely fill in
// all integers covered by this node.
let exp = (height as u32) - next.depth + 1;
let node_size = (BF as u64).pow(exp);
let Some(start) = u32::try_from(next.start)
.ok()
.and_then(|start| start.checked_add(bias))
.filter(|start| *start <= max_value)
else {
// start is outside the valid range of the set, so skip this range.
continue;
};
let end = u32::try_from(next.start + node_size - 1)
.unwrap_or(u32::MAX)
.saturating_add(bias)
.min(max_value);
// TODO(garretrieger): implement special insert_range on the builder as well.
builder.set.insert_range(start..=end);
continue;
}
let height = height as u32;
let exp = height - next.depth;
let next_node_size = (BF as u64).pow(exp);
loop {
let bit_index = bits.trailing_zeros();
if bit_index == 32 {
break;
}
// TODO(garretrieger): possible optimization by having two versions of this loop
// as next.depth == height has the same value for each of the outer iterations.
if next.depth == height {
// TODO(garretrieger): this has a few branches, is it faster to do all the math in u64
// then check only once for > max_value? Will need to check with a benchmark.
let Some(start) = u32::try_from(next.start)
.ok()
.and_then(|start| start.checked_add(bit_index))
.and_then(|start| start.checked_add(bias))
.filter(|start| *start <= max_value)
else {
// At the lowest depth values are encountered in order, so if this is out of range so will be
// all future values. We can break early.
break 'outer;
};
// TODO(garretrieger): further optimize by inserting entire nodes at once (as a bit field).
builder.insert(start);
} else {
let start_delta = bit_index as u64 * next_node_size;
queue.push_back(NextNode {
start: next.start + start_delta,
depth: next.depth + 1,
});
}
bits &= !(1 << bit_index); // clear the bit that was just read.
}
}
builder.finish();
// If the max value was reached the loop above may have terminated early leaving some unprocessed nodes
// in the queue. The loop can only break once we are at the lowest depth which means that each remaining queue node
// will consume only one node from the bit stream. Advance the bit stream by the remaining number of nodes to
// correctly count the number of bytes consumed.
if !bits.skip_nodes(queue.len() as u32) {
// We ran out of bits to consume before decoding would have been finished.
return Err(DecodingError);
}
Ok((out, &data[bits.bytes_consumed()..]))
}
/// Encode this set as a sparse bit set byte encoding.
///
/// Sparse bit sets are a specialized, compact encoding of bit sets defined in the IFT specification:
/// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
pub fn to_sparse_bit_set(&self) -> Vec<u8> {
// TODO(garretrieger): use the heuristic approach from the incxfer
// implementation to guess the optimal size. Building the set 4 times
// is costly.
let mut candidates: Vec<Vec<u8>> = vec![];
let Some(max_value) = self.last() else {
return OutputBitStream::new(BranchFactor::Two, 0).into_bytes();
};
if BranchFactor::Two.tree_height_for(max_value) <= BranchFactor::Two.max_height() {
candidates.push(to_sparse_bit_set_with_bf::<2>(self));
}
if BranchFactor::Four.tree_height_for(max_value) <= BranchFactor::Four.max_height() {
candidates.push(to_sparse_bit_set_with_bf::<4>(self));
}
if BranchFactor::Eight.tree_height_for(max_value) <= BranchFactor::Eight.max_height() {
candidates.push(to_sparse_bit_set_with_bf::<8>(self));
}
if BranchFactor::ThirtyTwo.tree_height_for(max_value)
<= BranchFactor::ThirtyTwo.max_height()
{
candidates.push(to_sparse_bit_set_with_bf::<32>(self));
}
candidates.into_iter().min_by_key(|f| f.len()).unwrap()
}
}
/// Encode this set as a sparse bit set byte encoding with a specified branch factor.
///
/// Branch factor can be 2, 4, 8 or 32. It's a compile time constant so that optimized decoding implementations
/// can be generated by the compiler.
///
/// Sparse bit sets are a specialized, compact encoding of bit sets defined in the IFT specification:
/// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
pub fn to_sparse_bit_set_with_bf<const BF: u8>(set: &IntSet<u32>) -> Vec<u8> {
let branch_factor = BranchFactor::from_val(BF);
let Some(max_value) = set.last() else {
return OutputBitStream::new(branch_factor, 0).into_bytes();
};
let mut height = branch_factor.tree_height_for(max_value);
if height > branch_factor.max_height() {
if BF == 2 {
// Branch factor 2 cannot encode all possible u32 values, so upgrade to a BF4 set in that case.
return to_sparse_bit_set_with_bf::<4>(set);
}
// This shouldn't be reachable for any possible u32 values.
panic!("Height value exceeds the maximum for this branch factor.");
}
let mut os = OutputBitStream::new(branch_factor, height);
let mut nodes: Vec<Node> = vec![];
// We build the nodes that will comprise the bit stream in reverse order
// from the last value in the last layer up to the first layer. Then
// when generating the final stream the order is reversed.
// The reverse order construction is needed since nodes at the lower layer
// affect the values in the parent layers.
let mut indices = set.clone();
let mut filled_indices = IntSet::<u32>::all();
while height > 0 {
(indices, filled_indices) =
create_layer(branch_factor, indices, filled_indices, &mut nodes);
height -= 1;
}
for node in nodes.iter().rev() {
match node.node_type {
NodeType::Standard => os.write_node(node.bits),
NodeType::Filled => os.write_node(0),
NodeType::Skip => {}
};
}
os.into_bytes()
}
struct CreateLayerState<'a> {
// This is the set of indices which are to be set in the layer above this one
upper_indices: IntSet<u32>,
// Similarly, this is the set of indices in the layer above this one which are fully filled.
upper_filled_indices: IntSet<u32>,
current_node: Option<Node>,
current_node_filled_bits: u32,
nodes: &'a mut Vec<Node>,
child_count: u64,
nodes_init_length: u64,
branch_factor: BranchFactor,
}
impl CreateLayerState<'_> {
fn commit_current_node(&mut self) {
let Some(mut node) = self.current_node.take() else {
// noop if there isn't a node to commit.
return;
};
self.upper_indices.insert(node.parent_index);
if self.current_node_filled_bits == self.branch_factor.u32_mask() {
// This node is filled and can thus be represented by a node that is '0'.
// It's index is recorded so that the parent node can also check if they are filled.
self.upper_filled_indices.insert(node.parent_index);
node.node_type = NodeType::Filled;
if self.nodes_init_length >= self.child_count {
// Since this node is filled, find all nodes which are children and set them to be skipped in
// the encoding.
let children_start_index = self.nodes_init_length.saturating_sub(self.child_count);
let children_end_index = self.nodes_init_length;
// TODO(garretrieger): this scans all nodes of the previous layer to find those which are children,
// but we can likely limit it to just the children of this node with some extra book keeping.
for child in
&mut self.nodes[children_start_index as usize..children_end_index as usize]
{
if child.parent_index >= node.parent_index * self.branch_factor.value()
&& child.parent_index < (node.parent_index + 1) * self.branch_factor.value()
{
child.node_type = NodeType::Skip;
}
}
}
}
self.nodes.push(node);
self.current_node_filled_bits = 0;
}
}
/// Compute the nodes for a layer of the sparse bit set.
///
/// Computes the nodes needed for the layer which contains the indices in
/// 'iter'. The new nodes are appended to 'nodes'. 'iter' must be sorted
/// in ascending order.
///
/// Returns the set of indices for the layer above.
fn create_layer(
branch_factor: BranchFactor,
values: IntSet<u32>,
filled_values: IntSet<u32>,
nodes: &mut Vec<Node>,
) -> (IntSet<u32>, IntSet<u32>) {
let mut state = CreateLayerState {
upper_indices: IntSet::<u32>::empty(),
upper_filled_indices: IntSet::<u32>::empty(),
current_node: None,
current_node_filled_bits: 0,
child_count: values.len(),
nodes_init_length: nodes.len() as u64,
nodes,
branch_factor,
};
// The nodes array is produced in reverse order and then reversed before final output.
for v in values.iter().rev() {
let parent_index = v / branch_factor.value();
let prev_parent_index = state
.current_node
.as_ref()
.map_or(parent_index, |node| node.parent_index);
if prev_parent_index != parent_index {
state.commit_current_node();
}
let current_node = state.current_node.get_or_insert(Node {
bits: 0,
parent_index,
node_type: NodeType::Standard,
});
let mask = 0b1 << (v % branch_factor.value());
current_node.bits |= mask;
if filled_values.contains(v) {
state.current_node_filled_bits |= mask;
}
}
state.commit_current_node();
(state.upper_indices, state.upper_filled_indices)
}
enum NodeType {
Standard,
Filled,
Skip,
}
struct Node {
bits: u32,
parent_index: u32,
node_type: NodeType,
}
impl BranchFactor {
pub(crate) fn value(&self) -> u32 {
match self {
BranchFactor::Two => 2,
BranchFactor::Four => 4,
BranchFactor::Eight => 8,
BranchFactor::ThirtyTwo => 32,
}
}
/// The maximum height that can be used for a given branch factor without the risk of encountering overflows
pub(crate) fn max_height(&self) -> u8 {
match self {
BranchFactor::Two => 31,
BranchFactor::Four => 16,
BranchFactor::Eight => 11,
BranchFactor::ThirtyTwo => 7,
}
}
fn tree_height_for(&self, max_value: u32) -> u8 {
// height H, can represent up to (BF^height) - 1
let mut height: u32 = 0;
let mut max_value = max_value;
loop {
height += 1;
max_value >>= self.node_size_log2();
if max_value == 0 {
break height as u8;
}
}
}
fn from_val(val: u8) -> BranchFactor {
match val {
2 => BranchFactor::Two,
4 => BranchFactor::Four,
8 => BranchFactor::Eight,
32 => BranchFactor::ThirtyTwo,
// This should never happen as this is only used internally.
_ => panic!("Invalid branch factor."),
}
}
fn node_size_log2(&self) -> u32 {
match self {
BranchFactor::Two => 1,
BranchFactor::Four => 2,
BranchFactor::Eight => 3,
BranchFactor::ThirtyTwo => 5,
}
}
pub(crate) fn byte_mask(&self) -> u32 {
match self {
BranchFactor::Two => 0b00000011,
BranchFactor::Four => 0b00001111,
BranchFactor::Eight => 0b11111111,
BranchFactor::ThirtyTwo => 0b11111111,
}
}
fn u32_mask(&self) -> u32 {
match self {
BranchFactor::Two => 0b00000000_00000000_00000000_00000011,
BranchFactor::Four => 0b00000000_00000000_00000000_00001111,
BranchFactor::Eight => 0b00000000_00000000_00000000_11111111,
BranchFactor::ThirtyTwo => 0b11111111_11111111_11111111_11111111,
}
}
}
struct NextNode {
start: u64,
depth: u32,
}
#[cfg(test)]
#[allow(clippy::unusual_byte_groupings)]
mod test {
use super::*;
#[test]
fn spec_example_2() {
// Test of decoding the example 2 given in the specification.
// See: <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let bytes = [
0b00001110, 0b00100001, 0b00010001, 0b00000001, 0b00000100, 0b00000010, 0b00001000,
];
let set = IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap();
let expected: IntSet<u32> = [2, 33, 323].iter().copied().collect();
assert_eq!(set, expected);
}
#[test]
fn spec_example_3() {
// Test of decoding the example 3 given in the specification.
// See: <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let bytes = [0b00000000];
let set = IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap();
let expected: IntSet<u32> = [].iter().copied().collect();
assert_eq!(set, expected);
}
#[test]
fn spec_example_4() {
// Test of decoding the example 4 given in the specification.
// See: <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let bytes = [0b00001101, 0b00000011, 0b00110001];
let set = IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap();
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(0..=17);
assert_eq!(set, expected);
}
#[test]
fn invalid() {
// Spec example 2 with one byte missing.
let bytes = [
0b00001110, 0b00100001, 0b00010001, 0b00000001, 0b00000100, 0b00000010,
];
assert!(IntSet::<u32>::from_sparse_bit_set(&bytes).is_err());
// Max height exceeded.
let bytes = [
0b0_01000_11, // BF 32, Depth 8
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L1
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L2
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L3
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L4
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L5
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L6
0b00000000,
0b00000000,
0b00000000,
0b00000001, // L7
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L8
];
assert!(IntSet::<u32>::from_sparse_bit_set(&bytes).is_err());
}
#[test]
fn invalid_biased_and_bounded() {
let bytes = [0b0_00011_01, 0b0000_0011, 0b1111_0011];
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, u32::MAX).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 20).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 19).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 18).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 15).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 14).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 1, 20).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 2, 20).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 3, 20).is_err());
assert!(IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 6, 20).is_err());
}
#[test]
fn larger_than_u32() {
// Set with values beyond u32
let bytes = [
0b0_00111_11, // BF 32, Depth 7
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L1
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L2
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L3
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L4
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L5
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L6
0b00000000,
0b00000000,
0b00000000,
0b00000001, // L7
];
assert_eq!(
IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap(),
IntSet::<u32>::empty()
);
// Set with filled node values beyond u32
let bytes = [
0b0_00111_11, // BF 32, Depth 7
0b00000000,
0b00000000,
0b00000000,
0b10000000, // L1
0b00000000,
0b00000000,
0b00000000,
0b00000000, // L2
];
assert_eq!(
IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap(),
IntSet::<u32>::empty()
);
}
#[test]
fn from_sparse_bit_set_bounded_with_remaining_data() {
let bytes = [0b00001101, 0b00000011, 0b00110001, 0b10101010];
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(0..=17);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 19).unwrap(),
(expected.clone(), &bytes[3..]),
);
}
#[test]
fn from_sparse_bit_set_biased_and_bounded() {
let bytes = [0b0_00011_01, 0b0000_0011, 0b1111_0011, 0b0000_0001];
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(0..=20);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 20).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(0..=19);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 19).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(1..=20);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 1, 20).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(1..=18);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 1, 18).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(0..=14);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 14).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert_range(6..=20);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 6, 20).unwrap(),
(expected.clone(), &bytes[4..])
);
let mut expected: IntSet<u32> = IntSet::<u32>::empty();
expected.insert(0);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 0, 0).unwrap(),
(expected.clone(), &bytes[4..])
);
assert_eq!(
IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 1, 0).unwrap(),
(IntSet::<u32>::empty().clone(), &bytes[4..])
);
let bytes = [0b00000000];
let set = IntSet::<u32>::from_sparse_bit_set_bounded(&bytes, 5, 0)
.unwrap()
.0;
assert_eq!(set, IntSet::<u32>::empty());
}
#[test]
fn test_tree_height_for() {
assert_eq!(BranchFactor::Two.tree_height_for(0), 1);
assert_eq!(BranchFactor::Two.tree_height_for(1), 1);
assert_eq!(BranchFactor::Two.tree_height_for(2), 2);
assert_eq!(BranchFactor::Two.tree_height_for(117), 7);
assert_eq!(BranchFactor::Four.tree_height_for(0), 1);
assert_eq!(BranchFactor::Four.tree_height_for(3), 1);
assert_eq!(BranchFactor::Four.tree_height_for(4), 2);
assert_eq!(BranchFactor::Four.tree_height_for(63), 3);
assert_eq!(BranchFactor::Four.tree_height_for(64), 4);
assert_eq!(BranchFactor::Eight.tree_height_for(0), 1);
assert_eq!(BranchFactor::Eight.tree_height_for(7), 1);
assert_eq!(BranchFactor::Eight.tree_height_for(8), 2);
assert_eq!(BranchFactor::Eight.tree_height_for(32767), 5);
assert_eq!(BranchFactor::Eight.tree_height_for(32768), 6);
assert_eq!(BranchFactor::ThirtyTwo.tree_height_for(0), 1);
assert_eq!(BranchFactor::ThirtyTwo.tree_height_for(31), 1);
assert_eq!(BranchFactor::ThirtyTwo.tree_height_for(32), 2);
assert_eq!(BranchFactor::ThirtyTwo.tree_height_for(1_048_575), 4);
assert_eq!(BranchFactor::ThirtyTwo.tree_height_for(1_048_576), 5);
}
#[test]
fn generate_spec_example_2() {
// Test of reproducing the encoding of example 2 given
// in the specification. See:
// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let actual_bytes = to_sparse_bit_set_with_bf::<8>(&[2, 33, 323].iter().copied().collect());
let expected_bytes = [
0b00001110, 0b00100001, 0b00010001, 0b00000001, 0b00000100, 0b00000010, 0b00001000,
];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn generate_spec_example_3() {
// Test of reproducing the encoding of example 3 given
// in the specification. See:
// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let actual_bytes = to_sparse_bit_set_with_bf::<2>(&IntSet::<u32>::empty());
let expected_bytes = [0b00000000];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn generate_spec_example_4() {
// Test of reproducing the encoding of example 3 given
// in the specification. See:
// <https://w3c.github.io/IFT/Overview.html#sparse-bit-set-decoding>
let actual_bytes = to_sparse_bit_set_with_bf::<4>(&(0..=17).collect());
let expected_bytes = [0b00001101, 0b0000_0011, 0b0011_0001];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_one_level() {
let actual_bytes = to_sparse_bit_set_with_bf::<8>(&[2, 6].iter().copied().collect());
let expected_bytes = [0b0_00001_10, 0b01000100];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_one_level_filled() {
let actual_bytes = to_sparse_bit_set_with_bf::<8>(&(0..=7).collect());
let expected_bytes = [0b0_00001_10, 0b00000000];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_two_level_filled() {
let actual_bytes = to_sparse_bit_set_with_bf::<8>(&(3..=21).collect());
let expected_bytes = [0b0_00010_10, 0b00000111, 0b11111000, 0b00000000, 0b00111111];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_two_level_not_filled() {
let actual_bytes = to_sparse_bit_set_with_bf::<4>(&[0, 4, 8, 12].iter().copied().collect());
let expected_bytes = [0b0_00010_01, 0b0001_1111, 0b0001_0001, 0b0000_0001];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_four_level_filled() {
let mut s = IntSet::<u32>::empty();
s.insert_range(64..=127); // Filled node on level 3
s.insert_range(512..=1023); // Filled node on level 2
s.insert(4000);
let actual_bytes = to_sparse_bit_set_with_bf::<8>(&s);
let expected_bytes = [
// Header
0b0_00100_10,
// L1
0b10000011,
// L2
0b00000010,
0b00000000,
0b01000000,
// L3,
0b00000000,
0b00010000,
// L4
0b00000001,
];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn encode_bf32() {
let actual_bytes = to_sparse_bit_set_with_bf::<32>(&[2, 31, 323].iter().copied().collect());
let expected_bytes = [
0b0_00010_11,
// node 0
0b00000001,
0b00000100,
0b00000000,
0b00000000,
// node 1
0b00000100,
0b00000000,
0b00000000,
0b10000000,
// node 2
0b00001000,
0b00000000,
0b00000000,
0b00000000,
];
assert_eq!(actual_bytes, expected_bytes);
}
#[test]
fn round_trip() {
let s1: IntSet<u32> = [11, 74, 9358].iter().copied().collect();
let mut s2: IntSet<u32> = s1.clone();
s2.insert_range(67..=412);
check_round_trip::<2>(&s1);
check_round_trip::<4>(&s1);
check_round_trip::<8>(&s1);
check_round_trip::<32>(&s1);
check_round_trip::<2>(&s2);
check_round_trip::<4>(&s2);
check_round_trip::<8>(&s2);
check_round_trip::<32>(&s2);
}
fn check_round_trip<const BF: u8>(s: &IntSet<u32>) {
let bytes = to_sparse_bit_set_with_bf::<BF>(s);
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes).unwrap();
assert_eq!(*s, s_prime);
}
#[test]
fn find_smallest_bf() {
let s: IntSet<u32> = [11, 74, 9358].iter().copied().collect();
let bytes = s.to_sparse_bit_set();
// BF4
assert_eq!(vec![0b0_00111_01], bytes[0..1]);
let s: IntSet<u32> = [
16, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
]
.iter()
.copied()
.collect();
let bytes = s.to_sparse_bit_set();
// BF32
assert_eq!(vec![0b0_00001_11], bytes[0..1]);
}
#[test]
fn encode_maxu32() {
let s: IntSet<u32> = [1, u32::MAX].iter().copied().collect();
let bytes = s.to_sparse_bit_set();
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes);
assert_eq!(s, s_prime.unwrap());
let s: IntSet<u32> = [1, u32::MAX].iter().copied().collect();
let bytes = to_sparse_bit_set_with_bf::<2>(&s);
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes);
assert_eq!(s, s_prime.unwrap());
let s: IntSet<u32> = [1, u32::MAX].iter().copied().collect();
let bytes = to_sparse_bit_set_with_bf::<4>(&s);
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes);
assert_eq!(s, s_prime.unwrap());
let s: IntSet<u32> = [1, u32::MAX].iter().copied().collect();
let bytes = to_sparse_bit_set_with_bf::<8>(&s);
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes);
assert_eq!(s, s_prime.unwrap());
let s: IntSet<u32> = [1, u32::MAX].iter().copied().collect();
let bytes = to_sparse_bit_set_with_bf::<32>(&s);
let s_prime = IntSet::<u32>::from_sparse_bit_set(&bytes);
assert_eq!(s, s_prime.unwrap());
}
}
+400
View File
@@ -0,0 +1,400 @@
//! Stores a disjoint collection of ranges over numeric types.
//!
//! Overlapping and adjacent ranges are automatically merged together.
use core::{
cmp::{max, min},
fmt::{Debug, Formatter},
iter::Peekable,
ops::RangeInclusive,
};
use std::collections::BTreeMap;
use types::Fixed;
#[derive(Default, Clone, PartialEq, Eq)]
/// A set of disjoint ranges over numeric types.
///
/// Overlapping and adjacent ranges are automatically merged together.
pub struct RangeSet<T> {
// an entry in the map ranges[a] = b implies there is an range [a, b] (inclusive) in this set.
ranges: BTreeMap<T, T>,
}
/// Allows a two values to be tested for adjacency.
pub trait OrdAdjacency {
/// Returns true if self is adjacent on either side of rhs.
fn are_adjacent(self, rhs: Self) -> bool;
}
impl<T> RangeSet<T>
where
T: Ord + Copy + OrdAdjacency,
{
// Returns true if there are no members in this set currently.
pub fn is_empty(&self) -> bool {
self.ranges.is_empty()
}
/// Insert a range into this set, automatically merging with existing ranges as needed.
pub fn insert(&mut self, range: RangeInclusive<T>) {
if range.end() < range.start() {
// ignore or malformed ranges.
return;
}
let mut start = *range.start();
let mut end = *range.end();
// There may be up to one intersecting range prior to this new range, check for it and merge if needed.
if let Some((prev_start, prev_end)) = self.prev_range(start) {
if range_is_subset(start, end, prev_start, prev_end) {
return;
}
if ranges_overlap_or_adjacent(start, end, prev_start, prev_end) {
start = min(start, prev_start);
end = max(end, prev_end);
self.ranges.remove(&prev_start);
}
};
// There may be one or more ranges proceeding this new range that intersect, find and merge them as needed.
loop {
let Some((next_start, next_end)) = self.next_range(start) else {
// No existing ranges which might overlap, can now insert the current range
self.ranges.insert(start, end);
return;
};
if range_is_subset(start, end, next_start, next_end) {
return;
}
if ranges_overlap_or_adjacent(start, end, next_start, next_end) {
start = min(start, next_start);
end = max(end, next_end);
self.ranges.remove(&next_start);
} else {
self.ranges.insert(start, end);
return;
}
}
}
/// Returns an iterator over the contained ranges.
pub fn iter(&'_ self) -> impl Iterator<Item = RangeInclusive<T>> + '_ {
self.ranges.iter().map(|(a, b)| *a..=*b)
}
/// Returns an iterator over the intersection of this and other.
pub fn intersection<'a>(
&'a self,
other: &'a Self,
) -> impl Iterator<Item = RangeInclusive<T>> + 'a {
IntersectionIter {
it_a: self.iter().peekable(),
it_b: other.iter().peekable(),
}
}
/// Finds a range in this set with a start greater than or equal to the provided start value.
fn next_range(&self, start: T) -> Option<(T, T)> {
let (next_start, next_end) = self.ranges.range(start..).next()?;
Some((*next_start, *next_end))
}
/// Finds a range in this set with a start less than the provided start value.
fn prev_range(&self, start: T) -> Option<(T, T)> {
let (next_start, next_end) = self.ranges.range(..start).next_back()?;
Some((*next_start, *next_end))
}
}
impl<T> Extend<RangeInclusive<T>> for RangeSet<T>
where
T: Copy + Ord + OrdAdjacency,
{
fn extend<I: IntoIterator<Item = RangeInclusive<T>>>(&mut self, iter: I) {
iter.into_iter().for_each(|r| self.insert(r));
}
}
impl<T> FromIterator<RangeInclusive<T>> for RangeSet<T>
where
T: Default + Copy + Ord + OrdAdjacency,
{
fn from_iter<I: IntoIterator<Item = RangeInclusive<T>>>(iter: I) -> Self {
let mut result: Self = Default::default();
result.extend(iter);
result
}
}
impl<T> Debug for RangeSet<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "RangeSet {{")?;
for (start, end) in self.ranges.iter() {
write!(f, "[{:?}, {:?}], ", start, end)?;
}
write!(f, "}}")
}
}
struct IntersectionIter<A, B, T>
where
A: Iterator<Item = RangeInclusive<T>>,
B: Iterator<Item = RangeInclusive<T>>,
{
it_a: Peekable<A>,
it_b: Peekable<B>,
}
impl<A, B, T> Iterator for IntersectionIter<A, B, T>
where
A: Iterator<Item = RangeInclusive<T>>,
B: Iterator<Item = RangeInclusive<T>>,
T: Ord + Copy,
{
type Item = RangeInclusive<T>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let (Some(a), Some(b)) = (self.it_a.peek(), self.it_b.peek()) else {
return None;
};
let a = a.clone();
let b = b.clone();
match range_intersection(&a, &b) {
Some(intersection) => {
self.step_iterators(&a, &b);
return Some(intersection);
}
None => self.step_iterators(&a, &b),
}
}
}
}
impl<A, B, T> IntersectionIter<A, B, T>
where
A: Iterator<Item = RangeInclusive<T>>,
B: Iterator<Item = RangeInclusive<T>>,
T: Ord,
{
fn step_iterators(&mut self, a: &RangeInclusive<T>, b: &RangeInclusive<T>) {
if a.end() <= b.end() {
self.it_a.next();
}
if a.end() >= b.end() {
self.it_b.next();
}
}
}
impl OrdAdjacency for u32 {
fn are_adjacent(self, rhs: u32) -> bool {
matches!(self.checked_add(1).map(|r| r == rhs), Some(true))
|| matches!(rhs.checked_add(1).map(|r| r == self), Some(true))
}
}
impl OrdAdjacency for u16 {
fn are_adjacent(self, rhs: u16) -> bool {
matches!(self.checked_add(1).map(|r| r == rhs), Some(true))
|| matches!(rhs.checked_add(1).map(|r| r == self), Some(true))
}
}
impl OrdAdjacency for Fixed {
fn are_adjacent(self, rhs: Fixed) -> bool {
matches!(
self.checked_add(Fixed::EPSILON).map(|r| r == rhs),
Some(true)
) || matches!(
rhs.checked_add(Fixed::EPSILON).map(|r| r == self),
Some(true)
)
}
}
/// If a and b intersect return a range representing the intersection.
fn range_intersection<T: Ord + Copy>(
a: &RangeInclusive<T>,
b: &RangeInclusive<T>,
) -> Option<RangeInclusive<T>> {
if a.start() <= b.end() && b.start() <= a.end() {
Some(*max(a.start(), b.start())..=*min(a.end(), b.end()))
} else {
None
}
}
/// Returns true if the ranges [a_start, a_end] and [b_start, b_end] overlap or are adjacent to each other.
///
/// All bounds are inclusive.
fn ranges_overlap_or_adjacent<T>(a_start: T, a_end: T, b_start: T, b_end: T) -> bool
where
T: Ord + OrdAdjacency,
{
(a_start <= b_end && b_start <= a_end)
|| (a_end.are_adjacent(b_start))
|| (b_end.are_adjacent(a_start))
}
/// Returns true if the range [a_start, a_end] is a subset of [b_start, b_end].
///
/// All bounds are inclusive.
fn range_is_subset<T>(a_start: T, a_end: T, b_start: T, b_end: T) -> bool
where
T: Ord,
{
a_start >= b_start && a_end <= b_end
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[allow(clippy::reversed_empty_ranges)]
fn insert_invalid() {
let mut map: RangeSet<u32> = Default::default();
map.insert(12..=11);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![],);
}
#[test]
fn insert_non_overlapping() {
let mut map: RangeSet<u32> = Default::default();
map.insert(11..=11);
map.insert(2..=3);
map.insert(6..=9);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=3, 6..=9, 11..=11],);
}
#[test]
fn insert_subset_before() {
let mut map: RangeSet<u32> = Default::default();
map.insert(2..=8);
map.insert(3..=7);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=8],);
}
#[test]
fn insert_subset_after() {
let mut map: RangeSet<u32> = Default::default();
map.insert(2..=8);
map.insert(2..=7);
map.insert(2..=8);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=8],);
}
#[test]
fn insert_overlapping_before() {
let mut map: RangeSet<u32> = Default::default();
map.insert(2..=8);
map.insert(7..=11);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=11],);
}
#[test]
fn insert_overlapping_after() {
let mut map: RangeSet<u32> = Default::default();
map.insert(10..=14);
map.insert(7..=11);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![7..=14],);
let mut map: RangeSet<u32> = Default::default();
map.insert(10..=14);
map.insert(10..=17);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);
}
#[test]
fn insert_overlapping_multiple_after() {
let mut map: RangeSet<u32> = Default::default();
map.insert(10..=14);
map.insert(16..=17);
map.insert(7..=16);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![7..=17],);
let mut map: RangeSet<u32> = Default::default();
map.insert(10..=14);
map.insert(16..=17);
map.insert(10..=16);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);
let mut map: RangeSet<u32> = Default::default();
map.insert(10..=14);
map.insert(16..=17);
map.insert(10..=17);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![10..=17],);
}
#[test]
fn insert_overlapping_before_and_after() {
let mut map: RangeSet<u32> = Default::default();
map.insert(6..=8);
map.insert(10..=14);
map.insert(16..=20);
map.insert(7..=19);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=20],);
}
#[test]
fn insert_joins_adjacent() {
let mut map: RangeSet<u32> = Default::default();
map.insert(6..=8);
map.insert(9..=10);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);
let mut map: RangeSet<u32> = Default::default();
map.insert(9..=10);
map.insert(6..=8);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);
let mut map: RangeSet<u32> = Default::default();
map.insert(6..=8);
map.insert(10..=10);
map.insert(9..=9);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![6..=10],);
}
#[test]
fn from_iter_and_extend() {
let mut map: RangeSet<u32> = [2..=5, 13..=64, 7..=9].into_iter().collect();
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=5, 7..=9, 13..=64],);
map.extend([6..=17, 100..=101]);
assert_eq!(map.iter().collect::<Vec<_>>(), vec![2..=64, 100..=101],);
}
#[test]
fn intersection() {
let a: RangeSet<u32> = [2..=5, 7..=9, 13..=64].into_iter().collect();
let b: RangeSet<u32> = [1..=3, 5..=8, 13..=64, 67..=69].into_iter().collect();
let expected = vec![2..=3, 5..=5, 7..=8, 13..=64];
assert_eq!(a.intersection(&b).collect::<Vec<_>>(), expected);
assert_eq!(b.intersection(&a).collect::<Vec<_>>(), expected);
}
}
+325
View File
@@ -0,0 +1,325 @@
//! raw font bytes
#![deny(clippy::arithmetic_side_effects)]
use std::ops::{Range, RangeBounds};
use bytemuck::AnyBitPattern;
use types::{BigEndian, FixedSize, Scalar};
use crate::array::ComputedArray;
use crate::read::{ComputeSize, FontReadWithArgs, ReadError};
use crate::table_ref::TableRef;
use crate::FontRead;
/// A reference to raw binary font data.
///
/// This is a wrapper around a byte slice, that provides convenience methods
/// for parsing and validating that data.
#[derive(Debug, Default, Clone, Copy)]
pub struct FontData<'a> {
bytes: &'a [u8],
}
/// A cursor for validating bytes during parsing.
///
/// This type improves the ergonomics of validation blah blah
///
/// # Note
///
/// call `finish` when you're done to ensure you're in bounds
#[derive(Debug, Default, Clone, Copy)]
pub struct Cursor<'a> {
pos: usize,
data: FontData<'a>,
}
impl<'a> FontData<'a> {
/// Empty data, useful for some tests and examples
pub const EMPTY: FontData<'static> = FontData { bytes: &[] };
/// Create a new `FontData` with these bytes.
///
/// You generally don't need to do this? It is handled for you when loading
/// data from disk, but may be useful in tests.
pub const fn new(bytes: &'a [u8]) -> Self {
FontData { bytes }
}
/// The length of the data, in bytes
pub fn len(&self) -> usize {
self.bytes.len()
}
/// `true` if the data has a length of zero bytes.
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Returns self[pos..]
pub fn split_off(&self, pos: usize) -> Option<FontData<'a>> {
self.bytes.get(pos..).map(|bytes| FontData { bytes })
}
/// returns self[..pos], and updates self to = self[pos..];
pub fn take_up_to(&mut self, pos: usize) -> Option<FontData<'a>> {
if pos > self.len() {
return None;
}
let (head, tail) = self.bytes.split_at(pos);
self.bytes = tail;
Some(FontData { bytes: head })
}
pub fn slice(&self, range: impl RangeBounds<usize>) -> Option<FontData<'a>> {
let bounds = (range.start_bound().cloned(), range.end_bound().cloned());
self.bytes.get(bounds).map(|bytes| FontData { bytes })
}
/// Read a scalar at the provided location in the data.
pub fn read_at<T: Scalar>(&self, offset: usize) -> Result<T, ReadError> {
let end = offset
.checked_add(T::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
self.bytes
.get(offset..end)
.and_then(T::read)
.ok_or(ReadError::OutOfBounds)
}
/// Read a big-endian value at the provided location in the data.
pub fn read_be_at<T: Scalar>(&self, offset: usize) -> Result<BigEndian<T>, ReadError> {
let end = offset
.checked_add(T::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
self.bytes
.get(offset..end)
.and_then(BigEndian::from_slice)
.ok_or(ReadError::OutOfBounds)
}
pub fn read_with_args<T>(&self, range: Range<usize>, args: &T::Args) -> Result<T, ReadError>
where
T: FontReadWithArgs<'a>,
{
self.slice(range)
.ok_or(ReadError::OutOfBounds)
.and_then(|data| T::read_with_args(data, args))
}
fn check_in_bounds(&self, offset: usize) -> Result<(), ReadError> {
self.bytes
.get(..offset)
.ok_or(ReadError::OutOfBounds)
.map(|_| ())
}
/// Interpret the bytes at the provided offset as a reference to `T`.
///
/// Returns an error if the slice `offset..` is shorter than `T::RAW_BYTE_LEN`.
///
/// This is a wrapper around [`read_ref_unchecked`][], which panics if
/// the type does not uphold the required invariants.
///
/// # Panics
///
/// This function will panic if `T` is zero-sized, has an alignment
/// other than one, or has any internal padding.
///
/// [`read_ref_unchecked`]: [Self::read_ref_unchecked]
pub fn read_ref_at<T: AnyBitPattern + FixedSize>(
&self,
offset: usize,
) -> Result<&'a T, ReadError> {
let end = offset
.checked_add(T::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
self.bytes
.get(offset..end)
.ok_or(ReadError::OutOfBounds)
.map(bytemuck::from_bytes)
}
/// Interpret the bytes at the provided offset as a slice of `T`.
///
/// Returns an error if `range` is out of bounds for the underlying data,
/// or if the length of the range is not a multiple of `T::RAW_BYTE_LEN`.
///
/// This is a wrapper around [`read_array_unchecked`][], which panics if
/// the type does not uphold the required invariants.
///
/// # Panics
///
/// This function will panic if `T` is zero-sized, has an alignment
/// other than one, or has any internal padding.
///
/// [`read_array_unchecked`]: [Self::read_array_unchecked]
pub fn read_array<T: AnyBitPattern + FixedSize>(
&self,
range: Range<usize>,
) -> Result<&'a [T], ReadError> {
let bytes = self
.bytes
.get(range.clone())
.ok_or(ReadError::OutOfBounds)?;
if bytes
.len()
.checked_rem(std::mem::size_of::<T>())
.unwrap_or(1) // definitely != 0
!= 0
{
return Err(ReadError::InvalidArrayLen);
};
Ok(bytemuck::cast_slice(bytes))
}
pub(crate) fn cursor(&self) -> Cursor<'a> {
Cursor {
pos: 0,
data: *self,
}
}
/// Return the data as a byte slice
pub fn as_bytes(&self) -> &'a [u8] {
self.bytes
}
}
impl<'a> Cursor<'a> {
pub(crate) fn advance<T: Scalar>(&mut self) {
self.pos = self.pos.saturating_add(T::RAW_BYTE_LEN);
}
pub(crate) fn advance_by(&mut self, n_bytes: usize) {
self.pos = self.pos.saturating_add(n_bytes);
}
/// Read a variable length u32 and advance the cursor
pub(crate) fn read_u32_var(&mut self) -> Result<u32, ReadError> {
let mut next = || self.read::<u8>().map(|v| v as u32);
let b0 = next()?;
// TODO this feels possible to simplify, e.g. compute length, loop taking one and shifting and or'ing
#[allow(clippy::arithmetic_side_effects)] // these are all checked
let result = match b0 {
_ if b0 < 0x80 => b0,
_ if b0 < 0xC0 => ((b0 - 0x80) << 8) | next()?,
_ if b0 < 0xE0 => ((b0 - 0xC0) << 16) | (next()? << 8) | next()?,
_ if b0 < 0xF0 => ((b0 - 0xE0) << 24) | (next()? << 16) | (next()? << 8) | next()?,
_ => {
// TODO: << 32 doesn't make sense. (b0 - 0xF0) << 32
(next()? << 24) | (next()? << 16) | (next()? << 8) | next()?
}
};
Ok(result)
}
/// Read a scalar and advance the cursor.
pub(crate) fn read<T: Scalar>(&mut self) -> Result<T, ReadError> {
let temp = self.data.read_at(self.pos);
self.advance::<T>();
temp
}
/// Read a big-endian value and advance the cursor.
pub(crate) fn read_be<T: Scalar>(&mut self) -> Result<BigEndian<T>, ReadError> {
let temp = self.data.read_be_at(self.pos);
self.advance::<T>();
temp
}
pub(crate) fn read_with_args<T>(&mut self, args: &T::Args) -> Result<T, ReadError>
where
T: FontReadWithArgs<'a> + ComputeSize,
{
let len = T::compute_size(args)?;
let range_end = self.pos.checked_add(len).ok_or(ReadError::OutOfBounds)?;
let temp = self.data.read_with_args(self.pos..range_end, args);
self.advance_by(len);
temp
}
// only used in records that contain arrays :/
pub(crate) fn read_computed_array<T>(
&mut self,
len: usize,
args: &T::Args,
) -> Result<ComputedArray<'a, T>, ReadError>
where
T: FontReadWithArgs<'a> + ComputeSize,
{
let len = len
.checked_mul(T::compute_size(args)?)
.ok_or(ReadError::OutOfBounds)?;
let range_end = self.pos.checked_add(len).ok_or(ReadError::OutOfBounds)?;
let temp = self.data.read_with_args(self.pos..range_end, args);
self.advance_by(len);
temp
}
pub(crate) fn read_array<T: AnyBitPattern + FixedSize>(
&mut self,
n_elem: usize,
) -> Result<&'a [T], ReadError> {
let len = n_elem
.checked_mul(T::RAW_BYTE_LEN)
.ok_or(ReadError::OutOfBounds)?;
let end = self.pos.checked_add(len).ok_or(ReadError::OutOfBounds)?;
let temp = self.data.read_array(self.pos..end);
self.advance_by(len);
temp
}
/// return the current position, or an error if we are out of bounds
pub(crate) fn position(&self) -> Result<usize, ReadError> {
self.data.check_in_bounds(self.pos).map(|_| self.pos)
}
// used when handling fields with an implicit length, which must be at the
// end of a table.
pub(crate) fn remaining_bytes(&self) -> usize {
self.data.len().saturating_sub(self.pos)
}
pub(crate) fn remaining(self) -> Option<FontData<'a>> {
self.data.split_off(self.pos)
}
pub fn is_empty(&self) -> bool {
self.pos >= self.data.len()
}
pub(crate) fn finish<T>(self, shape: T) -> Result<TableRef<'a, T>, ReadError> {
let data = self.data;
data.check_in_bounds(self.pos)?;
Ok(TableRef { data, shape })
}
}
// useful so we can have offsets that are just to data
impl<'a> FontRead<'a> for FontData<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
Ok(data)
}
}
impl AsRef<[u8]> for FontData<'_> {
fn as_ref(&self) -> &[u8] {
self.bytes
}
}
impl<'a> From<&'a [u8]> for FontData<'a> {
fn from(src: &'a [u8]) -> FontData<'a> {
FontData::new(src)
}
}
//kind of ugly, but makes FontData work with FontBuilder. If FontBuilder stops using
//Cow in its API, we can probably get rid of this?
#[cfg(feature = "std")]
impl<'a> From<FontData<'a>> for std::borrow::Cow<'a, [u8]> {
fn from(src: FontData<'a>) -> Self {
src.bytes.into()
}
}
+373
View File
@@ -0,0 +1,373 @@
//! Reading OpenType tables
//!
//! This crate provides memory safe zero-allocation parsing of font files.
//! It is unopinionated, and attempts to provide raw access to the underlying
//! font data as it is described in the [OpenType specification][spec].
//!
//! This crate is intended for use by other parts of a font stack, such as a
//! shaping engine or a glyph rasterizer.
//!
//! In addition to raw data access, this crate may also provide reference
//! implementations of algorithms for interpreting that data, where such an
//! implementation is required for the data to be useful. For instance, we
//! provide functions for [mapping codepoints to glyph identifiers][cmap-impl]
//! using the `cmap` table, or for [decoding entries in the `name` table][NameString].
//!
//! For higher level/more ergonomic access to font data, you may want to look
//! into using [`skrifa`] instead.
//!
//! ## Structure & codegen
//!
//! The root [`tables`] module contains a submodule for each supported
//! [table][table-directory], and that submodule contains items for each table,
//! record, flagset or enum described in the relevant portion of the spec.
//!
//! The majority of the code in the tables module is auto-generated. For more
//! information on our use of codegen, see the [codegen tour].
//!
//! # Related projects
//!
//! - [`write-fonts`] is a companion crate for creating/modifying font files
//! - [`skrifa`] provides access to glyph outlines and metadata (in the same vein
//! as [freetype])
//!
//! # Example
//!
//! ```no_run
//! # let path_to_my_font_file = std::path::Path::new("");
//! use read_fonts::{FontRef, TableProvider};
//! let font_bytes = std::fs::read(path_to_my_font_file).unwrap();
//! // Single fonts only. for font collections (.ttc) use FontRef::from_index
//! let font = FontRef::new(&font_bytes).expect("failed to read font data");
//! let head = font.head().expect("missing 'head' table");
//! let maxp = font.maxp().expect("missing 'maxp' table");
//!
//! println!("font version {} containing {} glyphs", head.font_revision(), maxp.num_glyphs());
//! ```
//!
//!
//! [spec]: https://learn.microsoft.com/en-us/typography/opentype/spec/
//! [codegen-tour]: https://github.com/googlefonts/fontations/blob/main/docs/codegen-tour.md
//! [cmap-impl]: tables::cmap::Cmap::map_codepoint
//! [`write-fonts`]: https://docs.rs/write-fonts/
//! [`skrifa`]: https://docs.rs/skrifa/
//! [freetype]: http://freetype.org
//! [codegen tour]: https://github.com/googlefonts/fontations/blob/main/docs/codegen-tour.md
//! [NameString]: tables::name::NameString
//! [table-directory]: https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![forbid(unsafe_code)]
#![deny(rustdoc::broken_intra_doc_links)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(any(feature = "std", test))]
#[macro_use]
extern crate std;
#[cfg(all(not(feature = "std"), not(test)))]
#[macro_use]
extern crate core as std;
pub mod array;
#[cfg(feature = "std")]
pub mod collections;
mod font_data;
mod offset;
mod offset_array;
mod read;
mod table_provider;
mod table_ref;
pub mod tables;
#[cfg(feature = "experimental_traverse")]
pub mod traversal;
#[cfg(any(test, feature = "codegen_test"))]
pub mod codegen_test;
pub use font_data::FontData;
pub use offset::{Offset, ResolveNullableOffset, ResolveOffset};
pub use offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
pub use read::{ComputeSize, FontRead, FontReadWithArgs, ReadArgs, ReadError, VarSize};
pub use table_provider::{TableProvider, TopLevelTable};
pub use table_ref::{MinByteRange, TableRef};
/// Public re-export of the font-types crate.
pub extern crate font_types as types;
/// All the types that may be referenced in auto-generated code.
#[doc(hidden)]
pub(crate) mod codegen_prelude {
pub use crate::array::{ComputedArray, VarLenArray};
pub use crate::font_data::{Cursor, FontData};
pub use crate::offset::{Offset, ResolveNullableOffset, ResolveOffset};
pub use crate::offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
//pub(crate) use crate::read::sealed;
pub use crate::read::{
ComputeSize, FontRead, FontReadWithArgs, Format, ReadArgs, ReadError, VarSize,
};
pub use crate::table_provider::TopLevelTable;
pub use crate::table_ref::{MinByteRange, TableRef};
pub use std::ops::Range;
pub use types::*;
#[cfg(feature = "experimental_traverse")]
pub use crate::traversal::{self, Field, FieldType, RecordResolver, SomeRecord, SomeTable};
// used in generated traversal code to get type names of offset fields, which
// may include generics
#[cfg(feature = "experimental_traverse")]
pub(crate) fn better_type_name<T>() -> &'static str {
let raw_name = std::any::type_name::<T>();
let last = raw_name.rsplit("::").next().unwrap_or(raw_name);
// this happens if we end up getting a type name like TableRef<'a, module::SomeMarker>
last.trim_end_matches("Marker>")
}
/// named transforms used in 'count', e.g
pub(crate) mod transforms {
pub fn subtract<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
lhs.try_into()
.unwrap_or_default()
.saturating_sub(rhs.try_into().unwrap_or_default())
}
pub fn add<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
lhs.try_into()
.unwrap_or_default()
.saturating_add(rhs.try_into().unwrap_or_default())
}
#[allow(dead_code)]
pub fn bitmap_len<T: TryInto<usize>>(count: T) -> usize {
count.try_into().unwrap_or_default().div_ceil(8)
}
#[cfg(feature = "ift")]
pub fn max_value_bitmap_len<T: TryInto<usize>>(count: T) -> usize {
let count: usize = count.try_into().unwrap_or_default() + 1usize;
count.div_ceil(8)
}
pub fn add_multiply<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
a: T,
b: U,
c: V,
) -> usize {
a.try_into()
.unwrap_or_default()
.saturating_add(b.try_into().unwrap_or_default())
.saturating_mul(c.try_into().unwrap_or_default())
}
#[cfg(feature = "ift")]
pub fn multiply_add<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
a: T,
b: U,
c: V,
) -> usize {
a.try_into()
.unwrap_or_default()
.saturating_mul(b.try_into().unwrap_or_default())
.saturating_add(c.try_into().unwrap_or_default())
}
pub fn half<T: TryInto<usize>>(val: T) -> usize {
val.try_into().unwrap_or_default() / 2
}
pub fn subtract_add_two<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
lhs.try_into()
.unwrap_or_default()
.saturating_sub(rhs.try_into().unwrap_or_default())
.saturating_add(2)
}
}
}
include!("../generated/font.rs");
#[derive(Clone)]
/// Reference to the content of a font or font collection file.
pub enum FileRef<'a> {
/// A single font.
Font(FontRef<'a>),
/// A collection of fonts.
Collection(CollectionRef<'a>),
}
impl<'a> FileRef<'a> {
/// Creates a new reference to a file representing a font or font collection.
pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
Ok(if let Ok(collection) = CollectionRef::new(data) {
Self::Collection(collection)
} else {
Self::Font(FontRef::new(data)?)
})
}
/// Returns an iterator over the fonts contained in the file.
pub fn fonts(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
let (iter_one, iter_two) = match self {
Self::Font(font) => (Some(Ok(font.clone())), None),
Self::Collection(collection) => (None, Some(collection.iter())),
};
iter_two.into_iter().flatten().chain(iter_one)
}
}
/// Reference to the content of a font collection file.
#[derive(Clone)]
pub struct CollectionRef<'a> {
data: FontData<'a>,
header: TTCHeader<'a>,
}
impl<'a> CollectionRef<'a> {
/// Creates a new reference to a font collection.
pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
let data = FontData::new(data);
let header = TTCHeader::read(data)?;
if header.ttc_tag() != TTC_HEADER_TAG {
Err(ReadError::InvalidTtc(header.ttc_tag()))
} else {
Ok(Self { data, header })
}
}
/// Returns the number of fonts in the collection.
pub fn len(&self) -> u32 {
self.header.num_fonts()
}
/// Returns true if the collection is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the font in the collection at the specified index.
pub fn get(&self, index: u32) -> Result<FontRef<'a>, ReadError> {
let offset = self
.header
.table_directory_offsets()
.get(index as usize)
.ok_or(ReadError::InvalidCollectionIndex(index))?
.get() as usize;
let table_dir_data = self.data.slice(offset..).ok_or(ReadError::OutOfBounds)?;
FontRef::with_table_directory(self.data, TableDirectory::read(table_dir_data)?)
}
/// Returns an iterator over the fonts in the collection.
pub fn iter(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
let copy = self.clone();
(0..self.len()).map(move |ix| copy.get(ix))
}
}
/// Reference to an in-memory font.
///
/// This is a simple implementation of the [`TableProvider`] trait backed
/// by a borrowed slice containing font data.
#[derive(Clone)]
pub struct FontRef<'a> {
pub data: FontData<'a>,
pub table_directory: TableDirectory<'a>,
}
impl<'a> FontRef<'a> {
/// Creates a new reference to an in-memory font backed by the given data.
///
/// The data must be a single font (not a font collection) and must begin with a
/// [table directory] to be considered valid.
///
/// To load a font from a font collection, use [`FontRef::from_index`] instead.
///
/// [table directory]: https://github.com/googlefonts/fontations/pull/549
pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
let data = FontData::new(data);
Self::with_table_directory(data, TableDirectory::read(data)?)
}
/// Creates a new reference to an in-memory font at the specified index
/// backed by the given data.
///
/// The data slice must begin with either a
/// [table directory](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
/// or a [ttc header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
/// to be considered valid.
///
/// In other words, this accepts either font collection (ttc) or single
/// font (ttf/otf) files. If a single font file is provided, the index
/// parameter must be 0.
pub fn from_index(data: &'a [u8], index: u32) -> Result<Self, ReadError> {
let file = FileRef::new(data)?;
match file {
FileRef::Font(font) => {
if index == 0 {
Ok(font)
} else {
Err(ReadError::InvalidCollectionIndex(index))
}
}
FileRef::Collection(collection) => collection.get(index),
}
}
/// Returns the data for the table with the specified tag, if present.
pub fn table_data(&self, tag: Tag) -> Option<FontData<'a>> {
self.table_directory
.table_records()
.binary_search_by(|rec| rec.tag.get().cmp(&tag))
.ok()
.and_then(|idx| self.table_directory.table_records().get(idx))
.and_then(|record| {
let start = Offset32::new(record.offset()).non_null()?;
let len = record.length() as usize;
self.data.slice(start..start.checked_add(len)?)
})
}
fn with_table_directory(
data: FontData<'a>,
table_directory: TableDirectory<'a>,
) -> Result<Self, ReadError> {
if [TT_SFNT_VERSION, CFF_SFNT_VERSION, TRUE_SFNT_VERSION]
.contains(&table_directory.sfnt_version())
{
Ok(FontRef {
data,
table_directory,
})
} else {
Err(ReadError::InvalidSfnt(table_directory.sfnt_version()))
}
}
}
impl<'a> TableProvider<'a> for FontRef<'a> {
fn data_for_tag(&self, tag: Tag) -> Option<FontData<'a>> {
self.table_data(tag)
}
}
#[cfg(test)]
mod tests {
use font_test_data::{ttc::TTC, AHEM};
use crate::FileRef;
#[test]
fn file_ref_non_collection() {
assert!(matches!(FileRef::new(AHEM), Ok(FileRef::Font(_))));
}
#[test]
fn file_ref_collection() {
let Ok(FileRef::Collection(collection)) = FileRef::new(TTC) else {
panic!("Expected a collection");
};
assert_eq!(2, collection.len());
assert!(!collection.is_empty());
}
}
+96
View File
@@ -0,0 +1,96 @@
//! Handling offsets
use super::read::{FontRead, ReadError};
use crate::{font_data::FontData, read::FontReadWithArgs};
use types::{Nullable, Offset16, Offset24, Offset32};
/// Any offset type.
pub trait Offset: Copy {
fn to_usize(self) -> usize;
fn non_null(self) -> Option<usize> {
match self.to_usize() {
0 => None,
other => Some(other),
}
}
}
macro_rules! impl_offset {
($name:ident, $width:literal) => {
impl Offset for $name {
#[inline]
fn to_usize(self) -> usize {
self.to_u32() as _
}
}
};
}
impl_offset!(Offset16, 2);
impl_offset!(Offset24, 3);
impl_offset!(Offset32, 4);
/// A helper trait providing a 'resolve' method for offset types
pub trait ResolveOffset {
fn resolve<'a, T: FontRead<'a>>(&self, data: FontData<'a>) -> Result<T, ReadError>;
fn resolve_with_args<'a, T: FontReadWithArgs<'a>>(
&self,
data: FontData<'a>,
args: &T::Args,
) -> Result<T, ReadError>;
}
/// A helper trait providing a 'resolve' method for nullable offset types
pub trait ResolveNullableOffset {
fn resolve<'a, T: FontRead<'a>>(&self, data: FontData<'a>) -> Option<Result<T, ReadError>>;
fn resolve_with_args<'a, T: FontReadWithArgs<'a>>(
&self,
data: FontData<'a>,
args: &T::Args,
) -> Option<Result<T, ReadError>>;
}
impl<O: Offset> ResolveNullableOffset for Nullable<O> {
fn resolve<'a, T: FontRead<'a>>(&self, data: FontData<'a>) -> Option<Result<T, ReadError>> {
match self.offset().resolve(data) {
Ok(thing) => Some(Ok(thing)),
Err(ReadError::NullOffset) => None,
Err(e) => Some(Err(e)),
}
}
fn resolve_with_args<'a, T: FontReadWithArgs<'a>>(
&self,
data: FontData<'a>,
args: &T::Args,
) -> Option<Result<T, ReadError>> {
match self.offset().resolve_with_args(data, args) {
Ok(thing) => Some(Ok(thing)),
Err(ReadError::NullOffset) => None,
Err(e) => Some(Err(e)),
}
}
}
impl<O: Offset> ResolveOffset for O {
fn resolve<'a, T: FontRead<'a>>(&self, data: FontData<'a>) -> Result<T, ReadError> {
self.non_null()
.ok_or(ReadError::NullOffset)
.and_then(|off| data.split_off(off).ok_or(ReadError::OutOfBounds))
.and_then(T::read)
}
fn resolve_with_args<'a, T: FontReadWithArgs<'a>>(
&self,
data: FontData<'a>,
args: &T::Args,
) -> Result<T, ReadError> {
self.non_null()
.ok_or(ReadError::NullOffset)
.and_then(|off| data.split_off(off).ok_or(ReadError::OutOfBounds))
.and_then(|data| T::read_with_args(data, args))
}
}
+148
View File
@@ -0,0 +1,148 @@
//! Arrays of offsets with dynamic resolution
//!
//! This module provides a number of types that wrap arrays of offsets, dynamically
//! resolving individual offsets as they are accessed.
use crate::offset::ResolveNullableOffset;
use font_types::{BigEndian, Nullable, Offset16, Scalar};
use crate::{FontData, FontReadWithArgs, Offset, ReadArgs, ReadError, ResolveOffset};
/// An array of offsets that can be resolved on access.
///
/// This bundles up the raw offsets with the data used to resolve them, along
/// with any arguments needed to resolve those offsets; it provides a simple
/// ergonomic interface that unburdens the user from needing to manually
/// determine the appropriate input data and arguments for a raw offset.
#[derive(Clone)]
pub struct ArrayOfOffsets<'a, T: ReadArgs, O: Scalar = Offset16> {
offsets: &'a [BigEndian<O>],
data: FontData<'a>,
args: T::Args,
}
/// An array of nullable offsets that can be resolved on access.
///
/// This is identical to [`ArrayOfOffsets`], except that each offset is
/// allowed to be null.
#[derive(Clone)]
pub struct ArrayOfNullableOffsets<'a, T: ReadArgs, O: Scalar = Offset16> {
offsets: &'a [BigEndian<Nullable<O>>],
data: FontData<'a>,
args: T::Args,
}
impl<'a, T, O> ArrayOfOffsets<'a, T, O>
where
O: Scalar,
T: ReadArgs,
{
pub(crate) fn new(offsets: &'a [BigEndian<O>], data: FontData<'a>, args: T::Args) -> Self {
Self {
offsets,
data,
args,
}
}
}
impl<'a, T, O> ArrayOfOffsets<'a, T, O>
where
O: Scalar + Offset,
T: ReadArgs + FontReadWithArgs<'a>,
T::Args: Copy + 'static,
{
/// The number of offsets in the array
pub fn len(&self) -> usize {
self.offsets.len()
}
/// `true` if the array is empty
pub fn is_empty(&self) -> bool {
self.offsets.is_empty()
}
/// Resolve the offset at the provided index.
///
/// Note: if the index is invalid this will return the `InvalidCollectionIndex`
/// error variant instead of `None`.
pub fn get(&self, idx: usize) -> Result<T, ReadError> {
self.offsets
.get(idx)
.ok_or(ReadError::InvalidCollectionIndex(idx as _))
.and_then(|o| o.get().resolve_with_args(self.data, &self.args))
}
/// Iterate over all of the offset targets.
///
/// Each offset will be resolved as it is encountered.
pub fn iter(&self) -> impl Iterator<Item = Result<T, ReadError>> + 'a {
let mut iter = self.offsets.iter();
let args = self.args;
let data = self.data;
std::iter::from_fn(move || {
iter.next()
.map(|off| off.get().resolve_with_args(data, &args))
})
}
}
impl<'a, T, O> ArrayOfNullableOffsets<'a, T, O>
where
O: Scalar + Offset,
T: ReadArgs,
{
pub(crate) fn new(
offsets: &'a [BigEndian<Nullable<O>>],
data: FontData<'a>,
args: T::Args,
) -> Self {
Self {
offsets,
data,
args,
}
}
}
impl<'a, T, O> ArrayOfNullableOffsets<'a, T, O>
where
O: Scalar + Offset,
T: ReadArgs + FontReadWithArgs<'a>,
T::Args: Copy + 'static,
{
/// The number of offsets in the array
pub fn len(&self) -> usize {
self.offsets.len()
}
/// `true` if the array is empty
pub fn is_empty(&self) -> bool {
self.offsets.is_empty()
}
/// Resolve the offset at the provided index.
///
/// This will return `None` only if the offset *exists*, but is null. if the
/// provided index does not exist, this will return the `InvalidCollectionIndex`
/// error variant.
pub fn get(&self, idx: usize) -> Option<Result<T, ReadError>> {
let Some(offset) = self.offsets.get(idx) else {
return Some(Err(ReadError::InvalidCollectionIndex(idx as _)));
};
offset.get().resolve_with_args(self.data, &self.args)
}
/// Iterate over all of the offset targets.
///
/// Each offset will be resolved as it is encountered.
pub fn iter(&self) -> impl Iterator<Item = Option<Result<T, ReadError>>> + 'a {
let mut iter = self.offsets.iter();
let args = self.args;
let data = self.data;
std::iter::from_fn(move || {
iter.next()
.map(|off| off.get().resolve_with_args(data, &args))
})
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Traits for interpreting font data
#![deny(clippy::arithmetic_side_effects)]
use types::{FixedSize, Scalar, Tag};
use crate::font_data::FontData;
/// A type that can be read from raw table data.
///
/// This trait is implemented for all font tables that are self-describing: that
/// is, tables that do not require any external state in order to interpret their
/// underlying bytes. (Tables that require external state implement
/// [`FontReadWithArgs`] instead)
pub trait FontRead<'a>: Sized {
/// Read an instance of `Self` from the provided data, performing validation.
///
/// In the case of a table, this method is responsible for ensuring the input
/// data is consistent: this means ensuring that any versioned fields are
/// present as required by the version, and that any array lengths are not
/// out-of-bounds.
fn read(data: FontData<'a>) -> Result<Self, ReadError>;
}
//NOTE: this is separate so that it can be a super trait of FontReadWithArgs and
//ComputeSize, without them needing to know about each other? I'm not sure this
//is necessary, but I don't know the full hierarchy of traits I'm going to need
//yet, so this seems... okay?
/// A trait for a type that needs additional arguments to be read.
pub trait ReadArgs {
type Args: Copy;
}
/// A trait for types that require external data in order to be constructed.
///
/// You should not need to use this directly; it is intended to be used from
/// generated code. Any type that requires external arguments also has a custom
/// `read` constructor where you can pass those arguments like normal.
pub trait FontReadWithArgs<'a>: Sized + ReadArgs {
/// read an item, using the provided args.
///
/// If successful, returns a new item of this type, and the number of bytes
/// used to construct it.
///
/// If a type requires multiple arguments, they will be passed as a tuple.
fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, ReadError>;
}
// a blanket impl of ReadArgs/FontReadWithArgs for general FontRead types.
//
// This is used by ArrayOfOffsets/ArrayOfNullableOffsets to provide a common
// interface for regardless of whether a type has args.
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)
}
}
/// A trait for tables that have multiple possible formats.
pub trait Format<T> {
/// The format value for this table.
const FORMAT: T;
}
/// A type that can compute its size at runtime, based on some input.
///
/// For types with a constant size, see [`FixedSize`] and
/// for types which store their size inline, see [`VarSize`].
pub trait ComputeSize: ReadArgs {
/// Compute the number of bytes required to represent this type.
fn compute_size(args: &Self::Args) -> Result<usize, ReadError>;
}
/// A trait for types that have variable length.
///
/// As a rule, these types have an initial length field.
///
/// For types with a constant size, see [`FixedSize`] and
/// for types which can pre-compute their size, see [`ComputeSize`].
pub trait VarSize {
/// The type of the first (length) field of the item.
///
/// When reading this type, we will read this value first, and use it to
/// determine the total length.
type Size: Scalar + Into<u32>;
#[doc(hidden)]
fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
let asu32 = data.read_at::<Self::Size>(pos).ok()?.into();
(asu32 as usize).checked_add(Self::Size::RAW_BYTE_LEN)
}
/// Determine the total length required to store `count` items of `Self` in
/// `data` starting from `start`.
#[doc(hidden)]
fn total_len_for_count(data: FontData, count: usize) -> Result<usize, ReadError> {
(0..count).try_fold(0usize, |current_pos, _i| {
Self::read_len_at(data, current_pos)
.and_then(|i_len| current_pos.checked_add(i_len))
.ok_or(ReadError::OutOfBounds)
})
}
}
/// An error that occurs when reading font data
#[derive(Debug, Clone, PartialEq)]
pub enum ReadError {
OutOfBounds,
// i64 is flexible enough to store any value we might encounter
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 occurred"),
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 {}
+301
View File
@@ -0,0 +1,301 @@
//! a trait for things that can serve font tables
use types::{BigEndian, Tag};
use crate::{tables, FontData, FontRead, ReadError};
/// A table that has an associated tag.
///
/// This is true of top-level tables, but not their various subtables.
pub trait TopLevelTable {
/// The table's tag.
const TAG: Tag;
}
/// An interface for accessing tables from a font (or font-like object)
pub trait TableProvider<'a> {
fn data_for_tag(&self, tag: Tag) -> Option<FontData<'a>>;
fn expect_data_for_tag(&self, tag: Tag) -> Result<FontData<'a>, ReadError> {
self.data_for_tag(tag).ok_or(ReadError::TableIsMissing(tag))
}
fn expect_table<T: TopLevelTable + FontRead<'a>>(&self) -> Result<T, ReadError> {
self.expect_data_for_tag(T::TAG).and_then(FontRead::read)
}
fn head(&self) -> Result<tables::head::Head<'a>, ReadError> {
self.expect_table()
}
fn name(&self) -> Result<tables::name::Name<'a>, ReadError> {
self.expect_table()
}
fn hhea(&self) -> Result<tables::hhea::Hhea<'a>, ReadError> {
self.expect_table()
}
fn vhea(&self) -> Result<tables::vhea::Vhea<'a>, ReadError> {
self.expect_table()
}
fn hmtx(&self) -> Result<tables::hmtx::Hmtx<'a>, ReadError> {
//FIXME: should we make the user pass these in?
let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
let number_of_h_metrics = self.hhea().map(|hhea| hhea.number_of_h_metrics())?;
let data = self.expect_data_for_tag(tables::hmtx::Hmtx::TAG)?;
tables::hmtx::Hmtx::read(data, number_of_h_metrics, num_glyphs)
}
fn hdmx(&self) -> Result<tables::hdmx::Hdmx<'a>, ReadError> {
let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
let data = self.expect_data_for_tag(tables::hdmx::Hdmx::TAG)?;
tables::hdmx::Hdmx::read(data, num_glyphs)
}
fn vmtx(&self) -> Result<tables::vmtx::Vmtx<'a>, ReadError> {
//FIXME: should we make the user pass these in?
let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
let number_of_v_metrics = self.vhea().map(|vhea| vhea.number_of_long_ver_metrics())?;
let data = self.expect_data_for_tag(tables::vmtx::Vmtx::TAG)?;
tables::vmtx::Vmtx::read(data, number_of_v_metrics, num_glyphs)
}
fn vorg(&self) -> Result<tables::vorg::Vorg<'a>, ReadError> {
self.expect_table()
}
fn fvar(&self) -> Result<tables::fvar::Fvar<'a>, ReadError> {
self.expect_table()
}
fn avar(&self) -> Result<tables::avar::Avar<'a>, ReadError> {
self.expect_table()
}
fn hvar(&self) -> Result<tables::hvar::Hvar<'a>, ReadError> {
self.expect_table()
}
fn vvar(&self) -> Result<tables::vvar::Vvar<'a>, ReadError> {
self.expect_table()
}
fn mvar(&self) -> Result<tables::mvar::Mvar<'a>, ReadError> {
self.expect_table()
}
fn maxp(&self) -> Result<tables::maxp::Maxp<'a>, ReadError> {
self.expect_table()
}
fn os2(&self) -> Result<tables::os2::Os2<'a>, ReadError> {
self.expect_table()
}
fn post(&self) -> Result<tables::post::Post<'a>, ReadError> {
self.expect_table()
}
fn gasp(&self) -> Result<tables::gasp::Gasp<'a>, ReadError> {
self.expect_table()
}
/// is_long can be optionally provided, if known, otherwise we look it up in head.
fn loca(&self, is_long: impl Into<Option<bool>>) -> Result<tables::loca::Loca<'a>, ReadError> {
let is_long = match is_long.into() {
Some(val) => val,
None => self.head()?.index_to_loc_format() == 1,
};
let data = self.expect_data_for_tag(tables::loca::Loca::TAG)?;
tables::loca::Loca::read(data, is_long)
}
fn glyf(&self) -> Result<tables::glyf::Glyf<'a>, ReadError> {
self.expect_table()
}
fn gvar(&self) -> Result<tables::gvar::Gvar<'a>, ReadError> {
self.expect_table()
}
/// Returns the array of entries for the control value table which is used
/// for TrueType hinting.
fn cvt(&self) -> Result<&'a [BigEndian<i16>], ReadError> {
let table_data = self.expect_data_for_tag(Tag::new(b"cvt "))?;
table_data.read_array(0..table_data.len())
}
fn cvar(&self) -> Result<tables::cvar::Cvar<'a>, ReadError> {
self.expect_table()
}
fn cff(&self) -> Result<tables::cff::Cff<'a>, ReadError> {
self.expect_table()
}
fn cff2(&self) -> Result<tables::cff2::Cff2<'a>, ReadError> {
self.expect_table()
}
fn cmap(&self) -> Result<tables::cmap::Cmap<'a>, ReadError> {
self.expect_table()
}
fn gdef(&self) -> Result<tables::gdef::Gdef<'a>, ReadError> {
self.expect_table()
}
fn gpos(&self) -> Result<tables::gpos::Gpos<'a>, ReadError> {
self.expect_table()
}
fn gsub(&self) -> Result<tables::gsub::Gsub<'a>, ReadError> {
self.expect_table()
}
fn feat(&self) -> Result<tables::feat::Feat<'a>, ReadError> {
self.expect_table()
}
fn ltag(&self) -> Result<tables::ltag::Ltag<'a>, ReadError> {
self.expect_table()
}
fn ankr(&self) -> Result<tables::ankr::Ankr<'a>, ReadError> {
self.expect_table()
}
fn trak(&self) -> Result<tables::trak::Trak<'a>, ReadError> {
self.expect_table()
}
fn morx(&self) -> Result<tables::morx::Morx<'a>, ReadError> {
self.expect_table()
}
fn kerx(&self) -> Result<tables::kerx::Kerx<'a>, ReadError> {
self.expect_table()
}
fn kern(&self) -> Result<tables::kern::Kern<'a>, ReadError> {
self.expect_table()
}
fn colr(&self) -> Result<tables::colr::Colr<'a>, ReadError> {
self.expect_table()
}
fn cpal(&self) -> Result<tables::cpal::Cpal<'a>, ReadError> {
self.expect_table()
}
fn cblc(&self) -> Result<tables::cblc::Cblc<'a>, ReadError> {
self.expect_table()
}
fn cbdt(&self) -> Result<tables::cbdt::Cbdt<'a>, ReadError> {
self.expect_table()
}
fn eblc(&self) -> Result<tables::eblc::Eblc<'a>, ReadError> {
self.expect_table()
}
fn ebdt(&self) -> Result<tables::ebdt::Ebdt<'a>, ReadError> {
self.expect_table()
}
fn sbix(&self) -> Result<tables::sbix::Sbix<'a>, ReadError> {
// should we make the user pass this in?
let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
let data = self.expect_data_for_tag(tables::sbix::Sbix::TAG)?;
tables::sbix::Sbix::read(data, num_glyphs)
}
fn stat(&self) -> Result<tables::stat::Stat<'a>, ReadError> {
self.expect_table()
}
fn svg(&self) -> Result<tables::svg::Svg<'a>, ReadError> {
self.expect_table()
}
fn varc(&self) -> Result<tables::varc::Varc<'a>, ReadError> {
self.expect_table()
}
#[cfg(feature = "ift")]
fn ift(&self) -> Result<tables::ift::Ift<'a>, ReadError> {
self.expect_data_for_tag(tables::ift::IFT_TAG)
.and_then(FontRead::read)
}
#[cfg(feature = "ift")]
fn iftx(&self) -> Result<tables::ift::Ift<'a>, ReadError> {
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()
}
fn base(&self) -> Result<tables::base::Base<'a>, ReadError> {
self.expect_table()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// https://github.com/googlefonts/fontations/issues/105
#[test]
fn bug_105() {
// serve some dummy versions of the tables used to compute hmtx. The only
// fields that matter are maxp::num_glyphs and hhea::number_of_h_metrics,
// everything else is zero'd out
struct DummyProvider;
impl TableProvider<'static> for DummyProvider {
fn data_for_tag(&self, tag: Tag) -> Option<FontData<'static>> {
if tag == Tag::new(b"maxp") {
Some(FontData::new(&[
0, 0, 0x50, 0, // version 0.5
0, 3, // num_glyphs = 3
]))
} else if tag == Tag::new(b"hhea") {
Some(FontData::new(&[
0, 1, 0, 0, // version 1.0
0, 0, 0, 0, // ascender/descender
0, 0, 0, 0, // line gap/advance width
0, 0, 0, 0, // min left/right side bearing
0, 0, 0, 0, // x_max, caret_slope_rise
0, 0, 0, 0, // caret_slope_run, caret_offset
0, 0, 0, 0, // reserved1/2
0, 0, 0, 0, // reserved 3/4
0, 0, 0, 1, // metric format, number_of_h_metrics
]))
} else if tag == Tag::new(b"hmtx") {
Some(FontData::new(&[
0, 4, 0, 6, // LongHorMetric: 4, 6
0, 30, 0, 111, // two lsb entries
]))
} else {
None
}
}
}
let number_of_h_metrics = DummyProvider.hhea().unwrap().number_of_h_metrics();
let num_glyphs = DummyProvider.maxp().unwrap().num_glyphs();
let hmtx = DummyProvider.hmtx().unwrap();
assert_eq!(number_of_h_metrics, 1);
assert_eq!(num_glyphs, 3);
assert_eq!(hmtx.h_metrics().len(), 1);
assert_eq!(hmtx.left_side_bearings().len(), 2);
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Typed font tables
use super::read::{FontRead, Format, ReadError};
use crate::{
font_data::FontData,
offset::{Offset, ResolveOffset},
};
use std::ops::Range;
/// Return the minimum range of the table bytes
///
/// This trait is implemented in generated code, and we use this to get the minimum length/bytes of a table
pub trait MinByteRange {
fn min_byte_range(&self) -> Range<usize>;
}
#[derive(Clone)]
/// Typed access to raw table data.
pub struct TableRef<'a, T> {
pub(crate) shape: T,
pub(crate) data: FontData<'a>,
}
impl<'a, T> TableRef<'a, T> {
/// Resolve the provided offset from the start of this table.
pub fn resolve_offset<O: Offset, R: FontRead<'a>>(&self, offset: O) -> Result<R, ReadError> {
offset.resolve(self.data)
}
/// Return a reference to this table's raw data.
///
/// We use this in the compile crate to resolve offsets.
pub fn offset_data(&self) -> FontData<'a> {
self.data
}
/// Return a reference to the table's 'Shape' struct.
///
/// This is a low level implementation detail, but it can be useful in
/// some cases where you want to know things about a table's layout, such
/// as the byte offsets of specific fields.
pub fn shape(&self) -> &T {
&self.shape
}
}
// a blanket impl so that the format is available through a TableRef
impl<U, T: Format<U>> Format<U> for TableRef<'_, T> {
const FORMAT: U = T::FORMAT;
}
impl<'a, T: MinByteRange> TableRef<'a, T> {
/// Return the minimum byte range of this table
pub fn min_byte_range(&self) -> Range<usize> {
self.shape.min_byte_range()
}
/// Return the minimum bytes of this table
pub fn min_table_bytes(&self) -> &'a [u8] {
self.offset_data()
.as_bytes()
.get(self.shape.min_byte_range())
.unwrap_or_default()
}
}
+79
View File
@@ -0,0 +1,79 @@
//! The various font tables
pub mod aat;
pub mod ankr;
pub mod avar;
pub mod base;
pub mod bitmap;
pub mod cbdt;
pub mod cblc;
pub mod cff;
pub mod cff2;
pub mod cmap;
pub mod colr;
pub mod cpal;
pub mod cvar;
pub mod ebdt;
pub mod eblc;
pub mod feat;
pub mod fvar;
pub mod gasp;
pub mod gdef;
pub mod glyf;
pub mod gpos;
pub mod gsub;
pub mod gvar;
pub mod hdmx;
pub mod head;
pub mod hhea;
pub mod hmtx;
pub mod hvar;
pub mod kern;
pub mod kerx;
pub mod layout;
pub mod loca;
pub mod ltag;
pub mod maxp;
pub mod meta;
pub mod morx;
pub mod mvar;
pub mod name;
pub mod os2;
pub mod post;
pub mod postscript;
pub mod sbix;
pub mod stat;
pub mod svg;
pub mod trak;
pub mod varc;
pub mod variations;
pub mod vhea;
pub mod vmtx;
pub mod vorg;
pub mod vvar;
#[cfg(feature = "ift")]
pub mod ift;
/// Computes the table checksum for the given data.
///
/// See the OpenType [specification](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#calculating-checksums)
/// for details.
pub fn compute_checksum(table: &[u8]) -> u32 {
let mut sum = 0u32;
let mut iter = table.chunks_exact(4);
for quad in &mut iter {
// this can't fail, and we trust the compiler to avoid a branch
let array: [u8; 4] = quad.try_into().unwrap_or_default();
sum = sum.wrapping_add(u32::from_be_bytes(array));
}
let rem = match *iter.remainder() {
[a] => u32::from_be_bytes([a, 0, 0, 0]),
[a, b] => u32::from_be_bytes([a, b, 0, 0]),
[a, b, c] => u32::from_be_bytes([a, b, c, 0]),
_ => 0,
};
sum.wrapping_add(rem)
}
+805
View File
@@ -0,0 +1,805 @@
//! Apple Advanced Typography common tables.
//!
//! See <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html>
include!("../../generated/generated_aat.rs");
/// Predefined classes.
///
/// See <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html>
pub mod class {
pub const END_OF_TEXT: u8 = 0;
pub const OUT_OF_BOUNDS: u8 = 1;
pub const DELETED_GLYPH: u8 = 2;
}
impl Lookup0<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
let data = self.values_data();
let data_len = data.len();
let n_elems = data_len / T::RAW_BYTE_LEN;
let len_in_bytes = n_elems * T::RAW_BYTE_LEN;
FontData::new(&data[..len_in_bytes])
.cursor()
.read_array::<BigEndian<T>>(n_elems)?
.get(index as usize)
.map(|val| val.get())
.ok_or(ReadError::OutOfBounds)
}
}
/// Lookup segment for format 2.
#[derive(Copy, Clone, bytemuck::AnyBitPattern)]
#[repr(C, packed)]
pub struct LookupSegment2<T>
where
T: LookupValue,
{
/// Last glyph index in this segment.
pub last_glyph: BigEndian<u16>,
/// First glyph index in this segment.
pub first_glyph: BigEndian<u16>,
/// The lookup value.
pub value: BigEndian<T>,
}
/// Note: this requires `LookupSegment2` to be `repr(packed)`.
impl<T: LookupValue> FixedSize for LookupSegment2<T> {
const RAW_BYTE_LEN: usize = std::mem::size_of::<Self>();
}
impl Lookup2<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
let segments = self.segments::<T>()?;
let ix = match segments.binary_search_by(|segment| segment.first_glyph.get().cmp(&index)) {
Ok(ix) => ix,
Err(ix) => ix.saturating_sub(1),
};
let segment = segments.get(ix).ok_or(ReadError::OutOfBounds)?;
if (segment.first_glyph.get()..=segment.last_glyph.get()).contains(&index) {
let value = segment.value;
return Ok(value.get());
}
Err(ReadError::OutOfBounds)
}
fn segments<T: LookupValue>(&self) -> Result<&[LookupSegment2<T>], ReadError> {
FontData::new(self.segments_data())
.cursor()
.read_array(self.n_units() as usize)
}
}
impl Lookup4<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
let segments = self.segments();
let ix = match segments.binary_search_by(|segment| segment.first_glyph.get().cmp(&index)) {
Ok(ix) => ix,
Err(ix) => ix.saturating_sub(1),
};
let segment = segments.get(ix).ok_or(ReadError::OutOfBounds)?;
if (segment.first_glyph.get()..=segment.last_glyph.get()).contains(&index) {
let base_offset = segment.value_offset() as usize;
let offset = base_offset
+ index
.checked_sub(segment.first_glyph())
.ok_or(ReadError::OutOfBounds)? as usize
* T::RAW_BYTE_LEN;
return self.offset_data().read_at(offset);
}
Err(ReadError::OutOfBounds)
}
}
/// Lookup single record for format 6.
#[derive(Copy, Clone, bytemuck::AnyBitPattern)]
#[repr(C, packed)]
pub struct LookupSingle<T>
where
T: LookupValue,
{
/// The glyph index.
pub glyph: BigEndian<u16>,
/// The lookup value.
pub value: BigEndian<T>,
}
/// Note: this requires `LookupSingle` to be `repr(packed)`.
impl<T: LookupValue> FixedSize for LookupSingle<T> {
const RAW_BYTE_LEN: usize = std::mem::size_of::<Self>();
}
impl Lookup6<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
let entries = self.entries::<T>()?;
if let Ok(ix) = entries.binary_search_by_key(&index, |entry| entry.glyph.get()) {
let entry = &entries[ix];
let value = entry.value;
return Ok(value.get());
}
Err(ReadError::OutOfBounds)
}
fn entries<T: LookupValue>(&self) -> Result<&[LookupSingle<T>], ReadError> {
FontData::new(self.entries_data())
.cursor()
.read_array(self.n_units() as usize)
}
}
impl Lookup8<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
index
.checked_sub(self.first_glyph())
.and_then(|ix| {
self.value_array()
.get(ix as usize)
.map(|val| T::from_u16(val.get()))
})
.ok_or(ReadError::OutOfBounds)
}
}
impl Lookup10<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
let ix = index
.checked_sub(self.first_glyph())
.ok_or(ReadError::OutOfBounds)? as usize;
let unit_size = self.unit_size() as usize;
let offset = ix * unit_size;
let mut cursor = FontData::new(self.values_data()).cursor();
cursor.advance_by(offset);
let val = match unit_size {
1 => cursor.read::<u8>()? as u32,
2 => cursor.read::<u16>()? as u32,
4 => cursor.read::<u32>()?,
_ => {
return Err(ReadError::MalformedData(
"invalid unit_size in format 10 AAT lookup table",
))
}
};
Ok(T::from_u32(val))
}
}
impl Lookup<'_> {
pub fn value<T: LookupValue>(&self, index: u16) -> Result<T, ReadError> {
match self {
Lookup::Format0(lookup) => lookup.value::<T>(index),
Lookup::Format2(lookup) => lookup.value::<T>(index),
Lookup::Format4(lookup) => lookup.value::<T>(index),
Lookup::Format6(lookup) => lookup.value::<T>(index),
Lookup::Format8(lookup) => lookup.value::<T>(index),
Lookup::Format10(lookup) => lookup.value::<T>(index),
}
}
}
#[derive(Clone)]
pub struct TypedLookup<'a, T> {
lookup: Lookup<'a>,
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: LookupValue> TypedLookup<'_, T> {
/// Returns the value associated with the given index.
pub fn value(&self, index: u16) -> Result<T, ReadError> {
self.lookup.value::<T>(index)
}
}
impl<'a, T> FontRead<'a> for TypedLookup<'a, T> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
Ok(Self {
lookup: Lookup::read(data)?,
_marker: std::marker::PhantomData,
})
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a, T> SomeTable<'a> for TypedLookup<'a, T> {
fn type_name(&self) -> &str {
"TypedLookup"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
self.lookup.get_field(idx)
}
}
/// Trait for values that can be read from lookup tables.
pub trait LookupValue: Copy + Scalar + bytemuck::AnyBitPattern {
fn from_u16(v: u16) -> Self;
fn from_u32(v: u32) -> Self;
}
impl LookupValue for u16 {
fn from_u16(v: u16) -> Self {
v
}
fn from_u32(v: u32) -> Self {
// intentionally truncates
v as _
}
}
impl LookupValue for u32 {
fn from_u16(v: u16) -> Self {
v as _
}
fn from_u32(v: u32) -> Self {
v
}
}
impl LookupValue for GlyphId16 {
fn from_u16(v: u16) -> Self {
GlyphId16::from(v)
}
fn from_u32(v: u32) -> Self {
// intentionally truncates
GlyphId16::from(v as u16)
}
}
pub type LookupU16<'a> = TypedLookup<'a, u16>;
pub type LookupU32<'a> = TypedLookup<'a, u32>;
pub type LookupGlyphId<'a> = TypedLookup<'a, GlyphId16>;
/// Empty data type for a state table entry with no payload.
///
/// Note: this type is only intended for use as the type parameter for
/// `StateEntry`. The inner field is private and this type cannot be
/// constructed outside of this module.
#[derive(Copy, Clone, bytemuck::AnyBitPattern, Debug)]
pub struct NoPayload(());
impl FixedSize for NoPayload {
const RAW_BYTE_LEN: usize = 0;
}
/// Entry in an (extended) state table.
#[derive(Clone, Debug)]
pub struct StateEntry<T = NoPayload> {
/// Index of the next state.
pub new_state: u16,
/// Flag values are table specific.
pub flags: u16,
/// Payload is table specific.
pub payload: T,
}
impl<'a, T: bytemuck::AnyBitPattern + FixedSize> FontRead<'a> for StateEntry<T> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let new_state = cursor.read()?;
let flags = cursor.read()?;
let remaining = cursor.remaining().ok_or(ReadError::OutOfBounds)?;
let payload = *remaining.read_ref_at(0)?;
Ok(Self {
new_state,
flags,
payload,
})
}
}
impl<T> FixedSize for StateEntry<T>
where
T: FixedSize,
{
// Two u16 fields + payload
const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + T::RAW_BYTE_LEN;
}
/// Table for driving a finite state machine for layout.
///
/// The input to the state machine consists of the current state
/// and a glyph class. The output is an [entry](StateEntry) containing
/// the next state and a payload that is dependent on the type of
/// layout action being performed.
///
/// See <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html#StateHeader>
/// for more detail.
#[derive(Clone)]
pub struct StateTable<'a> {
header: StateHeader<'a>,
}
impl StateTable<'_> {
pub const HEADER_LEN: usize = u16::RAW_BYTE_LEN * 4;
/// Returns the class table entry for the given glyph identifier.
pub fn class(&self, glyph_id: GlyphId16) -> Result<u8, ReadError> {
let glyph_id = glyph_id.to_u16();
if glyph_id == 0xFFFF {
return Ok(class::DELETED_GLYPH);
}
let class_table = self.header.class_table()?;
glyph_id
.checked_sub(class_table.first_glyph())
.and_then(|ix| class_table.class_array().get(ix as usize).copied())
.ok_or(ReadError::OutOfBounds)
}
/// Returns the entry for the given state and class.
pub fn entry(&self, state: u16, class: u8) -> Result<StateEntry, ReadError> {
// Each state has a 1-byte entry per class so state_size == n_classes
let n_classes = self.header.state_size() as usize;
if n_classes == 0 {
// Avoid potential divide by zero below
return Err(ReadError::MalformedData("empty AAT state table"));
}
let mut class = class as usize;
if class >= n_classes {
class = class::OUT_OF_BOUNDS as usize;
}
let state_array = self.header.state_array()?.data();
let entry_ix = state_array
.get(
(state as usize)
.checked_mul(n_classes)
.ok_or(ReadError::OutOfBounds)?
+ class,
)
.copied()
.ok_or(ReadError::OutOfBounds)? as usize;
let entry_offset = entry_ix * 4;
let entry_data = self
.header
.entry_table()?
.data()
.get(entry_offset..)
.ok_or(ReadError::OutOfBounds)?;
let mut entry = StateEntry::read(FontData::new(entry_data))?;
// For legacy state tables, the newState is a byte offset into
// the state array. Convert this to an index for consistency.
let new_state = (entry.new_state as i32)
.checked_sub(self.header.state_array_offset().to_u32() as i32)
.ok_or(ReadError::OutOfBounds)?
/ n_classes as i32;
entry.new_state = new_state.try_into().map_err(|_| ReadError::OutOfBounds)?;
Ok(entry)
}
/// Reads scalar values that are referenced from state table entries.
pub fn read_value<T: Scalar>(&self, offset: usize) -> Result<T, ReadError> {
self.header.offset_data().read_at::<T>(offset)
}
}
impl<'a> FontRead<'a> for StateTable<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
Ok(Self {
header: StateHeader::read(data)?,
})
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for StateTable<'a> {
fn type_name(&self) -> &str {
"StateTable"
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
self.header.get_field(idx)
}
}
#[derive(Clone)]
pub struct ExtendedStateTable<'a, T = NoPayload> {
n_classes: usize,
class_table: LookupU16<'a>,
state_array: &'a [BigEndian<u16>],
entry_table: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T> ExtendedStateTable<'_, T> {
pub const HEADER_LEN: usize = u32::RAW_BYTE_LEN * 4;
}
/// Table for driving a finite state machine for layout.
///
/// The input to the state machine consists of the current state
/// and a glyph class. The output is an [entry](StateEntry) containing
/// the next state and a payload that is dependent on the type of
/// layout action being performed.
///
/// See <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html#StateHeader>
/// for more detail.
impl<T> ExtendedStateTable<'_, T>
where
T: FixedSize + bytemuck::AnyBitPattern,
{
/// Returns the class table entry for the given glyph identifier.
pub fn class(&self, glyph_id: GlyphId) -> Result<u16, ReadError> {
let glyph_id: u16 = glyph_id
.to_u32()
.try_into()
.map_err(|_| ReadError::OutOfBounds)?;
if glyph_id == 0xFFFF {
return Ok(class::DELETED_GLYPH as u16);
}
self.class_table.value(glyph_id)
}
/// Returns the entry for the given state and class.
pub fn entry(&self, state: u16, class: u16) -> Result<StateEntry<T>, ReadError> {
let mut class = class as usize;
if class >= self.n_classes {
class = class::OUT_OF_BOUNDS as usize;
}
let state_ix = state as usize * self.n_classes + class;
let entry_ix = self
.state_array
.get(state_ix)
.copied()
.ok_or(ReadError::OutOfBounds)?
.get() as usize;
let entry_offset = entry_ix * StateEntry::<T>::RAW_BYTE_LEN;
let entry_data = self
.entry_table
.get(entry_offset..)
.ok_or(ReadError::OutOfBounds)?;
StateEntry::read(FontData::new(entry_data))
}
}
impl<'a, T> FontRead<'a> for ExtendedStateTable<'a, T> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let header = StxHeader::read(data)?;
let n_classes = header.n_classes() as usize;
let class_table = header.class_table()?;
let state_array = header.state_array()?.data();
let entry_table = header.entry_table()?.data();
Ok(Self {
n_classes,
class_table,
state_array,
entry_table,
_marker: std::marker::PhantomData,
})
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a, T> SomeTable<'a> for ExtendedStateTable<'a, T> {
fn type_name(&self) -> &str {
"ExtendedStateTable"
}
fn get_field(&self, _idx: usize) -> Option<Field<'a>> {
None
}
}
/// Reads an array of T from the given FontData, ensuring that the byte length
/// is a multiple of the size of T.
///
/// Many of the `morx` subtables have arrays without associated lengths so we
/// simply read to the end of the available data. The `FontData::read_array`
/// method will fail if the byte range provided is not exact so this helper
/// allows us to force the lengths to an acceptable value.
pub(crate) fn safe_read_array_to_end<'a, T: bytemuck::AnyBitPattern + FixedSize>(
data: &FontData<'a>,
offset: usize,
) -> Result<&'a [T], ReadError> {
let len = data
.len()
.checked_sub(offset)
.ok_or(ReadError::OutOfBounds)?;
let end = offset + len / T::RAW_BYTE_LEN * T::RAW_BYTE_LEN;
data.read_array(offset..end)
}
#[cfg(test)]
mod tests {
use font_test_data::bebuffer::BeBuffer;
use super::*;
#[test]
fn lookup_format_0() {
#[rustfmt::skip]
let words = [
0_u16, // format
0, 2, 4, 6, 8, 10, 12, 14, 16, // maps all glyphs to gid * 2
];
let mut buf = BeBuffer::new();
buf = buf.extend(words);
let lookup = LookupU16::read(buf.data().into()).unwrap();
for gid in 0..=8 {
assert_eq!(lookup.value(gid).unwrap(), gid * 2);
}
assert!(lookup.value(9).is_err());
}
// Taken from example 2 at https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html
#[test]
fn lookup_format_2() {
#[rustfmt::skip]
let words = [
2_u16, // format
6, // unit size (6 bytes)
3, // number of units
12, // search range
1, // entry selector
6, // range shift
22, 20, 4, // First segment, mapping glyphs 20 through 22 to class 4
24, 23, 5, // Second segment, mapping glyph 23 and 24 to class 5
28, 25, 6, // Third segment, mapping glyphs 25 through 28 to class 6
];
let mut buf = BeBuffer::new();
buf = buf.extend(words);
let lookup = LookupU16::read(buf.data().into()).unwrap();
let expected = [(20..=22, 4), (23..=24, 5), (25..=28, 6)];
for (range, class) in expected {
for gid in range {
assert_eq!(lookup.value(gid).unwrap(), class);
}
}
for fail in [0, 10, 19, 29, 0xFFFF] {
assert!(lookup.value(fail).is_err());
}
}
#[test]
fn lookup_format_4() {
#[rustfmt::skip]
let words = [
4_u16, // format
6, // unit size (6 bytes)
3, // number of units
12, // search range
1, // entry selector
6, // range shift
22, 20, 30, // First segment, mapping glyphs 20 through 22 to mapped data at offset 30
24, 23, 36, // Second segment, mapping glyph 23 and 24 to mapped data at offset 36
28, 25, 40, // Third segment, mapping glyphs 25 through 28 to mapped data at offset 40
// mapped data
3, 2, 1,
100, 150,
8, 6, 7, 9
];
let mut buf = BeBuffer::new();
buf = buf.extend(words);
let lookup = LookupU16::read(buf.data().into()).unwrap();
let expected = [
(20, 3),
(21, 2),
(22, 1),
(23, 100),
(24, 150),
(25, 8),
(26, 6),
(27, 7),
(28, 9),
];
for (in_glyph, out_glyph) in expected {
assert_eq!(lookup.value(in_glyph).unwrap(), out_glyph);
}
for fail in [0, 10, 19, 29, 0xFFFF] {
assert!(lookup.value(fail).is_err());
}
}
// Taken from example 1 at https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html
#[test]
fn lookup_format_6() {
#[rustfmt::skip]
let words = [
6_u16, // format
4, // unit size (4 bytes)
4, // number of units
16, // search range
2, // entry selector
0, // range shift
50, 600, // Input glyph 50 maps to glyph 600
51, 601, // Input glyph 51 maps to glyph 601
201, 602, // Input glyph 201 maps to glyph 602
202, 900, // Input glyph 202 maps to glyph 900
];
let mut buf = BeBuffer::new();
buf = buf.extend(words);
let lookup = LookupU16::read(buf.data().into()).unwrap();
let expected = [(50, 600), (51, 601), (201, 602), (202, 900)];
for (in_glyph, out_glyph) in expected {
assert_eq!(lookup.value(in_glyph).unwrap(), out_glyph);
}
for fail in [0, 10, 49, 52, 203, 0xFFFF] {
assert!(lookup.value(fail).is_err());
}
}
#[test]
fn lookup_format_8() {
#[rustfmt::skip]
let words = [
8_u16, // format
201, // first glyph
7, // glyph count
3, 8, 2, 9, 1, 200, 60, // glyphs 201..209 mapped to these values
];
let mut buf = BeBuffer::new();
buf = buf.extend(words);
let lookup = LookupU16::read(buf.data().into()).unwrap();
let expected = &words[3..];
for (gid, expected) in (201..209).zip(expected) {
assert_eq!(lookup.value(gid).unwrap(), *expected);
}
for fail in [0, 10, 200, 210, 0xFFFF] {
assert!(lookup.value(fail).is_err());
}
}
#[test]
fn lookup_format_10() {
#[rustfmt::skip]
let words = [
10_u16, // format
4, // unit size, use 4 byte values
201, // first glyph
7, // glyph count
];
// glyphs 201..209 mapped to these values
let mapped = [3_u32, 8, 2902384, 9, 1, u32::MAX, 60];
let mut buf = BeBuffer::new();
buf = buf.extend(words).extend(mapped);
let lookup = LookupU32::read(buf.data().into()).unwrap();
for (gid, expected) in (201..209).zip(mapped) {
assert_eq!(lookup.value(gid).unwrap(), expected);
}
for fail in [0, 10, 200, 210, 0xFFFF] {
assert!(lookup.value(fail).is_err());
}
}
#[test]
fn extended_state_table() {
#[rustfmt::skip]
let header = [
6_u32, // number of classes
20, // byte offset to class table
56, // byte offset to state array
92, // byte offset to entry array
0, // padding
];
#[rustfmt::skip]
let class_table = [
6_u16, // format
4, // unit size (4 bytes)
5, // number of units
16, // search range
2, // entry selector
0, // range shift
50, 4, // Input glyph 50 maps to class 4
51, 4, // Input glyph 51 maps to class 4
80, 5, // Input glyph 80 maps to class 5
201, 4, // Input glyph 201 maps to class 4
202, 4, // Input glyph 202 maps to class 4
!0, !0
];
#[rustfmt::skip]
let state_array: [u16; 18] = [
0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 2, 1,
];
#[rustfmt::skip]
let entry_table: [u16; 12] = [
0, 0, u16::MAX, u16::MAX,
2, 0, u16::MAX, u16::MAX,
0, 0, u16::MAX, 0,
];
let buf = BeBuffer::new()
.extend(header)
.extend(class_table)
.extend(state_array)
.extend(entry_table);
let table = ExtendedStateTable::<ContextualData>::read(buf.data().into()).unwrap();
// check class lookups
let [class_50, class_80, class_201] =
[50, 80, 201].map(|gid| table.class(GlyphId::new(gid)).unwrap());
assert_eq!(class_50, 4);
assert_eq!(class_80, 5);
assert_eq!(class_201, 4);
// initial state
let entry = table.entry(0, 4).unwrap();
assert_eq!(entry.new_state, 0);
assert_eq!(entry.payload.current_index, !0);
// entry (state 0, class 5) should transition to state 2
let entry = table.entry(0, 5).unwrap();
assert_eq!(entry.new_state, 2);
// from state 2, we transition back to state 0 when class is not 5
// this also enables an action (payload.current_index != -1)
let entry = table.entry(2, 4).unwrap();
assert_eq!(entry.new_state, 0);
assert_eq!(entry.payload.current_index, 0);
}
#[derive(Copy, Clone, Debug, bytemuck::AnyBitPattern)]
#[repr(C, packed)]
struct ContextualData {
_mark_index: BigEndian<u16>,
current_index: BigEndian<u16>,
}
impl FixedSize for ContextualData {
const RAW_BYTE_LEN: usize = 4;
}
// Take from example at <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html>
// with class table trimmed to 4 glyphs
#[test]
fn state_table() {
#[rustfmt::skip]
let header = [
7_u16, // number of classes
10, // byte offset to class table
18, // byte offset to state array
40, // byte offset to entry array
64, // byte offset to value array (unused here)
];
#[rustfmt::skip]
let class_table = [
3_u16, // first glyph
4, // number of glyphs
];
let classes = [1u8, 2, 3, 4];
#[rustfmt::skip]
let state_array: [u8; 22] = [
2, 0, 0, 2, 1, 0, 0,
2, 0, 0, 2, 1, 0, 0,
2, 3, 3, 2, 3, 4, 5,
0, // padding
];
#[rustfmt::skip]
let entry_table: [u16; 10] = [
// The first column are offsets from the beginning of the state
// table to some position in the state array
18, 0x8112,
32, 0x8112,
18, 0x0000,
32, 0x8114,
18, 0x8116,
];
let buf = BeBuffer::new()
.extend(header)
.extend(class_table)
.extend(classes)
.extend(state_array)
.extend(entry_table);
let table = StateTable::read(buf.data().into()).unwrap();
// check class lookups
for i in 0..4u8 {
assert_eq!(table.class(GlyphId16::from(i as u16 + 3)).unwrap(), i + 1);
}
// (state, class) -> (new_state, flags)
let cases = [
((0, 4), (2, 0x8112)),
((2, 1), (2, 0x8114)),
((1, 3), (0, 0x0000)),
((2, 5), (0, 0x8116)),
];
for ((state, class), (new_state, flags)) in cases {
let entry = table.entry(state, class).unwrap();
assert_eq!(
entry.new_state, new_state,
"state {state}, class {class} should map to new state {new_state} (got {})",
entry.new_state
);
assert_eq!(
entry.flags, flags,
"state {state}, class {class} should map to flags 0x{flags:X} (got 0x{:X})",
entry.flags
);
}
}
}
+67
View File
@@ -0,0 +1,67 @@
//! The [anchor point](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html) table.
use super::aat::LookupU16;
include!("../../generated/generated_ankr.rs");
impl<'a> Ankr<'a> {
/// Returns the set of anchor points for the given glyph.
pub fn anchor_points(&self, glyph_id: GlyphId) -> Result<&'a [AnchorPoint], ReadError> {
let glyph_id: GlyphId16 = glyph_id.try_into().map_err(|_| ReadError::OutOfBounds)?;
let entry_offset = self.lookup_table()?.value(glyph_id.to_u16())?;
let full_offset = (self.glyph_data_table_offset() as usize)
.checked_add(entry_offset as usize)
.ok_or(ReadError::OutOfBounds)?;
let data = self
.offset_data()
.split_off(full_offset)
.ok_or(ReadError::OutOfBounds)?;
Ok(GlyphDataEntry::read(data)?.anchor_points())
}
}
#[cfg(test)]
mod tests {
use font_test_data::bebuffer::BeBuffer;
use super::*;
#[test]
fn anchor_points() {
let mut buf = BeBuffer::new();
// lookup table (glyph_id -> offset)
#[rustfmt::skip]
let lookup = [
0_u16, // format
0, 8, 24, 32 // offsets to anchor points
];
let lookup_size = lookup.len() as u32 * 2;
// header
buf = buf.extend([0u32, 0x0000000C, 12 + lookup_size]);
buf = buf.extend(lookup);
// glyph entry data
#[rustfmt::skip]
let expected_anchor_points: [&[(i16, i16)]; 4] = [
&[(-20, 20)],
&[(42, -10), (-200, 300), (i16::MIN, i16::MAX)],
&[(0, 4)],
&[(0, 0), (64, -64)],
];
for entry in &expected_anchor_points {
buf = buf
.push(entry.len() as u32)
.extend(entry.iter().flat_map(|x| [x.0, x.1]));
}
let ankr = Ankr::read(buf.data().into()).unwrap();
let anchor_points = (0..4)
.map(|gid| {
let points = ankr.anchor_points(GlyphId::new(gid)).unwrap();
points
.iter()
.map(|point| (point.x(), point.y()))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
assert!(expected_anchor_points.iter().eq(anchor_points.iter()));
}
}
+171
View File
@@ -0,0 +1,171 @@
//! The [Axis Variations](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
use super::variations::{DeltaSetIndexMap, ItemVariationStore};
include!("../../generated/generated_avar.rs");
impl SegmentMaps<'_> {
/// Applies the piecewise linear mapping to the specified coordinate.
pub fn apply(&self, coord: Fixed) -> Fixed {
let mut prev = AxisValueMap {
from_coordinate: Default::default(),
to_coordinate: Default::default(),
};
for (i, axis_value_map) in self.axis_value_maps().iter().enumerate() {
use core::cmp::Ordering::*;
let from = axis_value_map.from_coordinate().to_fixed();
match from.cmp(&coord) {
Equal => return axis_value_map.to_coordinate().to_fixed(),
Greater => {
if i == 0 {
return coord;
}
let to = axis_value_map.to_coordinate().to_fixed();
let prev_from = prev.from_coordinate().to_fixed();
let prev_to = prev.to_coordinate().to_fixed();
return prev_to + (to - prev_to).mul_div(coord - prev_from, from - prev_from);
}
_ => {}
}
prev = *axis_value_map;
}
coord
}
}
impl VarSize for SegmentMaps<'_> {
type Size = u16;
fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
Some(
data.read_at::<u16>(pos).ok()? as usize * AxisValueMap::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN,
)
}
}
impl<'a> FontRead<'a> for SegmentMaps<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let mut cursor = data.cursor();
let position_map_count: BigEndian<u16> = cursor.read_be()?;
let axis_value_maps = cursor.read_array(position_map_count.get() as _)?;
Ok(SegmentMaps {
position_map_count,
axis_value_maps,
})
}
}
#[cfg(test)]
mod tests {
use font_test_data::bebuffer::BeBuffer;
use super::*;
use crate::{FontRef, TableProvider};
fn value_map(from: f32, to: f32) -> [F2Dot14; 2] {
[F2Dot14::from_f32(from), F2Dot14::from_f32(to)]
}
// for the purpose of testing it is easier for us to use an array
// instead of a concrete type, since we can write that into BeBuffer
impl PartialEq<[F2Dot14; 2]> for AxisValueMap {
fn eq(&self, other: &[F2Dot14; 2]) -> bool {
self.from_coordinate == other[0] && self.to_coordinate == other[1]
}
}
#[test]
fn segment_maps() {
let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
let avar = font.avar().unwrap();
assert_eq!(avar.axis_count(), 1);
let expected_segment_maps = &[vec![
value_map(-1.0, -1.0),
value_map(-0.6667, -0.5),
value_map(-0.3333, -0.25),
value_map(0.0, 0.0),
value_map(0.2, 0.3674),
value_map(0.4, 0.52246),
value_map(0.6, 0.67755),
value_map(0.8, 0.83875),
value_map(1.0, 1.0),
]];
let segment_maps = avar
.axis_segment_maps()
.iter()
.map(|segment_map| segment_map.unwrap().axis_value_maps().to_owned())
.collect::<Vec<_>>();
assert_eq!(segment_maps, expected_segment_maps);
}
#[test]
fn segment_maps_multi_axis() {
let segment_one_maps = [
value_map(-1.0, -1.0),
value_map(-0.6667, -0.5),
value_map(-0.3333, -0.25),
];
let segment_two_maps = [value_map(0.8, 0.83875), value_map(1.0, 1.0)];
let data = BeBuffer::new()
.push(MajorMinor::VERSION_1_0)
.push(0u16) // reserved
.push(2u16) // axis count
// segment map one
.push(3u16) // position count
.extend(segment_one_maps[0])
.extend(segment_one_maps[1])
.extend(segment_one_maps[2])
// segment map two
.push(2u16) // position count
.extend(segment_two_maps[0])
.extend(segment_two_maps[1]);
let avar = super::Avar::read(data.data().into()).unwrap();
assert_eq!(avar.axis_segment_maps().iter().count(), 2);
assert_eq!(
avar.axis_segment_maps()
.get(0)
.unwrap()
.unwrap()
.axis_value_maps,
segment_one_maps,
);
assert_eq!(
avar.axis_segment_maps()
.get(1)
.unwrap()
.unwrap()
.axis_value_maps,
segment_two_maps,
);
}
#[test]
fn piecewise_linear() {
let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
let avar = font.avar().unwrap();
let segment_map = avar.axis_segment_maps().get(0).unwrap().unwrap();
let coords = [-1.0, -0.5, 0.0, 0.5, 1.0];
let expected_result = [-1.0, -0.375, 0.0, 0.600006103515625, 1.0];
assert_eq!(
&expected_result[..],
&coords
.iter()
.map(|coord| segment_map.apply(Fixed::from_f64(*coord)).to_f64())
.collect::<Vec<_>>()
);
}
#[test]
fn avar2() {
let font = FontRef::new(font_test_data::AVAR2_CHECKER).unwrap();
let avar = font.avar().unwrap();
assert_eq!(avar.version(), MajorMinor::VERSION_2_0);
assert!(avar.axis_index_map_offset().is_some());
assert!(avar.var_store_offset().is_some());
assert!(avar.var_store().is_some());
}
}
+55
View File
@@ -0,0 +1,55 @@
//! The [BASE](https://learn.microsoft.com/en-us/typography/opentype/spec/base) table
use super::{layout::DeviceOrVariationIndex, variations::ItemVariationStore};
include!("../../generated/generated_base.rs");
#[cfg(test)]
mod tests {
use font_test_data::bebuffer::BeBuffer;
use font_types::MajorMinor;
use super::*;
#[test]
/// https://learn.microsoft.com/en-us/typography/opentype/spec/base#base-table-examples
fn example_1() {
let data = BeBuffer::new()
.push(MajorMinor::VERSION_1_0)
.push(8u16) // horizaxis offset
.push(0x10c_u16) // verticalaxis
// axis table
.push(4u16) //basetaglist
.push(0x12_u16) // basescript list
// base tag list
.push(3u16) // count
.push(Tag::new(b"hang"))
.push(Tag::new(b"ideo"))
.push(Tag::new(b"romn"))
// basescriptlist
.push(4u16) // basescript count
.push(Tag::new(b"cyrl"))
.push(0x1a_u16)
.push(Tag::new(b"devn"))
.push(0x60_u16)
.push(Tag::new(b"hani"))
.push(0x8a_u16)
.push(Tag::new(b"latn"))
.push(0xb4_u16);
let base = Base::read(data.data().into()).unwrap();
assert_eq!(base.version(), MajorMinor::VERSION_1_0);
let horiz = base.horiz_axis().unwrap().unwrap();
let base_tag = horiz.base_tag_list().unwrap().unwrap();
assert_eq!(
base_tag.baseline_tags(),
&[Tag::new(b"hang"), Tag::new(b"ideo"), Tag::new(b"romn")]
);
assert_eq!(base_tag.min_byte_range().end, 14);
let base_script = horiz.base_script_list().unwrap();
assert_eq!(
base_script.base_script_records()[3].base_script_tag(),
Tag::new(b"latn")
);
}
}
+463
View File
@@ -0,0 +1,463 @@
//! Common bitmap (EBLC/EBDT/CBLC/CBDT) types.
include!("../../generated/generated_bitmap.rs");
impl BitmapSize {
/// Returns the bitmap location information for the given glyph.
///
/// The `offset_data` parameter is provided by the `offset_data()` method
/// of the parent `Eblc` or `Cblc` table.
///
/// The resulting [`BitmapLocation`] value is used by the `data()` method
/// in the associated `Ebdt` or `Cbdt` table to extract the bitmap data.
pub fn location(
&self,
offset_data: FontData,
glyph_id: GlyphId,
) -> Result<BitmapLocation, ReadError> {
if !(self.start_glyph_index()..=self.end_glyph_index()).contains(&glyph_id) {
return Err(ReadError::OutOfBounds);
}
let subtable_list = self.index_subtable_list(offset_data)?;
let mut location = BitmapLocation {
bit_depth: self.bit_depth,
..BitmapLocation::default()
};
for record in subtable_list.index_subtable_records() {
let subtable = record.index_subtable(subtable_list.offset_data())?;
if !(record.first_glyph_index()..=record.last_glyph_index()).contains(&glyph_id) {
continue;
}
// glyph index relative to the first glyph in the subtable
let glyph_ix =
glyph_id.to_u32() as usize - record.first_glyph_index().to_u32() as usize;
match &subtable {
IndexSubtable::Format1(st) => {
location.format = st.image_format();
let start = st.image_data_offset() as usize
+ st.sbit_offsets()
.get(glyph_ix)
.ok_or(ReadError::OutOfBounds)?
.get() as usize;
let end = st.image_data_offset() as usize
+ st.sbit_offsets()
.get(glyph_ix + 1)
.ok_or(ReadError::OutOfBounds)?
.get() as usize;
location.data_offset = start;
if end < start {
return Err(ReadError::OutOfBounds);
}
location.data_size = end - start;
}
IndexSubtable::Format2(st) => {
location.format = st.image_format();
let data_size = st.image_size() as usize;
location.data_size = data_size;
location.data_offset = st.image_data_offset() as usize + glyph_ix * data_size;
location.metrics = Some(st.big_metrics()[0]);
}
IndexSubtable::Format3(st) => {
location.format = st.image_format();
let start = st.image_data_offset() as usize
+ st.sbit_offsets()
.get(glyph_ix)
.ok_or(ReadError::OutOfBounds)?
.get() as usize;
let end = st.image_data_offset() as usize
+ st.sbit_offsets()
.get(glyph_ix + 1)
.ok_or(ReadError::OutOfBounds)?
.get() as usize;
location.data_offset = start;
if end < start {
return Err(ReadError::OutOfBounds);
}
location.data_size = end - start;
}
IndexSubtable::Format4(st) => {
location.format = st.image_format();
let array = st.glyph_array();
let array_ix = match array
.binary_search_by(|x| x.glyph_id().to_u32().cmp(&glyph_id.to_u32()))
{
Ok(ix) => ix,
_ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
};
let start = array[array_ix].sbit_offset() as usize;
let end = array
.get(array_ix + 1)
.ok_or(ReadError::OutOfBounds)?
.sbit_offset() as usize;
location.data_offset = start;
if end < start {
return Err(ReadError::OutOfBounds);
}
location.data_size = end - start;
}
IndexSubtable::Format5(st) => {
location.format = st.image_format();
let array = st.glyph_array();
let array_ix = match array
.binary_search_by(|gid| gid.get().to_u32().cmp(&glyph_id.to_u32()))
{
Ok(ix) => ix,
_ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
};
let data_size = st.image_size() as usize;
location.data_size = data_size;
location.data_offset = st.image_data_offset() as usize + array_ix * data_size;
location.metrics = Some(st.big_metrics()[0]);
}
}
return Ok(location);
}
Err(ReadError::OutOfBounds)
}
/// Returns the [IndexSubtableList] associated with this size.
///
/// The `offset_data` parameter is provided by the `offset_data()` method
/// of the parent `Eblc` or `Cblc` table.
pub fn index_subtable_list<'a>(
&self,
offset_data: FontData<'a>,
) -> Result<IndexSubtableList<'a>, ReadError> {
let start = self.index_subtable_list_offset() as usize;
let end = start
.checked_add(self.index_subtable_list_size() as usize)
.ok_or(ReadError::OutOfBounds)?;
let data = offset_data
.slice(start..end)
.ok_or(ReadError::OutOfBounds)?;
IndexSubtableList::read(data, self.number_of_index_subtables())
}
}
#[derive(Clone, Default)]
pub struct BitmapLocation {
/// Format of EBDT/CBDT image data.
pub format: u16,
/// Offset in bytes from the start of the EBDT/CBDT table.
pub data_offset: usize,
/// Size of the image data in bytes.
pub data_size: usize,
/// Bit depth from the associated size. Required for computing image data
/// size when unspecified.
pub bit_depth: u8,
/// Full metrics, if present in the EBLC/CBLC table.
pub metrics: Option<BigGlyphMetrics>,
}
impl BitmapLocation {
/// Returns true if the location references an empty bitmap glyph such as
/// a space.
pub fn is_empty(&self) -> bool {
self.data_size == 0
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BitmapDataFormat {
/// The full bitmap is tightly packed according to the bit depth.
BitAligned,
/// Each row of the data is aligned to a byte boundary.
ByteAligned,
Png,
}
#[derive(Clone)]
pub enum BitmapMetrics {
Small(SmallGlyphMetrics),
Big(BigGlyphMetrics),
}
#[derive(Clone)]
pub struct BitmapData<'a> {
pub metrics: BitmapMetrics,
pub content: BitmapContent<'a>,
}
#[derive(Clone)]
pub enum BitmapContent<'a> {
Data(BitmapDataFormat, &'a [u8]),
Composite(&'a [BdtComponent]),
}
pub(crate) fn bitmap_data<'a>(
offset_data: FontData<'a>,
location: &BitmapLocation,
is_color: bool,
) -> Result<BitmapData<'a>, ReadError> {
let mut image_data = offset_data
.slice(location.data_offset..location.data_offset + location.data_size)
.ok_or(ReadError::OutOfBounds)?
.cursor();
match location.format {
// Small metrics, byte-aligned data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-1-small-metrics-byte-aligned-data>
1 => {
let metrics = read_small_metrics(&mut image_data)?;
// The data for each row is padded to a byte boundary
let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
let height = metrics.height as usize;
let data = image_data.read_array::<u8>(pitch * height)?;
Ok(BitmapData {
metrics: BitmapMetrics::Small(metrics),
content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
})
}
// Small metrics, bit-aligned data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-2-small-metrics-bit-aligned-data>
2 => {
let metrics = read_small_metrics(&mut image_data)?;
let width = metrics.width as usize * location.bit_depth as usize;
let height = metrics.height as usize;
// The data is tightly packed
let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
Ok(BitmapData {
metrics: BitmapMetrics::Small(metrics),
content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
})
}
// Format 3 is obsolete
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-3-obsolete>
// Format 4 is not supported
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-4-not-supported-metrics-in-eblc-compressed-data>
// ---
// Metrics in EBLC/CBLC, bit-aligned image data only
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-5-metrics-in-eblc-bit-aligned-image-data-only>
5 => {
let metrics = location.metrics.ok_or(ReadError::MalformedData(
"expected metrics from location table",
))?;
let width = metrics.width as usize * location.bit_depth as usize;
let height = metrics.height as usize;
// The data is tightly packed
let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
})
}
// Big metrics, byte-aligned data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-6-big-metrics-byte-aligned-data>
6 => {
let metrics = read_big_metrics(&mut image_data)?;
// The data for each row is padded to a byte boundary
let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
let height = metrics.height as usize;
let data = image_data.read_array::<u8>(pitch * height)?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
})
}
// Big metrics, bit-aligned data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format7-big-metrics-bit-aligned-data>
7 => {
let metrics = read_big_metrics(&mut image_data)?;
let width = metrics.width as usize * location.bit_depth as usize;
let height = metrics.height as usize;
// The data is tightly packed
let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
})
}
// Small metrics, component data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-8-small-metrics-component-data>
8 => {
let metrics = read_small_metrics(&mut image_data)?;
let _pad = image_data.read::<u8>()?;
let count = image_data.read::<u16>()? as usize;
let components = image_data.read_array::<BdtComponent>(count)?;
Ok(BitmapData {
metrics: BitmapMetrics::Small(metrics),
content: BitmapContent::Composite(components),
})
}
// Big metrics, component data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-9-big-metrics-component-data>
9 => {
let metrics = read_big_metrics(&mut image_data)?;
let count = image_data.read::<u16>()? as usize;
let components = image_data.read_array::<BdtComponent>(count)?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Composite(components),
})
}
// Small metrics, PNG image data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-17-small-metrics-png-image-data>
17 if is_color => {
let metrics = read_small_metrics(&mut image_data)?;
let data_len = image_data.read::<u32>()? as usize;
let data = image_data.read_array::<u8>(data_len)?;
Ok(BitmapData {
metrics: BitmapMetrics::Small(metrics),
content: BitmapContent::Data(BitmapDataFormat::Png, data),
})
}
// Big metrics, PNG image data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-18-big-metrics-png-image-data>
18 if is_color => {
let metrics = read_big_metrics(&mut image_data)?;
let data_len = image_data.read::<u32>()? as usize;
let data = image_data.read_array::<u8>(data_len)?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Data(BitmapDataFormat::Png, data),
})
}
// Metrics in CBLC table, PNG image data
// <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-19-metrics-in-cblc-table-png-image-data>
19 if is_color => {
let metrics = location.metrics.ok_or(ReadError::MalformedData(
"expected metrics from location table",
))?;
let data_len = image_data.read::<u32>()? as usize;
let data = image_data.read_array::<u8>(data_len)?;
Ok(BitmapData {
metrics: BitmapMetrics::Big(metrics),
content: BitmapContent::Data(BitmapDataFormat::Png, data),
})
}
_ => Err(ReadError::MalformedData("unexpected bitmap data format")),
}
}
fn read_small_metrics(cursor: &mut Cursor) -> Result<SmallGlyphMetrics, ReadError> {
Ok(cursor.read_array::<SmallGlyphMetrics>(1)?[0])
}
fn read_big_metrics(cursor: &mut Cursor) -> Result<BigGlyphMetrics, ReadError> {
Ok(cursor.read_array::<BigGlyphMetrics>(1)?[0])
}
#[cfg(feature = "experimental_traverse")]
impl SbitLineMetrics {
pub(crate) fn traversal_type<'a>(&self, data: FontData<'a>) -> FieldType<'a> {
FieldType::Record(self.traverse(data))
}
}
/// [IndexSubtables](https://learn.microsoft.com/en-us/typography/opentype/spec/eblc#indexsubtables) format type.
#[derive(Clone)]
pub enum IndexSubtable<'a> {
Format1(IndexSubtable1<'a>),
Format2(IndexSubtable2<'a>),
Format3(IndexSubtable3<'a>),
Format4(IndexSubtable4<'a>),
Format5(IndexSubtable5<'a>),
}
impl<'a> IndexSubtable<'a> {
///Return the `FontData` used to resolve offsets for this table.
pub fn offset_data(&self) -> FontData<'a> {
match self {
Self::Format1(item) => item.offset_data(),
Self::Format2(item) => item.offset_data(),
Self::Format3(item) => item.offset_data(),
Self::Format4(item) => item.offset_data(),
Self::Format5(item) => item.offset_data(),
}
}
/// Format of this IndexSubTable.
pub fn index_format(&self) -> u16 {
match self {
Self::Format1(item) => item.index_format(),
Self::Format2(item) => item.index_format(),
Self::Format3(item) => item.index_format(),
Self::Format4(item) => item.index_format(),
Self::Format5(item) => item.index_format(),
}
}
/// Format of EBDT image data.
pub fn image_format(&self) -> u16 {
match self {
Self::Format1(item) => item.image_format(),
Self::Format2(item) => item.image_format(),
Self::Format3(item) => item.image_format(),
Self::Format4(item) => item.image_format(),
Self::Format5(item) => item.image_format(),
}
}
/// Offset to image data in EBDT table.
pub fn image_data_offset(&self) -> u32 {
match self {
Self::Format1(item) => item.image_data_offset(),
Self::Format2(item) => item.image_data_offset(),
Self::Format3(item) => item.image_data_offset(),
Self::Format4(item) => item.image_data_offset(),
Self::Format5(item) => item.image_data_offset(),
}
}
}
impl ReadArgs for IndexSubtable<'_> {
type Args = (GlyphId16, GlyphId16);
}
impl<'a> FontReadWithArgs<'a> for IndexSubtable<'a> {
fn read_with_args(data: FontData<'a>, args: &Self::Args) -> Result<Self, ReadError> {
let format: u16 = data.read_at(0usize)?;
match format {
IndexSubtable1Marker::FORMAT => {
Ok(Self::Format1(FontReadWithArgs::read_with_args(data, args)?))
}
IndexSubtable2Marker::FORMAT => Ok(Self::Format2(FontRead::read(data)?)),
IndexSubtable3Marker::FORMAT => {
Ok(Self::Format3(FontReadWithArgs::read_with_args(data, args)?))
}
IndexSubtable4Marker::FORMAT => Ok(Self::Format4(FontRead::read(data)?)),
IndexSubtable5Marker::FORMAT => Ok(Self::Format5(FontRead::read(data)?)),
other => Err(ReadError::InvalidFormat(other.into())),
}
}
}
impl MinByteRange for IndexSubtable<'_> {
fn min_byte_range(&self) -> Range<usize> {
match self {
Self::Format1(item) => item.min_byte_range(),
Self::Format2(item) => item.min_byte_range(),
Self::Format3(item) => item.min_byte_range(),
Self::Format4(item) => item.min_byte_range(),
Self::Format5(item) => item.min_byte_range(),
}
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> IndexSubtable<'a> {
fn dyn_inner<'b>(&'b self) -> &'b dyn SomeTable<'a> {
match self {
Self::Format1(table) => table,
Self::Format2(table) => table,
Self::Format3(table) => table,
Self::Format4(table) => table,
Self::Format5(table) => table,
}
}
}
#[cfg(feature = "experimental_traverse")]
impl std::fmt::Debug for IndexSubtable<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.dyn_inner().fmt(f)
}
}
#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for IndexSubtable<'a> {
fn type_name(&self) -> &str {
self.dyn_inner().type_name()
}
fn get_field(&self, idx: usize) -> Option<Field<'a>> {
self.dyn_inner().get_field(idx)
}
}
+87
View File
@@ -0,0 +1,87 @@
//! The [CBDT (Color Bitmap Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/cbdt) table
use super::bitmap::{BitmapData, BitmapLocation};
include!("../../generated/generated_cbdt.rs");
impl<'a> Cbdt<'a> {
pub fn data(&self, location: &BitmapLocation) -> Result<BitmapData<'a>, ReadError> {
super::bitmap::bitmap_data(self.offset_data(), location, true)
}
}
#[cfg(test)]
mod tests {
use super::super::bitmap::{BitmapDataFormat, SmallGlyphMetrics};
use crate::{
types::{GlyphId, GlyphId16},
FontRef, TableProvider,
};
#[test]
fn read_cblc_1_cbdt_17() {
let font = FontRef::new(font_test_data::EMBEDDED_BITMAPS).unwrap();
let cblc = font.cblc().unwrap();
let cbdt = font.cbdt().unwrap();
let size = &cblc.bitmap_sizes()[0];
// Metrics for size at index 0
assert!(
size.hori.ascender() == 101
&& size.hori.descender() == -27
&& size.hori.width_max() == 136
&& size.vert.ascender() == 101
&& size.vert.descender() == -27
&& size.vert.width_max() == 136
&& size.start_glyph_index() == GlyphId16::new(4)
&& size.end_glyph_index() == GlyphId16::new(4)
&& size.ppem_x() == 109
&& size.ppem_y() == 109
&& size.bit_depth() == 32
);
let expected: &[(GlyphId, &[u8], SmallGlyphMetrics)] = &[(
GlyphId::new(4),
&[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
SmallGlyphMetrics {
height: 128,
width: 136,
bearing_x: 0.into(),
bearing_y: 101.into(),
advance: 136,
},
)];
for (gid, data, metrics) in expected {
let location = size.location(cblc.offset_data(), *gid).unwrap();
assert_eq!(location.format, 17);
let bitmap_data = cbdt.data(&location).unwrap();
let (img_fmt, img_data) = bitmap_data.content.extract_data();
assert_eq!(img_fmt, BitmapDataFormat::Png);
assert_eq!(img_data, *data);
assert_eq!(bitmap_data.extract_small_metrics(), metrics);
}
}
#[test]
fn sparse_glyph_ids() {
let font = FontRef::new(font_test_data::CBDT).unwrap();
let cblc = font.cblc().unwrap();
let cbdt = font.cbdt().unwrap();
let size = &cblc.bitmap_sizes()[0];
// this font has a sparse set with gid 1 missing
for gid in 0..=3 {
let location = size
.location(cblc.offset_data(), GlyphId::new(gid))
.unwrap();
if gid == 1 {
assert!(
cbdt.data(&location).is_err(),
"expected bitmap for {gid} to be empty"
);
} else {
assert!(
cbdt.data(&location).is_ok(),
"expected bitmap for {gid} to be present"
);
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
//! The [CBLC (Color Bitmap Location)](https://docs.microsoft.com/en-us/typography/opentype/spec/cblc) table
use super::bitmap::*;
include!("../../generated/generated_cblc.rs");
+225
View File
@@ -0,0 +1,225 @@
//! The [CFF](https://learn.microsoft.com/en-us/typography/opentype/spec/cff) table
include!("../../generated/generated_cff.rs");
use super::postscript::{dict, Charset, Error, Index1, Latin1String, StringId};
/// The [Compact Font Format](https://learn.microsoft.com/en-us/typography/opentype/spec/cff) table.
#[derive(Clone)]
pub struct Cff<'a> {
header: CffHeader<'a>,
names: Index1<'a>,
top_dicts: Index1<'a>,
strings: Index1<'a>,
global_subrs: Index1<'a>,
}
impl<'a> Cff<'a> {
pub fn offset_data(&self) -> FontData<'a> {
self.header.offset_data()
}
pub fn header(&self) -> CffHeader<'a> {
self.header.clone()
}
/// Returns the name index.
///
/// This contains the PostScript names of all fonts in the font set.
///
/// See "Name INDEX" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=13>
pub fn names(&self) -> Index1<'a> {
self.names.clone()
}
/// Returns the PostScript name for the font in the font set at the
/// given index.
pub fn name(&self, index: usize) -> Option<Latin1String<'a>> {
Some(Latin1String::new(self.names.get(index).ok()?))
}
/// Returns the top dict index.
///
/// This contains the top-level DICTs of all fonts in the font set. The
/// objects here correspond to those in the name index.
///
/// See "Top DICT INDEX" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=14>
pub fn top_dicts(&self) -> Index1<'a> {
self.top_dicts.clone()
}
/// Returns the string index.
///
/// This contains all of the strings used by fonts within the font set.
/// They are referenced by string identifiers represented by the
/// [`StringId`] type.
///
/// See "String INDEX" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=17>
pub fn strings(&self) -> Index1<'a> {
self.strings.clone()
}
/// Returns the associated string for the given identifier.
///
/// If the identifier does not represent a standard string, the result is
/// looked up in the string index.
pub fn string(&self, id: StringId) -> Option<Latin1String<'a>> {
match id.standard_string() {
Ok(name) => Some(name),
Err(ix) => self.strings.get(ix).ok().map(Latin1String::new),
}
}
/// Returns the global subroutine index.
///
/// This contains sub-programs that are referenced by one or more
/// charstrings in the font set.
///
/// See "Local/Global Subrs INDEXes" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=25>
pub fn global_subrs(&self) -> Index1<'a> {
self.global_subrs.clone()
}
/// Returns the character set associated with the top dict at the given
/// index.
///
/// See "Charsets" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=21>
pub fn charset(&self, top_dict_index: usize) -> Result<Option<Charset<'a>>, Error> {
let top_dict = self.top_dicts().get(top_dict_index)?;
let offset_data = self.offset_data();
let mut charset_offset: Option<usize> = None;
let mut num_glyphs: Option<u32> = None;
for entry in dict::entries(top_dict, None) {
match entry {
Ok(dict::Entry::Charset(offset)) => {
charset_offset = Some(offset);
}
Ok(dict::Entry::CharstringsOffset(offset)) => {
num_glyphs = Some(
Index1::read(
offset_data
.split_off(offset)
.ok_or(ReadError::OutOfBounds)?,
)?
.count() as u32,
);
}
// The ROS operator signifies a CID-keyed font and the charset
// maps to CIDs rather than SIDs which we don't parse for
// glyph names.
// <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=28>
Ok(dict::Entry::Ros { .. }) => {
return Ok(None);
}
_ => {}
}
}
if let Some((charset_offset, num_glyphs)) = charset_offset.zip(num_glyphs) {
Ok(Some(Charset::new(offset_data, charset_offset, num_glyphs)?))
} else {
Ok(None)
}
}
}
impl TopLevelTable for Cff<'_> {
const TAG: Tag = Tag::new(b"CFF ");
}
impl<'a> FontRead<'a> for Cff<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let header = CffHeader::read(data)?;
let mut data = FontData::new(header.trailing_data());
let names = Index1::read(data)?;
data = data
.split_off(names.size_in_bytes()?)
.ok_or(ReadError::OutOfBounds)?;
let top_dicts = Index1::read(data)?;
data = data
.split_off(top_dicts.size_in_bytes()?)
.ok_or(ReadError::OutOfBounds)?;
let strings = Index1::read(data)?;
data = data
.split_off(strings.size_in_bytes()?)
.ok_or(ReadError::OutOfBounds)?;
let global_subrs = Index1::read(data)?;
Ok(Self {
header,
names,
top_dicts,
strings,
global_subrs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{tables::postscript::StringId, FontRef, TableProvider};
#[test]
fn read_noto_serif_display_cff() {
let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
let cff = font.cff().unwrap();
assert_eq!(cff.header().major(), 1);
assert_eq!(cff.header().minor(), 0);
assert_eq!(cff.top_dicts().count(), 1);
assert_eq!(cff.names().count(), 1);
assert_eq!(cff.global_subrs.count(), 17);
let name = Latin1String::new(cff.names().get(0).unwrap());
assert_eq!(name, "NotoSerifDisplay-Regular");
assert_eq!(cff.strings().count(), 5);
// Version
assert_eq!(cff.string(StringId::new(391)).unwrap(), "2.9");
// Notice
assert_eq!(
cff.string(StringId::new(392)).unwrap(),
"Noto is a trademark of Google LLC."
);
// Copyright
assert_eq!(
cff.string(StringId::new(393)).unwrap(),
"Copyright 2022 The Noto Project Authors https:github.comnotofontslatin-greek-cyrillic"
);
// FullName
assert_eq!(
cff.string(StringId::new(394)).unwrap(),
"Noto Serif Display Regular"
);
// FamilyName
assert_eq!(
cff.string(StringId::new(395)).unwrap(),
"Noto Serif Display"
);
}
#[test]
fn glyph_names() {
test_glyph_names(
font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
&[".notdef", "i", "j", "k", "l"],
);
}
#[test]
fn icons_glyph_names() {
test_glyph_names(font_test_data::MATERIAL_ICONS_SUBSET, &[".notdef", "_10k"]);
}
fn test_glyph_names(font_data: &[u8], expected_names: &[&str]) {
let font = FontRef::new(font_data).unwrap();
let cff = font.cff().unwrap();
let charset = cff.charset(0).unwrap().unwrap();
let sid_to_string = |sid| std::str::from_utf8(cff.string(sid).unwrap().bytes()).unwrap();
let names_by_lookup = (0..charset.num_glyphs())
.map(|gid| sid_to_string(charset.string_id(GlyphId::new(gid)).unwrap()))
.collect::<Vec<_>>();
assert_eq!(names_by_lookup, expected_names);
let names_by_iter = charset
.iter()
.map(|(_gid, sid)| sid_to_string(sid))
.collect::<Vec<_>>();
assert_eq!(names_by_iter, expected_names);
}
}
+81
View File
@@ -0,0 +1,81 @@
//! The [CFF2](https://learn.microsoft.com/en-us/typography/opentype/spec/cff2) table
include!("../../generated/generated_cff2.rs");
use super::postscript::Index2;
/// The [Compact Font Format (CFF) version 2](https://learn.microsoft.com/en-us/typography/opentype/spec/cff2) table
#[derive(Clone)]
pub struct Cff2<'a> {
header: Cff2Header<'a>,
global_subrs: Index2<'a>,
}
impl<'a> Cff2<'a> {
pub fn offset_data(&self) -> FontData<'a> {
self.header.offset_data()
}
pub fn header(&self) -> &Cff2Header<'a> {
&self.header
}
/// Returns the raw data containing the top dict.
///
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#7-top-dict-data>
pub fn top_dict_data(&self) -> &'a [u8] {
self.header.top_dict_data()
}
/// Returns the global subroutine index.
///
/// This contains sub-programs that are referenced by one or more
/// charstrings in the font set.
///
/// See "Local/Global Subrs INDEXes" at <https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=25>
pub fn global_subrs(&self) -> Index2<'a> {
self.global_subrs.clone()
}
}
impl TopLevelTable for Cff2<'_> {
const TAG: Tag = Tag::new(b"CFF2");
}
impl<'a> FontRead<'a> for Cff2<'a> {
fn read(data: FontData<'a>) -> Result<Self, ReadError> {
let header = Cff2Header::read(data)?;
let global_subrs = Index2::read(FontData::new(header.trailing_data()))?;
Ok(Self {
header,
global_subrs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{FontData, FontRead, FontRef, TableProvider};
#[test]
fn read_example_cff2_table() {
let cff2 = Cff2::read(FontData::new(font_test_data::cff2::EXAMPLE)).unwrap();
assert_eq!(cff2.header().major_version(), 2);
assert_eq!(cff2.header().minor_version(), 0);
assert_eq!(cff2.header().header_size(), 5);
assert_eq!(cff2.top_dict_data().len(), 7);
assert_eq!(cff2.global_subrs().count(), 0);
}
#[test]
fn read_cantarell() {
let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
let cff2 = font.cff2().unwrap();
assert_eq!(cff2.header().major_version(), 2);
assert_eq!(cff2.header().minor_version(), 0);
assert_eq!(cff2.header().header_size(), 5);
assert_eq!(cff2.top_dict_data().len(), 7);
assert_eq!(cff2.global_subrs().count(), 0);
}
}
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
//! The [COLR](https://docs.microsoft.com/en-us/typography/opentype/spec/colr) table
#[cfg(feature = "std")]
mod closure;
use super::variations::{DeltaSetIndexMap, ItemVariationStore};
include!("../../generated/generated_colr.rs");
/// Unique paint identifier used for detecting cycles in the paint graph.
pub type PaintId = usize;
impl<'a> Colr<'a> {
/// Returns the COLRv0 base glyph for the given glyph identifier.
///
/// The return value is a range of layer indices that can be passed to
/// [`v0_layer`](Self::v0_layer) to retrieve the layer glyph identifiers
/// and palette color indices.
pub fn v0_base_glyph(&self, glyph_id: GlyphId) -> Result<Option<Range<usize>>, ReadError> {
let records = self.base_glyph_records().ok_or(ReadError::NullOffset)??;
let Ok(glyph_id) = glyph_id.try_into() else {
return Ok(None);
};
let record = match records.binary_search_by(|rec| rec.glyph_id().cmp(&glyph_id)) {
Ok(ix) => &records[ix],
_ => return Ok(None),
};
let start = record.first_layer_index() as usize;
let end = start + record.num_layers() as usize;
Ok(Some(start..end))
}
/// Returns the COLRv0 layer at the given index.
///
/// The layer is represented by a tuple containing the glyph identifier of
/// the associated outline and the palette color index.
pub fn v0_layer(&self, index: usize) -> Result<(GlyphId16, u16), ReadError> {
let layers = self.layer_records().ok_or(ReadError::NullOffset)??;
let layer = layers.get(index).ok_or(ReadError::OutOfBounds)?;
Ok((layer.glyph_id(), layer.palette_index()))
}
/// Returns the COLRv1 base glyph for the given glyph identifier.
///
/// The second value in the tuple is a unique identifier for the paint that
/// may be used to detect recursion in the paint graph.
pub fn v1_base_glyph(
&self,
glyph_id: GlyphId,
) -> Result<Option<(Paint<'a>, PaintId)>, ReadError> {
let Ok(glyph_id) = glyph_id.try_into() else {
return Ok(None);
};
let list = self.base_glyph_list().ok_or(ReadError::NullOffset)??;
let records = list.base_glyph_paint_records();
let record = match records.binary_search_by(|rec| rec.glyph_id().cmp(&glyph_id)) {
Ok(ix) => &records[ix],
_ => return Ok(None),
};
let offset_data = list.offset_data();
// Use the address of the paint as an identifier for the recursion
// blacklist.
let id = record.paint_offset().to_u32() as usize + offset_data.as_ref().as_ptr() as usize;
Ok(Some((record.paint(offset_data)?, id)))
}
/// Returns the COLRv1 layer at the given index.
///
/// The second value in the tuple is a unique identifier for the paint that
/// may be used to detect recursion in the paint graph.
pub fn v1_layer(&self, index: usize) -> Result<(Paint<'a>, PaintId), ReadError> {
let list = self.layer_list().ok_or(ReadError::NullOffset)??;
let offset = list
.paint_offsets()
.get(index)
.ok_or(ReadError::OutOfBounds)?
.get();
let offset_data = list.offset_data();
// Use the address of the paint as an identifier for the recursion
// blacklist.
let id = offset.to_u32() as usize + offset_data.as_ref().as_ptr() as usize;
Ok((offset.resolve(offset_data)?, id))
}
/// Returns the COLRv1 clip box for the given glyph identifier.
pub fn v1_clip_box(&self, glyph_id: GlyphId) -> Result<Option<ClipBox<'a>>, ReadError> {
use core::cmp::Ordering;
let Ok(glyph_id): Result<GlyphId16, _> = glyph_id.try_into() else {
return Ok(None);
};
let list = self.clip_list().ok_or(ReadError::NullOffset)??;
let clips = list.clips();
let clip = match clips.binary_search_by(|clip| {
if glyph_id < clip.start_glyph_id() {
Ordering::Greater
} else if glyph_id > clip.end_glyph_id() {
Ordering::Less
} else {
Ordering::Equal
}
}) {
Ok(ix) => &clips[ix],
_ => return Ok(None),
};
Ok(Some(clip.clip_box(list.offset_data())?))
}
}
+734
View File
@@ -0,0 +1,734 @@
//! computing closure for the colr table
use font_types::{GlyphId, GlyphId16};
use crate::{collections::IntSet, tables::variations::NO_VARIATION_INDEX, ResolveOffset};
use super::{
Clip, ClipBox, ClipBoxFormat2, ClipList, ColorLine, ColorStop, Colr, Paint, PaintColrGlyph,
PaintColrLayers, PaintComposite, PaintGlyph, PaintLinearGradient, PaintRadialGradient,
PaintRotate, PaintRotateAroundCenter, PaintScale, PaintScaleAroundCenter, PaintScaleUniform,
PaintScaleUniformAroundCenter, PaintSkew, PaintSkewAroundCenter, PaintSolid,
PaintSweepGradient, PaintTransform, PaintTranslate, PaintVarLinearGradient,
PaintVarRadialGradient, PaintVarRotate, PaintVarRotateAroundCenter, PaintVarScale,
PaintVarScaleAroundCenter, PaintVarScaleUniform, PaintVarScaleUniformAroundCenter,
PaintVarSkew, PaintVarSkewAroundCenter, PaintVarSolid, PaintVarSweepGradient,
PaintVarTransform, PaintVarTranslate, VarAffine2x3, VarColorLine, VarColorStop,
};
impl Colr<'_> {
//Collect the transitive closure of V0 palette indices needed for all of the input glyphs set
//It's similar to closure glyphs but in a separate fn, because v1 closure might adds more v0 glyphs, so this fn needs to be called after v1 closure
pub fn v0_closure_palette_indices(
&self,
glyph_set: &IntSet<GlyphId>,
palette_indices: &mut IntSet<u16>,
) {
let Some(Ok(records)) = self.base_glyph_records() else {
return;
};
for glyph_id in glyph_set.iter() {
let Ok(glyph_id) = glyph_id.try_into() else {
continue;
};
let record = match records.binary_search_by(|rec| rec.glyph_id().cmp(&glyph_id)) {
Ok(idx) => records[idx],
_ => continue,
};
let start = record.first_layer_index() as usize;
let end = start + record.num_layers() as usize;
for layer_index in start..end {
if let Ok((_gid, palette_id)) = self.v0_layer(layer_index) {
palette_indices.insert(palette_id);
}
}
}
}
/// Collect the transitive closure of v1 glyphs,layer/paletted indices and variation/delta set indices for COLRv1
pub fn v1_closure(
&self,
glyph_set: &mut IntSet<GlyphId>,
layer_indices: &mut IntSet<u32>,
palette_indices: &mut IntSet<u16>,
variation_indices: &mut IntSet<u32>,
) {
if self.version() < 1 {
return;
}
let mut c =
Colrv1ClosureContext::new(layer_indices, palette_indices, variation_indices, self);
if let Some(Ok(base_glyph_list)) = self.base_glyph_list() {
let base_glyph_records = base_glyph_list.base_glyph_paint_records();
let offset_data = base_glyph_list.offset_data();
for paint_record in base_glyph_records {
let gid = paint_record.glyph_id();
if !glyph_set.contains(GlyphId::from(gid)) {
continue;
}
if let Ok(paint) = paint_record.paint(offset_data) {
c.dispatch(&paint);
}
}
glyph_set.union(&c.glyph_set);
}
if let Some(Ok(clip_list)) = self.clip_list() {
c.glyph_set.union(glyph_set);
for clip_record in clip_list.clips() {
clip_record.v1_closure(&mut c, &clip_list);
}
}
}
/// Collect the transitive closure of V0 glyphs needed for all of the input glyphs set
pub fn v0_closure_glyphs(
&self,
glyph_set: &IntSet<GlyphId>,
glyphset_colrv0: &mut IntSet<GlyphId>,
) {
glyphset_colrv0.union(glyph_set);
let Some(Ok(records)) = self.base_glyph_records() else {
return;
};
for glyph_id in glyph_set.iter() {
let Ok(glyph_id) = glyph_id.try_into() else {
continue;
};
let record = match records.binary_search_by(|rec| rec.glyph_id().cmp(&glyph_id)) {
Ok(idx) => records[idx],
_ => continue,
};
let start = record.first_layer_index() as usize;
let end = start + record.num_layers() as usize;
for layer_index in start..end {
if let Ok((gid, _palette_id)) = self.v0_layer(layer_index) {
glyphset_colrv0.insert(GlyphId::from(gid));
}
}
}
}
}
struct Colrv1ClosureContext<'a> {
glyph_set: IntSet<GlyphId>,
layer_indices: &'a mut IntSet<u32>,
palette_indices: &'a mut IntSet<u16>,
variation_indices: &'a mut IntSet<u32>,
colr: &'a Colr<'a>,
nesting_level_left: u8,
visited_paints: IntSet<u32>,
colr_head: usize,
}
impl<'a> Colrv1ClosureContext<'a> {
pub fn new(
layer_indices: &'a mut IntSet<u32>,
palette_indices: &'a mut IntSet<u16>,
variation_indices: &'a mut IntSet<u32>,
colr: &'a Colr,
) -> Self {
let colr_head = colr.offset_data().as_bytes().as_ptr() as usize;
Self {
glyph_set: IntSet::empty(),
layer_indices,
palette_indices,
variation_indices,
colr,
nesting_level_left: 64,
visited_paints: IntSet::empty(),
colr_head,
}
}
fn dispatch(&mut self, paint: &Paint) {
if self.nesting_level_left == 0 {
return;
}
if self.paint_visited(paint) {
return;
}
self.nesting_level_left -= 1;
paint.v1_closure(self);
self.nesting_level_left += 1;
}
fn paint_visited(&mut self, paint: &Paint) -> bool {
let offset = (paint.offset_data().as_bytes().as_ptr() as usize - self.colr_head) as u32;
if self.visited_paints.contains(offset) {
return true;
}
self.visited_paints.insert(offset);
false
}
fn add_layer_indices(&mut self, first_layer_index: u32, last_layer_index: u32) {
self.layer_indices
.insert_range(first_layer_index..=last_layer_index);
}
fn add_palette_index(&mut self, palette_index: u16) {
self.palette_indices.insert(palette_index);
}
fn add_variation_indices(&mut self, var_index_base: u32, num_vars: u8) {
if num_vars == 0 || var_index_base == NO_VARIATION_INDEX {
return;
}
let last_var_index = var_index_base + num_vars as u32 - 1;
self.variation_indices
.insert_range(var_index_base..=last_var_index);
}
fn add_glyph_id(&mut self, gid: GlyphId16) {
self.glyph_set.insert(GlyphId::from(gid));
}
}
impl ColorStop {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_palette_index(self.palette_index());
}
}
impl VarColorStop {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_palette_index(self.palette_index());
c.add_variation_indices(self.var_index_base(), 2);
}
}
impl ColorLine<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
for colorstop in self.color_stops() {
colorstop.v1_closure(c);
}
}
}
impl VarColorLine<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
for var_colorstop in self.color_stops() {
var_colorstop.v1_closure(c);
}
}
}
impl Paint<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
match self {
Self::ColrLayers(item) => item.v1_closure(c),
Self::Solid(item) => item.v1_closure(c),
Self::VarSolid(item) => item.v1_closure(c),
Self::LinearGradient(item) => item.v1_closure(c),
Self::VarLinearGradient(item) => item.v1_closure(c),
Self::RadialGradient(item) => item.v1_closure(c),
Self::VarRadialGradient(item) => item.v1_closure(c),
Self::SweepGradient(item) => item.v1_closure(c),
Self::VarSweepGradient(item) => item.v1_closure(c),
Self::Glyph(item) => item.v1_closure(c),
Self::ColrGlyph(item) => item.v1_closure(c),
Self::Transform(item) => item.v1_closure(c),
Self::VarTransform(item) => item.v1_closure(c),
Self::Translate(item) => item.v1_closure(c),
Self::VarTranslate(item) => item.v1_closure(c),
Self::Scale(item) => item.v1_closure(c),
Self::VarScale(item) => item.v1_closure(c),
Self::ScaleAroundCenter(item) => item.v1_closure(c),
Self::VarScaleAroundCenter(item) => item.v1_closure(c),
Self::ScaleUniform(item) => item.v1_closure(c),
Self::VarScaleUniform(item) => item.v1_closure(c),
Self::ScaleUniformAroundCenter(item) => item.v1_closure(c),
Self::VarScaleUniformAroundCenter(item) => item.v1_closure(c),
Self::Rotate(item) => item.v1_closure(c),
Self::VarRotate(item) => item.v1_closure(c),
Self::RotateAroundCenter(item) => item.v1_closure(c),
Self::VarRotateAroundCenter(item) => item.v1_closure(c),
Self::Skew(item) => item.v1_closure(c),
Self::VarSkew(item) => item.v1_closure(c),
Self::SkewAroundCenter(item) => item.v1_closure(c),
Self::VarSkewAroundCenter(item) => item.v1_closure(c),
Self::Composite(item) => item.v1_closure(c),
}
}
}
impl PaintColrLayers<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
let num_layers = self.num_layers();
if num_layers == 0 {
return;
}
let Some(Ok(layer_list)) = c.colr.layer_list() else {
return;
};
let first_layer_index = self.first_layer_index();
let last_layer_index = first_layer_index + num_layers as u32 - 1;
c.add_layer_indices(first_layer_index, last_layer_index);
let offset_data = layer_list.offset_data();
for layer_index in first_layer_index..=last_layer_index {
if let Some(paint_offset) = layer_list.paint_offsets().get(layer_index as usize) {
if let Ok(paint) = paint_offset.get().resolve::<Paint>(offset_data) {
c.dispatch(&paint);
}
}
}
}
}
impl PaintSolid<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_palette_index(self.palette_index());
}
}
impl PaintVarSolid<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_palette_index(self.palette_index());
c.add_variation_indices(self.var_index_base(), 1);
}
}
impl PaintLinearGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(colorline) = self.color_line() {
colorline.v1_closure(c);
}
}
}
impl PaintVarLinearGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(var_colorline) = self.color_line() {
var_colorline.v1_closure(c);
}
c.add_variation_indices(self.var_index_base(), 6);
}
}
impl PaintRadialGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(colorline) = self.color_line() {
colorline.v1_closure(c);
}
}
}
impl PaintVarRadialGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(var_colorline) = self.color_line() {
var_colorline.v1_closure(c);
}
c.add_variation_indices(self.var_index_base(), 6);
}
}
impl PaintSweepGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(colorline) = self.color_line() {
colorline.v1_closure(c);
}
}
}
impl PaintVarSweepGradient<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(var_colorline) = self.color_line() {
var_colorline.v1_closure(c);
}
c.add_variation_indices(self.var_index_base(), 4);
}
}
impl PaintGlyph<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_glyph_id(self.glyph_id());
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintColrGlyph<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
let glyph_id = self.glyph_id();
let Some(Ok(list)) = c.colr.base_glyph_list() else {
return;
};
let records = list.base_glyph_paint_records();
let record = match records.binary_search_by(|rec| rec.glyph_id().cmp(&glyph_id)) {
Ok(ix) => &records[ix],
_ => return,
};
if let Ok(paint) = record.paint(list.offset_data()) {
c.add_glyph_id(glyph_id);
c.dispatch(&paint);
}
}
}
impl PaintTransform<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl VarAffine2x3<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_variation_indices(self.var_index_base(), 6);
}
}
impl PaintVarTransform<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
if let Ok(affine2x3) = self.transform() {
affine2x3.v1_closure(c);
}
}
}
}
impl PaintTranslate<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarTranslate<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 2);
}
}
}
impl PaintScale<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarScale<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 2);
}
}
}
impl PaintScaleAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarScaleAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 4);
}
}
}
impl PaintScaleUniform<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarScaleUniform<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 1);
}
}
}
impl PaintScaleUniformAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarScaleUniformAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 3);
}
}
}
impl PaintRotate<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarRotate<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 1);
}
}
}
impl PaintRotateAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarRotateAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 3);
}
}
}
impl PaintSkew<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarSkew<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 2);
}
}
}
impl PaintSkewAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
}
}
}
impl PaintVarSkewAroundCenter<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(paint) = self.paint() {
c.dispatch(&paint);
c.add_variation_indices(self.var_index_base(), 4);
}
}
}
impl PaintComposite<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Ok(source_paint) = self.source_paint() {
c.dispatch(&source_paint);
}
if let Ok(backdrop_paint) = self.backdrop_paint() {
c.dispatch(&backdrop_paint);
}
}
}
impl Clip {
fn v1_closure(&self, c: &mut Colrv1ClosureContext, clip_list: &ClipList) {
let Ok(clip_box) = self.clip_box(clip_list.offset_data()) else {
return;
};
//TODO: replace below code when we have intersects(Range) available for int-set
let mut included_gids = IntSet::empty();
let start_id = GlyphId::from(self.start_glyph_id());
let end_id = GlyphId::from(self.end_glyph_id());
included_gids.insert_range(start_id..=end_id);
included_gids.intersect(&c.glyph_set);
if included_gids.is_empty() {
return;
}
clip_box.v1_closure(c);
}
}
impl ClipBox<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
if let Self::Format2(item) = self {
item.v1_closure(c)
}
}
}
impl ClipBoxFormat2<'_> {
fn v1_closure(&self, c: &mut Colrv1ClosureContext) {
c.add_variation_indices(self.var_index_base(), 4);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{FontRef, GlyphId, TableProvider};
#[test]
fn test_colr_v0_closure() {
let font = FontRef::new(font_test_data::COLRV0V1_VARIABLE).unwrap();
let colr = font.colr().unwrap();
let mut input_glyph_set = IntSet::empty();
input_glyph_set.insert(GlyphId::new(168));
let mut glyph_set_colred = IntSet::empty();
colr.v0_closure_glyphs(&input_glyph_set, &mut glyph_set_colred);
assert_eq!(glyph_set_colred.len(), 9);
assert!(glyph_set_colred.contains(GlyphId::new(5)));
assert!(glyph_set_colred.contains(GlyphId::new(168)));
assert!(glyph_set_colred.contains(GlyphId::new(170)));
assert!(glyph_set_colred.contains(GlyphId::new(171)));
assert!(glyph_set_colred.contains(GlyphId::new(172)));
assert!(glyph_set_colred.contains(GlyphId::new(173)));
assert!(glyph_set_colred.contains(GlyphId::new(174)));
assert!(glyph_set_colred.contains(GlyphId::new(175)));
assert!(glyph_set_colred.contains(GlyphId::new(176)));
let mut palette_indices = IntSet::empty();
colr.v0_closure_palette_indices(&glyph_set_colred, &mut palette_indices);
assert_eq!(palette_indices.len(), 8);
assert!(palette_indices.contains(0));
assert!(palette_indices.contains(1));
assert!(palette_indices.contains(2));
assert!(palette_indices.contains(3));
assert!(palette_indices.contains(4));
assert!(palette_indices.contains(5));
assert!(palette_indices.contains(6));
assert!(palette_indices.contains(10));
}
#[test]
fn test_colr_v0_closure_not_found() {
let font = FontRef::new(font_test_data::COLRV0V1_VARIABLE).unwrap();
let colr = font.colr().unwrap();
let mut input_glyph_set = IntSet::empty();
input_glyph_set.insert(GlyphId::new(8));
let mut glyph_set_colred = IntSet::empty();
colr.v0_closure_glyphs(&input_glyph_set, &mut glyph_set_colred);
assert_eq!(glyph_set_colred.len(), 1);
assert!(glyph_set_colred.contains(GlyphId::new(8)));
}
#[test]
fn test_colr_v1_closure_no_var() {
let font = FontRef::new(font_test_data::COLRV0V1_VARIABLE).unwrap();
let colr = font.colr().unwrap();
let mut glyph_set = IntSet::empty();
glyph_set.insert(GlyphId::new(220));
glyph_set.insert(GlyphId::new(120));
let mut layer_indices = IntSet::empty();
let mut palette_indices = IntSet::empty();
let mut variation_indices = IntSet::empty();
colr.v1_closure(
&mut glyph_set,
&mut layer_indices,
&mut palette_indices,
&mut variation_indices,
);
assert_eq!(glyph_set.len(), 6);
assert!(glyph_set.contains(GlyphId::new(6)));
assert!(glyph_set.contains(GlyphId::new(7)));
assert!(glyph_set.contains(GlyphId::new(220)));
assert!(glyph_set.contains(GlyphId::new(3)));
assert!(glyph_set.contains(GlyphId::new(2)));
assert!(glyph_set.contains(GlyphId::new(120)));
assert_eq!(palette_indices.len(), 5);
assert!(palette_indices.contains(0));
assert!(palette_indices.contains(4));
assert!(palette_indices.contains(10));
assert!(palette_indices.contains(11));
assert!(palette_indices.contains(12));
assert_eq!(layer_indices.len(), 2);
assert!(layer_indices.contains(0));
assert!(layer_indices.contains(1));
assert!(variation_indices.is_empty());
}
#[test]
fn test_colr_v1_closure_w_var() {
let font = FontRef::new(font_test_data::COLRV0V1_VARIABLE).unwrap();
let colr = font.colr().unwrap();
let mut glyph_set = IntSet::empty();
glyph_set.insert(GlyphId::new(109));
let mut layer_indices = IntSet::empty();
let mut palette_indices = IntSet::empty();
let mut variation_indices = IntSet::empty();
colr.v1_closure(
&mut glyph_set,
&mut layer_indices,
&mut palette_indices,
&mut variation_indices,
);
assert_eq!(glyph_set.len(), 2);
assert!(glyph_set.contains(GlyphId::new(3)));
assert!(glyph_set.contains(GlyphId::new(109)));
assert_eq!(palette_indices.len(), 2);
assert!(palette_indices.contains(1));
assert!(palette_indices.contains(4));
assert!(layer_indices.is_empty());
assert_eq!(variation_indices.len(), 6);
assert!(variation_indices.contains(51));
assert!(variation_indices.contains(52));
assert!(variation_indices.contains(53));
assert!(variation_indices.contains(54));
assert!(variation_indices.contains(55));
assert!(variation_indices.contains(56));
}
}
+36
View File
@@ -0,0 +1,36 @@
//! The [CPAL](https://docs.microsoft.com/en-us/typography/opentype/spec/cpal) table
include!("../../generated/generated_cpal.rs");
#[cfg(test)]
mod tests {
use crate::{FontRef, TableProvider};
#[test]
fn read_sample() {
let font = FontRef::new(font_test_data::COLR_GRADIENT_RECT).unwrap();
let table = font.cpal().unwrap();
assert_eq!(table.version(), 0);
assert_eq!(table.num_palette_entries(), 2);
assert_eq!(table.num_palettes(), 2);
assert_eq!(table.num_color_records(), 4);
let color_records = table.color_records_array().unwrap().unwrap();
assert_eq!(color_records.len(), 4);
let color_tuples: Vec<[u8; 4]> = color_records
.iter()
.map(|cr| [cr.red(), cr.green(), cr.blue(), cr.alpha()])
.collect();
assert_eq!(
color_tuples,
vec![
[0x00, 0x00, 0xFF, 0xFF],
[0x00, 0xFF, 0xFF, 0xFF],
[0xAA, 0x00, 0xFF, 0xFF],
[0xAA, 0xFF, 0xFF, 0xFF],
]
);
}
}
+267
View File
@@ -0,0 +1,267 @@
//! The [cvar (CVT Variations)](https://learn.microsoft.com/en-us/typography/opentype/spec/cvar)
//! table.
include!("../../generated/generated_cvar.rs");
use super::variations::{
PackedPointNumbers, TupleDelta, TupleVariationCount, TupleVariationData, TupleVariationHeader,
};
/// Variation data specialized for the CVT variation table.
pub type CvtVariationData<'a> = TupleVariationData<'a, CvtDelta>;
impl<'a> Cvar<'a> {
/// Returns the variation data containing the tuples and deltas for the
/// control value table.
///
/// This table doesn't contain an axis count field so this must be provided
/// by the user and can be read from the `fvar` table.
pub fn variation_data(&self, axis_count: u16) -> Result<CvtVariationData<'a>, ReadError> {
let count = self.tuple_variation_count();
let data = self.data()?;
let header_data = self.raw_tuple_header_data();
// if there are shared point numbers, get them now
let (shared_point_numbers, serialized_data) = if count.shared_point_numbers() {
let (packed, data) = PackedPointNumbers::split_off_front(data);
(Some(packed), data)
} else {
(None, data)
};
Ok(CvtVariationData {
tuple_count: count,
axis_count,
shared_tuples: None,
shared_point_numbers,
header_data,
serialized_data,
_marker: std::marker::PhantomData,
})
}
/// Computes the accumulated deltas for the given set of normalized
/// coordinates and stores them in `deltas`.
///
/// The `axis_count` parameter expects the value from the `fvar`
/// table.
///
/// The `deltas` slice should have a length greater than or equal
/// to the number of values in the `cvt` table. The values are
/// computed in 16.16 format.
pub fn deltas(
&self,
axis_count: u16,
coords: &[F2Dot14],
deltas: &mut [i32],
) -> Result<(), ReadError> {
let var_data = self.variation_data(axis_count)?;
for (tuple, scalar) in var_data.active_tuples_at(coords) {
for delta in tuple.deltas() {
let ix = delta.position as usize;
if let Some(value) = deltas.get_mut(ix) {
*value += delta.apply_scalar(scalar).to_bits();
}
}
}
Ok(())
}
fn raw_tuple_header_data(&self) -> FontData<'a> {
let range = self.shape.tuple_variation_headers_byte_range();
self.data.split_off(range.start).unwrap()
}
}
/// Delta for an entry in the control value table.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CvtDelta {
/// The index in the CVT.
pub position: u16,
/// The delta to apply to the value in the CVT.
pub value: i32,
}
impl CvtDelta {
/// Applies a tuple scalar to this delta.
pub fn apply_scalar(self, scalar: Fixed) -> Fixed {
Fixed::from_i32(self.value) * scalar
}
}
impl TupleDelta for CvtDelta {
fn is_point() -> bool {
false
}
fn new(position: u16, x: i32, _y: i32) -> Self {
Self { position, value: x }
}
}
#[cfg(test)]
mod tests {
use font_types::F2Dot14;
use crate::{FontRef, TableProvider};
#[test]
fn scaled_deltas() {
let font = FontRef::new(font_test_data::CVAR).unwrap();
// Elements are ([coords], [deltas]) where deltas are fixed point
// values.
// These were generated by fancy printf debugging in FreeType.
let cases = &[
(
[0.5, 0.5],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 720896, 3276800, 1179648, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 622592, 0, 1179648, 0, 0, 0, 0, 0, 622592,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
),
(
[-0.5, 0.5],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1441792, -2162688, -1277952, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -917504, 0, -1277952, 0, 0, 0, 0, 0,
-720896, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
],
),
(
[0.5, -0.5],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1900544, 2621440, 2129920, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 360448, 0, 1015808, 0, 0, 0, 0, 0,
524288, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
],
),
(
[-0.5, -0.5],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1212416, -2293760, -1130496, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1097728, 0, -1277952, 0, 0, 0, 0, 0,
-737280, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
],
),
(
[-1.0, -1.0],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2490368, -4325376, -2490368, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1835008, 0, -2555904, 0, 0, 0, 0, 0,
-1441792, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
],
),
(
[1.0, 1.0],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1441792, 6553600, 2359296, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1245184, 0, 2359296, 0, 0, 0, 0, 0,
1245184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
],
),
(
[-1.0, 1.0],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2883584, -4325376, -2555904, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1835008, 0, -2555904, 0, 0, 0, 0, 0,
-1441792, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
],
),
(
[1.0, -1.0],
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5636096, 4456448, 5636096, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 917504, 0, 1703936, 0, 0, 0, 0, 0,
917504, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
],
),
];
let cvar = font.cvar().unwrap();
let axis_count = font.fvar().unwrap().axis_count();
let cvar_data = cvar.variation_data(axis_count).unwrap();
for (coords, expected_deltas) in cases {
let coords = coords.map(F2Dot14::from_f32);
let mut deltas = vec![0; expected_deltas.len()];
for tuple in cvar_data.tuples() {
let Some(scalar) = tuple.compute_scalar(&coords) else {
continue;
};
for delta in tuple.deltas() {
let scaled_delta = delta.apply_scalar(scalar);
deltas[delta.position as usize] += scaled_delta.to_bits();
}
}
assert_eq!(&deltas, expected_deltas);
}
}
#[test]
fn raw_tuple_deltas() {
let font = FontRef::new(font_test_data::CVAR).unwrap();
let cvar = font.cvar().unwrap();
let axis_count = font.fvar().unwrap().axis_count();
let cvar_data = cvar.variation_data(axis_count).unwrap();
// An array of slices of (point number, delta) pairs, one for each
// tuple.
// These were taken directly from the ttx
let expected = [
&[(65, 8), (66, -8), (67, 8), (85, -11), (87, 0), (93, -1)],
&[(65, -2), (66, 8), (67, -7), (85, 11), (87, 0), (93, 1)],
&[(65, 56), (66, -24), (67, 42), (85, 6), (87, -10), (93, -4)],
&[
(65, -44),
(66, -66),
(67, -39),
(85, -28),
(87, -39),
(93, -22),
],
&[(65, 22), (66, 100), (67, 36), (85, 19), (87, 36), (93, 19)],
&[(65, 8), (66, 0), (67, 8), (85, -43), (87, -49), (93, -32)],
&[(65, -8), (66, 0), (67, -8), (85, 11), (87, 9), (93, 1)],
&[(65, -80), (66, 0), (67, -90), (85, -6), (87, -47), (93, 4)],
&[(65, -16), (66, 0), (67, -21), (85, 28), (87, 39), (93, 22)],
&[
(65, -46),
(66, 0),
(67, -22),
(85, -19),
(87, 35),
(93, -19),
],
&[(65, 2), (66, 0), (67, 7), (85, -11), (87, -9), (93, -1)],
];
let mut count = 0;
for (tuple, expected) in cvar_data.tuples().zip(&expected) {
count += 1;
let deltas = tuple
.deltas()
.map(|delta| (delta.position, delta.value))
.collect::<Vec<_>>();
assert_eq!(&deltas, expected);
}
assert_eq!(count, expected.len());
}
}

Some files were not shown because too many files have changed in this diff Show More