1#![cfg_attr(docsrs, feature(doc_cfg))]
60#![forbid(unsafe_code)]
61#![deny(rustdoc::broken_intra_doc_links)]
62#![cfg_attr(not(feature = "std"), no_std)]
63
64#[cfg(any(feature = "std", test))]
65#[macro_use]
66extern crate std;
67
68#[cfg(all(not(feature = "std"), not(test)))]
69#[macro_use]
70extern crate core as std;
71
72extern crate alloc;
75
76pub mod array;
77pub(crate) use array::impl_font_read_at;
78#[cfg(any(test, feature = "codegen_test"))]
79pub mod codegen_test;
80pub mod collections;
81mod font_data;
82pub mod limits;
83pub mod mem;
84pub mod model;
85mod offset;
86mod offset_array;
87pub mod ps;
88mod read;
89mod table_provider;
90mod table_ref;
91pub mod tables;
92
93pub use font_data::FontData;
94pub use offset::{Offset, ResolveNullableOffset, ResolveOffset};
95pub use offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
96pub use read::{ComputeSize, FontRead, FontReadAt, ReadArgs, ReadError, VarSize};
97pub use table_provider::{TableProvider, TopLevelTable};
98pub use table_ref::MinByteRange;
99
100pub extern crate font_types as types;
102
103#[doc(hidden)]
105pub(crate) mod codegen_prelude {
106 pub use crate::array::{ComputedArray, VarLenArray};
107 pub use crate::font_data::{Cursor, FontData};
108 pub use crate::offset::{Offset, ResolveNullableOffset, ResolveOffset};
109 pub use crate::offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
110 pub use crate::read::{
111 ComputeSize, Discriminant, FontRead, FontReadAt, Format, ReadArgs, ReadError, VarSize,
112 };
113 pub use crate::table_provider::TopLevelTable;
114 pub use crate::table_ref::MinByteRange;
115 pub use std::ops::Range;
116
117 pub use types::*;
118
119 pub(crate) mod transforms {
121 pub fn to_usize<T: TryInto<usize>>(value: T) -> usize {
122 value.try_into().unwrap_or_default()
123 }
124
125 pub fn subtract<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
126 lhs.try_into()
127 .unwrap_or_default()
128 .saturating_sub(rhs.try_into().unwrap_or_default())
129 }
130
131 pub fn add<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
132 lhs.try_into()
133 .unwrap_or_default()
134 .saturating_add(rhs.try_into().unwrap_or_default())
135 }
136
137 #[allow(dead_code)]
138 pub fn bitmap_len<T: TryInto<usize>>(count: T) -> usize {
139 count.try_into().unwrap_or_default().div_ceil(8)
140 }
141
142 pub fn add_multiply<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
143 a: T,
144 b: U,
145 c: V,
146 ) -> usize {
147 a.try_into()
148 .unwrap_or_default()
149 .saturating_add(b.try_into().unwrap_or_default())
150 .saturating_mul(c.try_into().unwrap_or_default())
151 }
152
153 #[cfg(feature = "ift")]
154 pub fn multiply_add<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
155 a: T,
156 b: U,
157 c: V,
158 ) -> usize {
159 a.try_into()
160 .unwrap_or_default()
161 .saturating_mul(b.try_into().unwrap_or_default())
162 .saturating_add(c.try_into().unwrap_or_default())
163 }
164
165 pub fn half<T: TryInto<usize>>(val: T) -> usize {
166 val.try_into().unwrap_or_default() / 2
167 }
168
169 pub fn subtract_add_two<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
170 lhs.try_into()
171 .unwrap_or_default()
172 .saturating_sub(rhs.try_into().unwrap_or_default())
173 .saturating_add(2)
174 }
175 }
176
177 macro_rules! basic_table_impls {
178 (impl_the_methods) => {
179 pub fn resolve_offset<O: Offset, R: FontRead<'a, Args = ()>>(
181 &self,
182 offset: O,
183 ) -> Result<R, ReadError> {
184 offset.resolve(self.offset_data())
185 }
186
187 #[inline(always)]
191 pub fn offset_data(&self) -> FontData<'a> {
192 FontData::new(self.data.data())
193 }
194
195 #[deprecated(note = "just use the base type directly")]
201 pub fn shape(&self) -> &Self {
202 &self
203 }
204 };
205 }
206
207 pub(crate) use basic_table_impls;
208}
209
210include!("../generated/font.rs");
211
212#[derive(Clone)]
213pub enum FileRef<'a> {
215 Font(FontRef<'a>),
217 Collection(CollectionRef<'a>),
219}
220
221impl<'a> FileRef<'a> {
222 pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
224 Ok(if let Ok(collection) = CollectionRef::new(data) {
225 Self::Collection(collection)
226 } else {
227 Self::Font(FontRef::new(data)?)
228 })
229 }
230
231 pub fn fonts(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
233 let (iter_one, iter_two) = match self {
234 Self::Font(font) => (Some(Ok(font.clone())), None),
235 Self::Collection(collection) => (None, Some(collection.iter())),
236 };
237 iter_two.into_iter().flatten().chain(iter_one)
238 }
239}
240
241#[derive(Clone)]
243pub struct CollectionRef<'a> {
244 data: FontData<'a>,
245 offsets: &'a [types::BigEndian<u32>],
246}
247
248impl<'a> CollectionRef<'a> {
249 pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
251 let data = FontData::new(data);
252 let header = TTCHeader::read(data)?;
253 if header.ttc_tag() != TTC_HEADER_TAG {
254 Err(ReadError::InvalidTtc(header.ttc_tag()))
255 } else {
256 let legacy_end = usize::try_from(header.num_fonts())
257 .ok()
258 .and_then(|count| count.checked_mul(4))
259 .and_then(|size| size.checked_add(12))
260 .ok_or(ReadError::OutOfBounds)?;
261 let version = header.version();
262 let offsets = if matches!(version.major, 1 | 2) && version.minor >= 1 {
263 let count_pos = legacy_end
267 .checked_add(if version.major == 2 { 12 } else { 0 })
268 .ok_or(ReadError::OutOfBounds)?;
269 let count = data.read_at::<u32>(count_pos)?;
270 let start = count_pos.checked_add(4).ok_or(ReadError::OutOfBounds)?;
271 let end = usize::try_from(count)
272 .ok()
273 .and_then(|count| count.checked_mul(4))
274 .and_then(|size| start.checked_add(size))
275 .ok_or(ReadError::OutOfBounds)?;
276 data.read_array(start..end)?
277 } else {
278 data.read_array(12..legacy_end)?
279 };
280 Ok(Self { data, offsets })
281 }
282 }
283
284 pub fn len(&self) -> u32 {
286 self.offsets.len() as u32
287 }
288
289 pub fn is_empty(&self) -> bool {
291 self.len() == 0
292 }
293
294 pub fn get(&self, index: u32) -> Result<FontRef<'a>, ReadError> {
296 let offset = self
297 .offsets
298 .get(index as usize)
299 .ok_or(ReadError::InvalidCollectionIndex(index))?
300 .get() as usize;
301 let table_dir_data = self.data.slice(offset..).ok_or(ReadError::OutOfBounds)?;
302 FontRef::with_table_directory(
303 self.data,
304 TableDirectory::read(table_dir_data)?,
305 Some(index),
306 )
307 }
308
309 pub fn iter(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
311 let copy = self.clone();
312 (0..self.len()).map(move |ix| copy.get(ix))
313 }
314}
315
316impl TableDirectory<'_> {
317 fn is_sorted(&self) -> bool {
318 let mut last_tag = Tag::new(&[0u8; 4]);
319
320 for tag in self.table_records().iter().map(|rec| rec.tag()) {
321 if tag <= last_tag {
322 return false;
323 }
324
325 last_tag = tag;
326 }
327
328 true
329 }
330}
331
332#[derive(Clone)]
337pub struct FontRef<'a> {
338 data: FontData<'a>,
339 pub table_directory: TableDirectory<'a>,
340 ttc_index: u32,
342 in_ttc: bool,
347 table_directory_sorted: bool,
351}
352
353impl<'a> FontRef<'a> {
354 pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
363 let data = FontData::new(data);
364 Self::with_table_directory(data, TableDirectory::read(data)?, None)
365 }
366
367 pub fn from_index(data: &'a [u8], index: u32) -> Result<Self, ReadError> {
379 let file = FileRef::new(data)?;
380 match file {
381 FileRef::Font(font) => {
382 if index == 0 {
383 Ok(font)
384 } else {
385 Err(ReadError::InvalidCollectionIndex(index))
386 }
387 }
388 FileRef::Collection(collection) => collection.get(index),
389 }
390 }
391
392 pub fn data(&self) -> FontData<'a> {
397 self.data
398 }
399
400 pub fn ttc_index(&self) -> Option<u32> {
403 self.in_ttc.then_some(self.ttc_index)
404 }
405
406 pub fn table_directory(&self) -> &TableDirectory<'a> {
408 &self.table_directory
409 }
410
411 pub fn table_data(&self, tag: Tag) -> Option<FontData<'a>> {
413 let entry = if self.table_directory_sorted {
414 self.table_directory
415 .table_records()
416 .binary_search_by(|rec| rec.tag.get().cmp(&tag))
417 .ok()
418 } else {
419 self.table_directory
420 .table_records()
421 .iter()
422 .position(|rec| rec.tag.get().eq(&tag))
423 };
424
425 entry
426 .and_then(|idx| self.table_directory.table_records().get(idx))
427 .and_then(|record| {
428 let start = Offset32::new(record.offset()).non_null()?;
429 let len = record.length() as usize;
430 self.data.slice(start..start.checked_add(len)?)
431 })
432 }
433
434 pub fn fonts(
437 data: &'a [u8],
438 ) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
439 let count = match FileRef::new(data) {
440 Ok(FileRef::Font(_)) => 1,
441 Ok(FileRef::Collection(ttc)) => ttc.len(),
442 _ => 0,
443 };
444 (0..count).map(|idx| FontRef::from_index(data, idx))
445 }
446
447 fn with_table_directory(
448 data: FontData<'a>,
449 table_directory: TableDirectory<'a>,
450 ttc_index: Option<u32>,
451 ) -> Result<Self, ReadError> {
452 if [TT_SFNT_VERSION, CFF_SFNT_VERSION, TRUE_SFNT_VERSION]
453 .contains(&table_directory.sfnt_version())
454 {
455 let table_directory_sorted = table_directory.is_sorted();
456
457 Ok(FontRef {
458 data,
459 table_directory,
460 ttc_index: ttc_index.unwrap_or_default(),
461 in_ttc: ttc_index.is_some(),
462 table_directory_sorted,
463 })
464 } else {
465 Err(ReadError::InvalidSfnt(table_directory.sfnt_version()))
466 }
467 }
468}
469
470impl<'a> TableProvider<'a> for FontRef<'a> {
471 fn data_for_tag(&self, tag: Tag) -> Option<FontData<'a>> {
472 self.table_data(tag)
473 }
474}
475
476#[cfg(test)]
477mod tests {
478 use font_test_data::{be_buffer, bebuffer::BeBuffer, ttc::TTC, AHEM};
479 use types::{Tag, TT_SFNT_VERSION};
480
481 use crate::{FileRef, FontRef};
482
483 #[test]
484 fn file_ref_non_collection() {
485 assert!(matches!(FileRef::new(AHEM), Ok(FileRef::Font(_))));
486 }
487
488 #[test]
489 fn file_ref_collection() {
490 let Ok(FileRef::Collection(collection)) = FileRef::new(TTC) else {
491 panic!("Expected a collection");
492 };
493 assert_eq!(2, collection.len());
494 assert!(!collection.is_empty());
495 }
496
497 #[test]
498 fn extended_ttc_directory_list_takes_precedence() {
499 for major in [1u16, 2] {
500 for legacy_count in [0u32, 1] {
501 let extended_start =
502 12 + legacy_count as usize * 4 + if major == 2 { 12 } else { 0 };
503 let first_directory = extended_start + 12;
504 let second_directory = first_directory + 12;
505 let mut bytes = b"ttcf".to_vec();
506 bytes.extend_from_slice(&major.to_be_bytes());
507 bytes.extend_from_slice(&1u16.to_be_bytes());
508 bytes.extend_from_slice(&legacy_count.to_be_bytes());
509 if legacy_count != 0 {
510 bytes.extend_from_slice(&(first_directory as u32).to_be_bytes());
511 }
512 if major == 2 {
513 bytes.extend_from_slice(&0x44534947u32.to_be_bytes());
515 bytes.extend_from_slice(&8u32.to_be_bytes());
516 bytes.extend_from_slice(&((second_directory + 12) as u32).to_be_bytes());
517 }
518 bytes.extend_from_slice(&2u32.to_be_bytes());
519 bytes.extend_from_slice(&(second_directory as u32).to_be_bytes());
520 bytes.extend_from_slice(&(first_directory as u32).to_be_bytes());
521 bytes.extend_from_slice(&TT_SFNT_VERSION.to_be_bytes());
522 bytes.extend_from_slice(&[0; 8]);
523 bytes.extend_from_slice(&0x4F54544Fu32.to_be_bytes());
524 bytes.extend_from_slice(&[0; 8]);
525 bytes.extend_from_slice(&[0; 8]);
526 let collection = crate::CollectionRef::new(&bytes).unwrap();
527 assert_eq!(collection.len(), 2);
528 assert_eq!(
529 collection.get(0).unwrap().table_directory().sfnt_version(),
530 0x4F54544F
531 );
532 assert_eq!(
533 collection.get(1).unwrap().table_directory().sfnt_version(),
534 TT_SFNT_VERSION
535 );
536 assert_eq!(FontRef::fonts(&bytes).count(), 2);
537 assert_eq!(
538 FontRef::from_index(&bytes, 0)
539 .unwrap()
540 .table_directory()
541 .sfnt_version(),
542 0x4F54544F
543 );
544 for len in extended_start..first_directory {
546 assert!(crate::CollectionRef::new(&bytes[..len]).is_err());
547 }
548 let mut empty = bytes.clone();
549 empty[extended_start..extended_start + 4].copy_from_slice(&0u32.to_be_bytes());
550 assert!(crate::CollectionRef::new(&empty).unwrap().is_empty());
551 let mut huge = bytes.clone();
552 huge[extended_start..extended_start + 4].copy_from_slice(&u32::MAX.to_be_bytes());
553 assert!(crate::CollectionRef::new(&huge).is_err());
554 }
555 }
556 }
557
558 #[test]
559 fn font_ref_fonts_iter() {
560 assert_eq!(FontRef::fonts(AHEM).count(), 1);
561 assert_eq!(FontRef::fonts(TTC).count(), 2);
562 assert_eq!(FontRef::fonts(b"NOT_A_FONT").count(), 0);
563 }
564
565 #[test]
566 fn ttc_index() {
567 for (idx, font) in FontRef::fonts(TTC).map(|font| font.unwrap()).enumerate() {
568 assert_eq!(font.ttc_index(), Some(idx as u32));
569 }
570 assert!(FontRef::new(AHEM).unwrap().ttc_index().is_none());
571 }
572
573 #[test]
574 fn unsorted_table_directory() {
575 let cff2_data = font_test_data::cff2::EXAMPLE;
576 let post_data = font_test_data::post::SIMPLE;
577 let gdef_data = [
578 font_test_data::gdef::GDEF_HEADER,
579 font_test_data::gdef::GLYPHCLASSDEF_TABLE,
580 ]
581 .concat();
582 let gpos_data = font_test_data::gpos::SINGLEPOSFORMAT1;
583
584 let font_data = be_buffer! {
585 TT_SFNT_VERSION,
586 4u16, 64u16, 2u16, 0u16, (Tag::new(b"post")),
592 0u32, 76u32, (post_data.len() as u32),
595
596 (Tag::new(b"GPOS")),
597 0u32, 108u32, (gpos_data.len() as u32),
600
601 (Tag::new(b"GDEF")),
602 0u32, 128u32, (gdef_data.len() as u32),
605
606 (Tag::new(b"CFF2")),
607 0u32, 160u32, (cff2_data.len() as u32)
610 };
611
612 let mut full_font = font_data.to_vec();
613
614 full_font.extend_from_slice(post_data);
615 full_font.extend_from_slice(gpos_data);
616 full_font.extend_from_slice(&gdef_data);
617 full_font.extend_from_slice(cff2_data);
618
619 let font = FontRef::new(&full_font).unwrap();
620
621 assert!(!font.table_directory_sorted);
622
623 assert!(font.table_data(Tag::new(b"CFF2")).is_some());
624 assert!(font.table_data(Tag::new(b"GDEF")).is_some());
625 assert!(font.table_data(Tag::new(b"GPOS")).is_some());
626 assert!(font.table_data(Tag::new(b"post")).is_some());
627 }
628}