Skip to main content

font_parse/tables/
name.rs

1//! `name` — naming table: family, style, full name, PostScript name.
2
3use crate::error::{ParseError, RawTag};
4use alloc::string::String;
5use alloc::vec::Vec;
6
7pub(crate) const TAG: RawTag = *b"name";
8
9/// Record header size.
10const RECORD: usize = 12;
11
12/// Well-known name ids (subset; raw ids pass through).
13pub mod name_id {
14    /// Copyright notice.
15    pub const COPYRIGHT: u16 = 0;
16    /// Font family name.
17    pub const FAMILY: u16 = 1;
18    /// Font subfamily (style) name.
19    pub const SUBFAMILY: u16 = 2;
20    /// Unique font identifier.
21    pub const UNIQUE_ID: u16 = 3;
22    /// Full font name.
23    pub const FULL_NAME: u16 = 4;
24    /// Version string.
25    pub const VERSION: u16 = 5;
26    /// PostScript name.
27    pub const POSTSCRIPT: u16 = 6;
28    /// Trademark.
29    pub const TRADEMARK: u16 = 7;
30    /// Manufacturer.
31    pub const MANUFACTURER: u16 = 8;
32    /// Designer.
33    pub const DESIGNER: u16 = 9;
34    /// Description.
35    pub const DESCRIPTION: u16 = 10;
36    /// Vendor URL.
37    pub const VENDOR_URL: u16 = 11;
38    /// Designer URL.
39    pub const DESIGNER_URL: u16 = 12;
40    /// License description.
41    pub const LICENSE: u16 = 13;
42    /// License URL.
43    pub const LICENSE_URL: u16 = 14;
44    /// Preferred family.
45    pub const PREFERRED_FAMILY: u16 = 16;
46    /// Preferred subfamily.
47    pub const PREFERRED_SUBFAMILY: u16 = 17;
48}
49
50/// One naming record: metadata ids plus the borrowed string bytes.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct NameRecord<'a> {
53    /// Platform id (0 Unicode, 1 Macintosh, 3 Windows).
54    pub platform_id: u16,
55    /// Platform-specific encoding id.
56    pub encoding_id: u16,
57    /// Language id.
58    pub language_id: u16,
59    /// What the string names (see [`name_id`]).
60    pub name_id: u16,
61    /// Raw string bytes.
62    pub bytes: &'a [u8],
63}
64
65impl NameRecord<'_> {
66    /// True for Windows (platform 3) records.
67    #[must_use]
68    pub const fn is_windows(self) -> bool {
69        self.platform_id == 3
70    }
71
72    /// The string as `&str` when the raw bytes are valid UTF-8 (typical for
73    /// ASCII Macintosh strings); `None` otherwise (use
74    /// [`decode`](Self::decode)).
75    #[must_use]
76    pub fn to_str(&self) -> Option<&str> {
77        core::str::from_utf8(self.bytes).ok()
78    }
79
80    /// Decode the string: UTF-16BE for Windows (platform 3) records,
81    /// lossy byte-per-char (Latin-1) otherwise.
82    #[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/// Zero-copy view over the `name` table.
99#[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    /// Parse and validate the `name` table header.
108    ///
109    /// # Errors
110    /// [`ParseError::TruncatedTable`] when header or records are truncated;
111    /// [`ParseError::InvalidGlyphFormat`] when the string storage falls
112    /// outside the table.
113    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    /// Raw table bytes.
145    #[must_use]
146    pub fn as_bytes(&self) -> &'a [u8] {
147        self.data
148    }
149
150    /// Format (0 or 1).
151    ///
152    /// # Errors
153    /// Truncation (impossible post-[`parse`](Self::parse)).
154    pub fn format(&self) -> Result<u16, ParseError> {
155        crate::reader::be_u16_at(self.data, 0, TAG)
156    }
157
158    /// Declared record count.
159    #[must_use]
160    pub const fn count(&self) -> u16 {
161        self.count
162    }
163
164    /// All records, in table order.
165    ///
166    /// # Errors
167    /// [`ParseError::TruncatedTable`] when a record's string range falls
168    /// outside the storage area.
169    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    /// First record matching `id`, preferring Windows (platform 3) then
200    /// Unicode (platform 0) then Macintosh (platform 1) encodings.
201    #[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    /// Family name (name id 1).
225    #[must_use]
226    pub fn family(&self) -> Option<String> {
227        self.get(name_id::FAMILY).map(|r| r.decode())
228    }
229
230    /// Subfamily / style name (name id 2).
231    #[must_use]
232    pub fn subfamily(&self) -> Option<String> {
233        self.get(name_id::SUBFAMILY).map(|r| r.decode())
234    }
235
236    /// Full font name (name id 4).
237    #[must_use]
238    pub fn full_name(&self) -> Option<String> {
239        self.get(name_id::FULL_NAME).map(|r| r.decode())
240    }
241
242    /// PostScript name (name id 6).
243    #[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    // Test harness: assertions legitimately panic; the lib target stays
257    // lint-clean.
258
259    /// Two records: (3,1,0x409) family "Test" as UTF-16BE, (1,0,0) PS name
260    /// "Test-Regular" as ASCII.
261    fn sample() -> Vec<u8> {
262        let mut d = Vec::new();
263        d.extend_from_slice(&0u16.to_be_bytes()); // format
264        d.extend_from_slice(&2u16.to_be_bytes()); // count
265        let string_offset = 6u16 + 2 * 12;
266        d.extend_from_slice(&string_offset.to_be_bytes());
267        // Record 1: family, Windows.
268        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()); // len
273        d.extend_from_slice(&0u16.to_be_bytes()); // offset
274                                                  // Record 2: PS name, Mac.
275        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        // Strings.
282        d.extend_from_slice(&[0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74]); // "Test"
283        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        // Raw UTF-16BE bytes happen to be valid UTF-8 (all ASCII range) —
299        // `to_str` passes them through; `decode` is the proper reader.
300        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        // Records truncated.
317        let mut d = sample();
318        d.truncate(20);
319        assert!(NameTable::parse(&d).is_err());
320        // String storage outside the table: parse stays lazy (header +
321        // records validated), but the records access surfaces the error.
322        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}