Vendor things

This commit is contained in:
John Doty 2024-03-08 11:03:01 -08:00
parent 5deceec006
commit 977e3c17e5
19434 changed files with 10682014 additions and 0 deletions

View file

@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"bb52dca363c07d59c28f2d87795ff3b2ee48ca1f7e25ac3501ef336a285cc914","Cargo.toml":"4ca36f79c8b65ad48657a9e852ef99e5dab476a26900cf187f7f5099d16a2c1d","LICENSE":"a6cba85bc92e0cff7a450b1d873c0eaa2e9fc96bf472df0247a26bec77bf3ff9","README.md":"c23ff857e7caeb79d745b208dff1a7cc3fec009aefbadbacaaf15615da2b66e7","fonts/Cantarell-VF.otf":"257cafd9c63c0c29f77b357eb4143f574149ac45e26596c3db9997451a64fbb0","fonts/NotoColorEmoji-Partial.ttf":"9f74c83cf6a7342b4f2ccface3d9777a35a822694b6b7a14df12e6bb365beb73","fonts/font.ttf":"77f615401f92518fe5da8382b4c4741dd4d7ab3cf4da9a18290964df1682e6d0","src/convert.rs":"0a6051867d150b9c5a05f165cb77c83caf27f2a2aa1bcdae3838e53ddb3b5fcc","src/lib.rs":"2ca92f15ddf3ba1680c877d908a4c7f3250470438a4ea4b0ec7dc3dafa9b2fc7","src/owned.rs":"e9d7a181ab0a200116acc3d6af3f2c5be045ad0540435707b28d53434a8aff78","src/preparse.rs":"c92126a7296106859f99b0afdba5397f3d08850428dc7958a6757168efee5466","test":"225a183d77f6738711be41a069ed6c698a2059d9ef7745b8cdb636560323d03b","tests/face_mut.rs":"809bb601a7c633cfc7e7f4e1152bbaed41c3a3a1321402a8663a706b928eeda1","tests/owned_ttf.rs":"4d29480b37f81d2e0394009ee18b2bf3ba910dfc6e5d1f2b2b2996e5f3d6d361","tests/preparse.rs":"045f7e4d163f70c8cef6664aacc51363b9bbf3957b9a0d2391dd28afb3f41900"},"package":"d4586edfe4c648c71797a74c84bacb32b52b212eff5dfe2bb9f2c599844023e7"}

View file

