cad_text_realization/
font_container.rs1mod preflight;
5#[cfg(test)]
6mod tests;
7
8use sha2::{Digest, Sha256};
9use std::fmt;
10
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum FontContainerErrorKind {
13 InvalidContainer,
14 UnsupportedProfile,
15 LimitExceeded,
16}
17
18#[derive(Debug)]
19pub struct FontContainerError {
20 pub kind: FontContainerErrorKind,
21 message: String,
22}
23
24impl fmt::Display for FontContainerError {
25 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26 formatter.write_str(&self.message)
27 }
28}
29impl std::error::Error for FontContainerError {}
30
31fn error(kind: FontContainerErrorKind, message: impl Into<String>) -> FontContainerError {
32 FontContainerError {
33 kind,
34 message: message.into(),
35 }
36}
37
38#[derive(Debug)]
40pub struct PreparedFontContainer {
41 source_sha256: String,
42 sfnt_sha256: String,
43 sfnt: Vec<u8>,
44 source_container: &'static str,
45 normalization_engine: &'static str,
46}
47
48impl PreparedFontContainer {
49 pub fn source_sha256(&self) -> &str {
50 &self.source_sha256
51 }
52 pub fn sfnt_sha256(&self) -> &str {
53 &self.sfnt_sha256
54 }
55 pub fn sfnt_bytes(&self) -> &[u8] {
56 &self.sfnt
57 }
58 pub fn into_sfnt_bytes(self) -> Vec<u8> {
59 self.sfnt
60 }
61 pub fn source_container(&self) -> &str {
62 self.source_container
63 }
64 pub fn normalization_engine(&self) -> &str {
65 self.normalization_engine
66 }
67 pub fn sfnt_media_type(&self) -> &str {
68 if self.sfnt.starts_with(b"OTTO") {
69 "font/otf"
70 } else {
71 "font/ttf"
72 }
73 }
74}
75
76pub fn prepare_font_container(raw: &[u8]) -> Result<PreparedFontContainer, FontContainerError> {
79 let (sfnt, source_container, normalization_engine) = match raw.get(..4) {
80 Some(b"OTTO" | b"\x00\x01\x00\x00" | b"true") => {
81 preflight::sfnt(raw)?;
82 (raw.to_vec(), "sfnt", "sfnt-pass-through-v1")
83 }
84 Some(b"wOF2") => {
85 preflight::woff2_cff(raw)?;
86 let bytes = wuff::decompress_woff2(raw).map_err(|cause| {
87 error(FontContainerErrorKind::InvalidContainer, cause.to_string())
88 })?;
89 preflight::sfnt(&bytes)?;
90 if !bytes.starts_with(b"OTTO") {
91 return Err(error(
92 FontContainerErrorKind::InvalidContainer,
93 "CFF decoder returned another SFNT flavor",
94 ));
95 }
96 (bytes, "woff2", "wuff-0.2.9+single-face-cff-null-v1")
97 }
98 _ => {
99 return Err(error(
100 FontContainerErrorKind::UnsupportedProfile,
101 "Font container/profile is unsupported",
102 ));
103 }
104 };
105 Ok(PreparedFontContainer {
106 source_sha256: digest(raw),
107 sfnt_sha256: digest(&sfnt),
108 sfnt,
109 source_container,
110 normalization_engine,
111 })
112}
113
114fn digest(bytes: &[u8]) -> String {
115 Sha256::digest(bytes)
116 .iter()
117 .map(|byte| format!("{byte:02x}"))
118 .collect()
119}