1use crate::error::{ParseError, RawTag};
4use alloc::string::String;
5use alloc::vec::Vec;
6
7pub(crate) const TAG: RawTag = *b"name";
8
9const RECORD: usize = 12;
11
12pub mod name_id {
14 pub const COPYRIGHT: u16 = 0;
16 pub const FAMILY: u16 = 1;
18 pub const SUBFAMILY: u16 = 2;
20 pub const UNIQUE_ID: u16 = 3;
22 pub const FULL_NAME: u16 = 4;
24 pub const VERSION: u16 = 5;
26 pub const POSTSCRIPT: u16 = 6;
28 pub const TRADEMARK: u16 = 7;
30 pub const MANUFACTURER: u16 = 8;
32 pub const DESIGNER: u16 = 9;
34 pub const DESCRIPTION: u16 = 10;
36 pub const VENDOR_URL: u16 = 11;
38 pub const DESIGNER_URL: u16 = 12;
40 pub const LICENSE: u16 = 13;
42 pub const LICENSE_URL: u16 = 14;
44 pub const PREFERRED_FAMILY: u16 = 16;
46 pub const PREFERRED_SUBFAMILY: u16 = 17;
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct NameRecord<'a> {
53 pub platform_id: u16,
55 pub encoding_id: u16,
57 pub language_id: u16,
59 pub name_id: u16,
61 pub bytes: &'a [u8],
63}
64
65impl NameRecord<'_> {
66 #[must_use]
68 pub const fn is_windows(self) -> bool {
69 self.platform_id == 3
70 }
71
72 #[must_use]
76 pub fn to_str(&self) -> Option<&str> {
77 core::str::from_utf8(self.bytes).ok()
78 }
79
80 #[must_use]
83 pub fn decode(&self) -> String {
84 if self.is_windows() {
85 let mut units = Vec::with_capacity(self.bytes.len() / 2);
86 for c in self.bytes.chunks_exact(2) {
87 if let Ok(pair) = <[u8; 2]>::try_from(c) {
88 units.push(u16::from_be_bytes(pair));
89 }
90 }
91 String::from_utf16_lossy(&units)
92 } else {
93 self.bytes.iter().map(|&b| b as char).collect()
94 }
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct NameTable<'a> {
101 data: &'a [u8],
102 count: u16,
103 string_offset: usize,
104}
105
106impl<'a> NameTable<'a> {
107 pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
114 if data.len() < 6 {
115 return Err(ParseError::TruncatedTable {
116 tag: TAG,
117 expected: 6,
118 got: data.len(),
119 });
120 }
121 let count = crate::reader::be_u16_at(data, 2, TAG)?;
122 let string_offset = usize::from(crate::reader::be_u16_at(data, 4, TAG)?);
123 let end = 6usize
124 .checked_add(
125 usize::from(count)
126 .checked_mul(RECORD)
127 .ok_or(ParseError::InvalidGlyphFormat)?,
128 )
129 .ok_or(ParseError::InvalidGlyphFormat)?;
130 if end > data.len() {
131 return Err(ParseError::TruncatedTable {
132 tag: TAG,
133 expected: end,
134 got: data.len(),
135 });
136 }
137 Ok(Self {
138 data,
139 count,
140 string_offset,
141 })
142 }
143
144 #[must_use]
146 pub fn as_bytes(&self) -> &'a [u8] {
147 self.data
148 }
149
150 pub fn format(&self) -> Result<u16, ParseError> {
155 crate::reader::be_u16_at(self.data, 0, TAG)
156 }
157
158 #[must_use]
160 pub const fn count(&self) -> u16 {
161 self.count
162 }
163
164 pub fn records(&self) -> Result<Vec<NameRecord<'a>>, ParseError> {
170 let mut out = Vec::with_capacity(usize::from(self.count));
171 for i in 0..usize::from(self.count) {
172 out.push(self.record_at(i)?);
173 }
174 Ok(out)
175 }
176
177 fn record_at(&self, i: usize) -> Result<NameRecord<'a>, ParseError> {
178 let at = 6 + i * RECORD;
179 let platform_id = crate::reader::be_u16_at(self.data, at, TAG)?;
180 let encoding_id = crate::reader::be_u16_at(self.data, at + 2, TAG)?;
181 let language_id = crate::reader::be_u16_at(self.data, at + 4, TAG)?;
182 let name_id = crate::reader::be_u16_at(self.data, at + 6, TAG)?;
183 let length = usize::from(crate::reader::be_u16_at(self.data, at + 8, TAG)?);
184 let offset = usize::from(crate::reader::be_u16_at(self.data, at + 10, TAG)?);
185 let base = self
186 .string_offset
187 .checked_add(offset)
188 .ok_or(ParseError::InvalidGlyphFormat)?;
189 let bytes = crate::reader::slice_at(self.data, base, length, TAG)?;
190 Ok(NameRecord {
191 platform_id,
192 encoding_id,
193 language_id,
194 name_id,
195 bytes,
196 })
197 }
198
199 #[must_use]
202 pub fn get(&self, id: u16) -> Option<NameRecord<'a>> {
203 let mut best: Option<(u8, NameRecord<'a>)> = None;
204 for i in 0..usize::from(self.count) {
205 let rec = self.record_at(i).ok()?;
206 if rec.name_id != id {
207 continue;
208 }
209 let score = match rec.platform_id {
210 3 => 3,
211 0 => 2,
212 1 => 1,
213 _ => 0,
214 };
215 best = match best {
216 None => Some((score, rec)),
217 Some((s, _)) if score > s => Some((score, rec)),
218 other => other,
219 };
220 }
221 best.map(|(_, rec)| rec)
222 }
223
224 #[must_use]
226 pub fn family(&self) -> Option<String> {
227 self.get(name_id::FAMILY).map(|r| r.decode())
228 }
229
230 #[must_use]
232 pub fn subfamily(&self) -> Option<String> {
233 self.get(name_id::SUBFAMILY).map(|r| r.decode())
234 }
235
236 #[must_use]
238 pub fn full_name(&self) -> Option<String> {
239 self.get(name_id::FULL_NAME).map(|r| r.decode())
240 }
241
242 #[must_use]
244 pub fn postscript_name(&self) -> Option<String> {
245 self.get(name_id::POSTSCRIPT).map(|r| r.decode())
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
252
253 use super::{name_id, NameTable};
254 use alloc::vec::Vec;
255
256 fn sample() -> Vec<u8> {
262 let mut d = Vec::new();
263 d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&2u16.to_be_bytes()); let string_offset = 6u16 + 2 * 12;
266 d.extend_from_slice(&string_offset.to_be_bytes());
267 d.extend_from_slice(&3u16.to_be_bytes());
269 d.extend_from_slice(&1u16.to_be_bytes());
270 d.extend_from_slice(&0x0409u16.to_be_bytes());
271 d.extend_from_slice(&name_id::FAMILY.to_be_bytes());
272 d.extend_from_slice(&8u16.to_be_bytes()); d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes());
276 d.extend_from_slice(&0u16.to_be_bytes());
277 d.extend_from_slice(&0u16.to_be_bytes());
278 d.extend_from_slice(&name_id::POSTSCRIPT.to_be_bytes());
279 d.extend_from_slice(&12u16.to_be_bytes());
280 d.extend_from_slice(&8u16.to_be_bytes());
281 d.extend_from_slice(&[0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74]); d.extend_from_slice(b"Test-Regular");
284 d
285 }
286
287 #[test]
288 fn reads_records_and_helpers() {
289 let d = sample();
290 let n = NameTable::parse(&d).unwrap();
291 assert_eq!(n.count(), 2);
292 assert_eq!(n.format().unwrap(), 0);
293 assert_eq!(n.family().as_deref(), Some("Test"));
294 assert_eq!(n.postscript_name().as_deref(), Some("Test-Regular"));
295 assert!(n.subfamily().is_none());
296 let fam = n.get(name_id::FAMILY).unwrap();
297 assert!(fam.is_windows());
298 assert_eq!(fam.decode(), "Test");
301 let recs = n.records().unwrap();
302 assert_eq!(recs.len(), 2);
303 assert_eq!(recs[1].to_str(), Some("Test-Regular"));
304 }
305
306 #[test]
307 fn errors() {
308 assert_eq!(
309 NameTable::parse(&[0u8; 5]),
310 Err(crate::ParseError::TruncatedTable {
311 tag: *b"name",
312 expected: 6,
313 got: 5
314 })
315 );
316 let mut d = sample();
318 d.truncate(20);
319 assert!(NameTable::parse(&d).is_err());
320 let mut d = sample();
323 d.truncate(35);
324 let n = NameTable::parse(&d).unwrap();
325 assert!(n.records().is_err());
326 assert!(n.get(super::name_id::FAMILY).is_none());
327 }
328}