@ -0,0 +1,86 @@
# 0.20.0
* Update _ttf-parser_ to `0.20.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0200---2023-10-15).
* Guard against future soundness issues if upstream `Face` were to implement `Drop`.
# 0.19.0
* Update _ttf-parser_ to `0.19.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0190---2023-04-17).
# 0.18.1
* Make `PreParsedSubtables` `face` field public. This allows referencing and unwrapping the underlying face.
# 0.18.0
* Update _ttf-parser_ to `0.18.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0180---2022-12-25).
# 0.17.1
* Add `PreParsedSubtables::glyph_variation_index`.
# 0.17.0
* Update _ttf-parser_ to `0.17.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0170---2022-09-28).
# 0.16.0
* Update _ttf-parser_ to `0.16.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0160---2022-09-18).
# 0.15.2
* Add `FaceMut::set_variation` trait abstraction for calling mutable `Face::set_variation` via `OwnedFace`.
* Use edition 2021.
# 0.15.1
* Add `OwnedFace::as_slice`, `OwnedFace::into_vec`.
# 0.15.0
* Update _ttf-parser_ to `0.15.0`, add `apple-layout` feature [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0150---2022-02-20).
# 0.14.0
* Update _ttf-parser_ to `0.14.0`, [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0140---2021-12-28).
# 0.13.2
* Add `PreParsedSubtables` struct allowing pre-parsing of cmap & kern face subtables at initialization
time for re-use. This allows much faster `glyph_index` & `glyphs_hor_kerning` avoiding the need
to parse subtables inside each call.
* Update _ttf-parser_ to `0.13.2`, add `gvar-alloc` feature [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0132---2021-10-28).
# 0.13.1
* Update _ttf-parser_ to `0.13.1` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0131---2021-10-27).
# 0.13.0
* Update _ttf-parser_ to `0.13` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0130---2021-10-24).
# 0.12.1
* Update _ttf-parser_ to `0.12.3` to ensure consistent glyph bounding box behaviour.
# 0.12
* Update _ttf-parser_ to `0.12` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0120---2021-02-14).
# 0.11
* Update _ttf-parser_ to `0.11` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0110---2021-02-04).
# 0.10
* Update _ttf-parser_ to `0.10` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#0100---2021-01-16).
* Add `variable-fonts` features, alongside existing `std` feature (both default) inline with upstream.
# 0.9
* Update _ttf-parser_ to `0.9` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#090---2020-12-05).
# 0.8
* Update _ttf-parser_ to `0.8` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#080---2020-07-21).
* `OwnedFace::from_vec` now returns a `Result`.
# 0.7
* Update _ttf-parser_ to `0.7` [changelog](https://github.com/RazrFalcon/ttf-parser/blob/master/CHANGELOG.md#070---2020-07-16).
* Update `*Font` -> `*Face` to reflect the _ttf-parser_ API changes.
```rust
// 0.6
let owned_font = OwnedFont::from_vec(owned_font_data, 0)?;
// 0.7
let owned_face = OwnedFace::from_vec(owned_font_data, 0)?;
```
# 0.6
* Update _ttf-parser_ to `0.6`.
# 0.5.1
* Support no_std.
# 0.5
* Implement crate supporting _ttf-parser_ `0.5`.

View file

@ -0,0 +1,48 @@
# 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"
name = "owned_ttf_parser"
version = "0.20.0"
authors = ["Alex Butler <alexheretic@gmail.com>"]
description = "ttf-parser plus support for owned data"
readme = "README.md"
keywords = [
"ttf",
"truetype",
"otf",
"opentype",
]
license = "Apache-2.0"
repository = "https://github.com/alexheretic/owned-ttf-parser"
[dependencies.ttf-parser]
version = "0.20"
default-features = false
[features]
apple-layout = ["ttf-parser/apple-layout"]
default = [
"std",
"opentype-layout",
"apple-layout",
"variable-fonts",
"glyph-names",
]
glyph-names = ["ttf-parser/glyph-names"]
gvar-alloc = [
"std",
"ttf-parser/gvar-alloc",
]
opentype-layout = ["ttf-parser/opentype-layout"]
std = ["ttf-parser/std"]
variable-fonts = ["ttf-parser/variable-fonts"]

View file

@ -0,0 +1,176 @@
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) 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
(d) 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

View file

@ -0,0 +1,26 @@
owned_ttf_parser
[![crates.io](https://img.shields.io/crates/v/owned_ttf_parser.svg)](https://crates.io/crates/owned_ttf_parser)
[![Documentation](https://docs.rs/owned_ttf_parser/badge.svg)](https://docs.rs/owned_ttf_parser)
================
[ttf-parser](https://github.com/RazrFalcon/ttf-parser) plus support for owned data.
Provides `OwnedFace`, `AsFaceRef` and re-exports `ttf_parser::*`.
## Example
```rust
use owned_ttf_parser::{AsFaceRef, OwnedFace, Face};
let owned_face = OwnedFace::from_vec(owned_face_data, 0).unwrap();
let face_ref: &Face<'_> = owned_face.as_face_ref();
assert_eq!(face_ref.ascender(), 2254);
```
## no_std
no_std environments are supported using `alloc`.
```toml
owned_ttf_parser = { default-features = false }
```
## Minimum supported rust compiler
All crates maintained with [latest stable rust](https://gist.github.com/alexheretic/d1e98d8433b602e57f5d0a9637927e0c).

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,39 @@
/// Used to perform a cheap conversion to a [`Face`](struct.Face.html) reference.
pub trait AsFaceRef {
/// Convert to a [`Face`](struct.Face.html) reference.
fn as_face_ref(&self) -> &ttf_parser::Face<'_>;
}
impl AsFaceRef for ttf_parser::Face<'_> {
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self
}
}
impl AsFaceRef for &ttf_parser::Face<'_> {
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self
}
}
/// Trait exposing mutable operations on a [`ttf_parser::Face`].
pub trait FaceMut {
/// Sets a variation axis coordinate.
///
/// See [`ttf_parser::Face::set_variation`].
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()>;
}
impl FaceMut for ttf_parser::Face<'_> {
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
ttf_parser::Face::set_variation(self, axis, value)
}
}
impl FaceMut for &mut ttf_parser::Face<'_> {
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
ttf_parser::Face::set_variation(self, axis, value)
}
}

View file

@ -0,0 +1,26 @@
//! Extends [ttf_parser](https://docs.rs/ttf-parser) with owned version of
//! [`Face`](struct.Face.html): [`OwnedFace`](struct.OwnedFace.html).
//!
//! Re-exports `ttf_parser::*`.
//!
//! # Example
//! ```
//! use owned_ttf_parser::{AsFaceRef, Face, OwnedFace};
//!
//! # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
//! let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
//! let face_ref: &Face<'_> = owned_face.as_face_ref();
//!
//! assert_eq!(face_ref.ascender(), 2254);
//! ```
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
mod convert;
mod owned;
mod preparse;
pub use convert::*;
pub use owned::*;
pub use preparse::*;
pub use ttf_parser::*;

View file

@ -0,0 +1,159 @@
use crate::preparse::{FaceSubtables, PreParsedSubtables};
#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};
use core::{fmt, marker::PhantomPinned, mem, pin::Pin, slice};
/// An owned version of font [`Face`](struct.Face.html).
pub struct OwnedFace(Pin<Box<SelfRefVecFace>>);
impl OwnedFace {
/// Creates an `OwnedFace` from owned data.
///
/// You can set index for font collections. For simple ttf fonts set index to 0.
///
/// # Example
/// ```
/// # use owned_ttf_parser::OwnedFace;
/// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
/// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
/// ```
// Note: not `try_from_vec` to better mimic `ttf_parser::Face::from_data`.
pub fn from_vec(data: Vec<u8>, index: u32) -> Result<Self, ttf_parser::FaceParsingError> {
let inner = SelfRefVecFace::try_from_vec(data, index)?;
Ok(Self(inner))
}
pub(crate) fn pre_parse_subtables(self) -> PreParsedSubtables<'static, Self> {
// build subtables referencing fake static data
let subtables = FaceSubtables::from(match self.0.face.as_ref() {
Some(f) => f,
None => unsafe { core::hint::unreachable_unchecked() },
});
// bundle everything together so self-reference lifetimes hold
PreParsedSubtables {
face: self,
subtables,
}
}
/// Extracts a slice containing the data passed into [`OwnedFace::from_vec`].
///
/// # Example
/// ```
/// # use owned_ttf_parser::OwnedFace;
/// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
/// let data_clone = owned_font_data.clone();
/// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
/// assert_eq!(owned_face.as_slice(), data_clone);
/// ```
pub fn as_slice(&self) -> &[u8] {
&self.0.data
}
/// Unwraps the data passed into [`OwnedFace::from_vec`].
///
/// # Example
/// ```
/// # use owned_ttf_parser::OwnedFace;
/// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
/// let data_clone = owned_font_data.clone();
/// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
/// assert_eq!(owned_face.into_vec(), data_clone);
/// ```
pub fn into_vec(self) -> Vec<u8> {
self.0.into_vec()
}
}
impl fmt::Debug for OwnedFace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OwnedFace()")
}
}
impl crate::convert::AsFaceRef for OwnedFace {
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self.0.inner_ref()
}
}
impl crate::convert::AsFaceRef for &OwnedFace {
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self.0.inner_ref()
}
}
impl crate::convert::FaceMut for OwnedFace {
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
unsafe {
let mut_ref = Pin::as_mut(&mut self.0);
let mut_inner = mut_ref.get_unchecked_mut();
match mut_inner.face.as_mut() {
Some(face) => face.set_variation(axis, value),
None => None,
}
}
}
}
impl crate::convert::FaceMut for &mut OwnedFace {
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
(*self).set_variation(axis, value)
}
}
// Face data in a `Vec` with a self-referencing `Face`.
struct SelfRefVecFace {
data: Vec<u8>,
face: Option<ttf_parser::Face<'static>>,
_pin: PhantomPinned,
}
impl SelfRefVecFace {
/// Creates an underlying face object from owned data.
fn try_from_vec(
data: Vec<u8>,
index: u32,
) -> Result<Pin<Box<Self>>, ttf_parser::FaceParsingError> {
let face = Self {
data,
face: None,
_pin: PhantomPinned,
};
let mut b = Box::pin(face);
unsafe {
// 'static lifetime is a lie, this data is owned, it has pseudo-self lifetime.
let slice: &'static [u8] = slice::from_raw_parts(b.data.as_ptr(), b.data.len());
let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut b);
let mut_inner = mut_ref.get_unchecked_mut();
mut_inner.face = Some(ttf_parser::Face::parse(slice, index)?);
}
Ok(b)
}
// Must not leak the fake 'static lifetime that we lied about earlier to the
// compiler. Since the lifetime 'a will not outlive our owned data it's
// safe to provide Face<'a>
#[inline]
#[allow(clippy::needless_lifetimes)] // explicit is nice as it's important 'static isn't leaked
fn inner_ref<'a>(self: &'a Pin<Box<Self>>) -> &'a ttf_parser::Face<'a> {
// Safety: if you have a ref `face` is always Some
unsafe { self.face.as_ref().unwrap_unchecked() }
}
fn into_vec(self: Pin<Box<Self>>) -> Vec<u8> {
// Safety: safe as `face` is dropped.
let mut me = unsafe { Pin::into_inner_unchecked(self) };
me.face.take(); // ensure dropped before taking `data`
mem::take(&mut me.data)
}
}
impl Drop for SelfRefVecFace {
fn drop(&mut self) {
self.face.take(); // ensure dropped before `data`
}
}

View file

@ -0,0 +1,153 @@
//! Logic to avoid re-parsing subtables in ttf_parser::Face methods
use crate::{AsFaceRef, FaceMut, OwnedFace};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt;
use ttf_parser::{cmap, kern, Face, GlyphId};
/// A `Face` with cmap & kern subtables parsed once on initialization.
///
/// Provides much faster [`PreParsedSubtables::glyph_index`] &
/// [`PreParsedSubtables::glyphs_hor_kerning`] methods compared to the
/// `.as_face_ref()` equivalents that must parse their subtables on each call.
///
/// # Example
/// ```
/// use owned_ttf_parser::{AsFaceRef, GlyphId, OwnedFace, PreParsedSubtables};
///
/// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
/// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
/// let faster_face = PreParsedSubtables::from(owned_face);
///
/// // Lookup a GlyphId using the pre-parsed cmap subtables
/// // this is much faster than doing: .as_face_ref().glyph_index('x')
/// assert_eq!(faster_face.glyph_index('x'), Some(GlyphId(91)));
///
/// // The rest of the methods are still available as normal
/// assert_eq!(faster_face.as_face_ref().ascender(), 2254);
/// ```
#[derive(Clone)]
pub struct PreParsedSubtables<'face, F> {
/// Underlying face.
pub face: F,
// note must not be public as could be self-referencing
pub(crate) subtables: FaceSubtables<'face>,
}
impl<'face> From<Face<'face>> for PreParsedSubtables<'face, Face<'face>> {
fn from(face: Face<'face>) -> Self {
let subtables = FaceSubtables::from(&face);
Self { face, subtables }
}
}
impl From<OwnedFace> for PreParsedSubtables<'static, OwnedFace> {
fn from(face: OwnedFace) -> Self {
face.pre_parse_subtables()
}
}
impl<F> fmt::Debug for PreParsedSubtables<'_, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PreParsedSubtables")
}
}
#[derive(Clone)]
pub(crate) struct FaceSubtables<'face> {
/// Unicode cmap subtables.
cmap: Vec<cmap::Subtable<'face>>,
/// Horizontal kern subtables.
h_kern: Vec<kern::Subtable<'face>>,
}
impl<'face> From<&Face<'face>> for FaceSubtables<'face> {
fn from(face: &Face<'face>) -> Self {
let cmap = face
.tables()
.cmap
.iter()
.flat_map(|cmap| cmap.subtables)
.filter(|st| st.is_unicode())
.collect();
let h_kern = face
.tables()
.kern
.iter()
.flat_map(|c| c.subtables)
.filter(|st| st.horizontal && !st.variable)
.collect();
Self { cmap, h_kern }
}
}
impl<F> PreParsedSubtables<'_, F> {
/// Maps a character to a `GlyphId` using pre-parsed unicode cmap subtables.
#[inline]
pub fn glyph_index(&self, c: char) -> Option<GlyphId> {
self.subtables
.cmap
.iter()
.find_map(|t| t.glyph_index(c.into()))
}
/// Maps a variation of a character to a `GlyphId` using pre-parsed unicode cmap subtables.
#[inline]
pub fn glyph_variation_index(&self, c: char, v: char) -> Option<GlyphId> {
self.subtables
.cmap
.iter()
.find_map(|t| t.glyph_variation_index(c.into(), v.into()))
.and_then(|r| match r {
cmap::GlyphVariationResult::Found(v) => Some(v),
cmap::GlyphVariationResult::UseDefault => self.glyph_index(c),
})
}
/// Returns horizontal kerning for a pair of glyphs using pre-parsed kern subtables.
#[inline]
pub fn glyphs_hor_kerning(&self, first: GlyphId, second: GlyphId) -> Option<i16> {
self.subtables
.h_kern
.iter()
.find_map(|st| st.glyphs_kerning(first, second))
}
}
impl<F> AsFaceRef for PreParsedSubtables<'_, F>
where
F: AsFaceRef,
{
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self.face.as_face_ref()
}
}
impl<F> AsFaceRef for &PreParsedSubtables<'_, F>
where
F: AsFaceRef,
{
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
(*self).as_face_ref()
}
}
impl<F> FaceMut for PreParsedSubtables<'_, F>
where
F: FaceMut,
{
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
self.face.set_variation(axis, value)
}
}
impl<F> FaceMut for &mut PreParsedSubtables<'_, F>
where
F: FaceMut,
{
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
(*self).set_variation(axis, value)
}
}

15
third-party/vendor/owned_ttf_parser/test vendored Executable file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env bash
# run CI-like set of tests
set -eu
dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$dir"
echo "==> test"
cargo test
echo "==> no_std"
cargo build --target thumbv6m-none-eabi --no-default-features --features "variable-fonts opentype-layout glyph-names"
echo "==> rustfmt"
cargo fmt -- --check

View file

@ -0,0 +1,19 @@
//! Tests for the FaceMut trait.
use owned_ttf_parser::{AsFaceRef, FaceMut, OwnedFace};
const VFONT: &[u8] = include_bytes!("../fonts/Cantarell-VF.otf");
#[test]
fn set_variation() {
let mut face = OwnedFace::from_vec(VFONT.to_vec(), 0).unwrap();
let axis = face.as_face_ref().variation_axes().get(0).unwrap();
let def_coord = face.as_face_ref().variation_coordinates()[0];
// after setting variation on the owned face it should change
let new_value = axis.def_value + 100.0;
face.set_variation(axis.tag, new_value)
.expect("Should be some");
let coord = face.as_face_ref().variation_coordinates()[0];
assert!(coord.get() > def_coord.get());
}

View file

@ -0,0 +1,16 @@
use owned_ttf_parser::{AsFaceRef, OwnedFace};
const FONT: &[u8] = include_bytes!("../fonts/font.ttf");
#[test]
fn move_and_use() {
let owned_data = FONT.to_vec();
let pin_face = OwnedFace::from_vec(owned_data, 0).unwrap();
let ascent = pin_face.as_face_ref().ascender();
// force a move
let moved = Box::new(pin_face);
assert_eq!(moved.as_face_ref().ascender(), ascent);
}

View file

@ -0,0 +1,56 @@
use owned_ttf_parser::{AsFaceRef, GlyphId, PreParsedSubtables};
const FONT: &[u8] = include_bytes!("../fonts/font.ttf");
const EMOJI_FONT: &[u8] = include_bytes!("../fonts/NotoColorEmoji-Partial.ttf");
#[test]
fn preparse_glyph_index() {
let face = owned_ttf_parser::Face::parse(FONT, 0).unwrap();
let pre_parse = PreParsedSubtables::from(face.clone());
assert_eq!(pre_parse.glyph_index('x'), face.glyph_index('x'));
assert_eq!(
pre_parse.as_face_ref().glyph_index('x'),
face.glyph_index('x')
);
}
#[test]
fn preparse_glyph_variation_index() {
let face = owned_ttf_parser::Face::parse(EMOJI_FONT, 0).unwrap();
let pre_parse = PreParsedSubtables::from(face.clone());
assert_eq!(
pre_parse.glyph_variation_index('#', '\u{FE0F}'),
face.glyph_variation_index('#', '\u{FE0F}')
);
assert_eq!(
pre_parse
.as_face_ref()
.glyph_variation_index('#', '\u{FE0F}'),
face.glyph_variation_index('#', '\u{FE0F}')
);
}
#[test]
fn preparse_glyphs_kerning() {
let face = owned_ttf_parser::Face::parse(FONT, 0).unwrap();
let pre_parse = PreParsedSubtables::from(face.clone());
let (a, b) = (GlyphId(92), GlyphId(93));
assert_eq!(
pre_parse.glyphs_hor_kerning(a, b),
face.tables()
.kern
.iter()
.flat_map(|c| c.subtables)
.filter(|st| st.horizontal && !st.variable)
.find_map(|st| st.glyphs_kerning(a, b))
);
}