Skip to main content

pdf/
font.rs

1// font -- TrueType / OpenType fonts for a document: their metrics, the glyphs a document uses,
2// and what goes into the file: a Type0 font with Identity-H encoding over a CIDFont whose CIDs
3// are the font's glyph ids, a subset of the font program (TrueType: unused glyphs emptied in
4// glyf; CFF: unused charstrings replaced by endchar, cff.rs), the widths (W) and a ToUnicode
5// CMap for search and copy.
6//
7// Glyph ids stay as they are (CIDToGIDMap /Identity), so nothing in the content stream depends on
8// which glyphs the document uses; the emptied entries of glyf, loca and hmtx compress to
9// almost nothing.
10
11use alloc::collections::BTreeMap;
12use alloc::string::String;
13use alloc::vec;
14use alloc::vec::Vec;
15
16use crate::obj::{self, num};
17use crate::{cff, Error};
18
19/// the vertical metrics of a font in its own units (Document::font_metrics)
20#[non_exhaustive]
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct FontMetrics {
23    pub units_per_em: u16,
24    /// above the baseline (positive)
25    pub ascent: i16,
26    /// below the baseline (negative)
27    pub descent: i16,
28    pub line_gap: i16,
29    pub cap_height: i16,
30    pub x_height: i16,
31    /// how many glyphs the font has
32    pub glyphs: u16,
33}
34
35pub(crate) struct FontData {
36    data: Vec<u8>,
37    /// tag, offset, length (into data)
38    tables: Vec<([u8; 4], usize, usize)>,
39    pub(crate) cff: bool,
40    pub(crate) upem: u16,
41    pub(crate) glyphs: u16,
42    advances: Vec<u16>,
43    ps_name: Vec<u8>,
44    pub(crate) metrics: FontMetrics,
45    flags: u32,
46    bbox: [i16; 4],
47    italic_angle: f64,
48    stem_v: f64,
49    no_subset: bool,
50    /// embedded in full (a form field's font): every glyph, the widths of all, no subset tag
51    pub(crate) full: bool,
52    pub(crate) engine: text_shape::Engine,
53    /// the glyphs drawn, with the text the first of them stood for
54    pub(crate) used: BTreeMap<u16, Option<String>>,
55}
56
57fn u16_at(d: &[u8], o: usize) -> Option<u16> {
58    Some(u16::from_be_bytes([*d.get(o)?, *d.get(o + 1)?]))
59}
60
61fn i16_at(d: &[u8], o: usize) -> Option<i16> {
62    u16_at(d, o).map(|v| v as i16)
63}
64
65fn u32_at(d: &[u8], o: usize) -> Option<u32> {
66    Some(u32::from_be_bytes([*d.get(o)?, *d.get(o + 1)?, *d.get(o + 2)?, *d.get(o + 3)?]))
67}
68
69const BAD: Error = Error::Font("a damaged font file");
70
71impl FontData {
72    pub(crate) fn parse(data: Vec<u8>, face: u32) -> Result<FontData, Error> {
73        let d = &data[..];
74        let mut base = 0usize;
75        if d.get(..4) == Some(b"ttcf") {
76            let n = u32_at(d, 8).ok_or(BAD)?;
77            if face >= n {
78                return Err(Error::Font("no such face in the collection"));
79            }
80            base = u32_at(d, 12 + 4 * face as usize).ok_or(BAD)? as usize;
81        } else if face != 0 {
82            return Err(Error::Font("no such face in the collection"));
83        }
84        let version = u32_at(d, base).ok_or(BAD)?;
85        let cff = match version {
86            0x0001_0000 | 0x7472_7565 => false, // 'true'
87            0x4F54_544F => true,                // 'OTTO'
88            _ => return Err(Error::Font("not a TrueType or OpenType font")),
89        };
90        let n = u16_at(d, base + 4).ok_or(BAD)? as usize;
91        let mut tables = Vec::with_capacity(n);
92        for i in 0..n {
93            let r = base + 12 + 16 * i;
94            let tag: [u8; 4] = d.get(r..r + 4).ok_or(BAD)?.try_into().map_err(|_| BAD)?;
95            let off = u32_at(d, r + 8).ok_or(BAD)? as usize;
96            let len = u32_at(d, r + 12).ok_or(BAD)? as usize;
97            if off.checked_add(len).is_none_or(|e| e > d.len()) {
98                return Err(BAD);
99            }
100            tables.push((tag, off, len));
101        }
102        tables.sort_by(|a, b| a.0.cmp(&b.0));
103        let mut f = FontData {
104            data: Vec::new(),
105            tables,
106            cff,
107            upem: 0,
108            glyphs: 0,
109            advances: Vec::new(),
110            ps_name: Vec::new(),
111            metrics: FontMetrics { units_per_em: 0, ascent: 0, descent: 0, line_gap: 0, cap_height: 0, x_height: 0, glyphs: 0 },
112            flags: 0,
113            bbox: [0; 4],
114            italic_angle: 0.0,
115            stem_v: 0.0,
116            no_subset: false,
117            full: false,
118            engine: text_shape::Engine::new(d, face).ok_or(Error::Font("the shaper does not take the font"))?,
119            used: BTreeMap::new(),
120        };
121        f.data = data;
122        f.read_tables()?;
123        Ok(f)
124    }
125
126    fn table(&self, tag: &[u8; 4]) -> Option<&[u8]> {
127        let i = self.tables.binary_search_by(|t| t.0.cmp(tag)).ok()?;
128        let (_, off, len) = self.tables[i];
129        self.data.get(off..off + len)
130    }
131
132    fn read_tables(&mut self) -> Result<(), Error> {
133        let head = self.table(b"head").ok_or(Error::Font("no head table"))?;
134        let upem = u16_at(head, 18).ok_or(BAD)?;
135        if !(16..=16384).contains(&upem) {
136            return Err(Error::Font("units per em outside 16 to 16384"));
137        }
138        let bbox = [i16_at(head, 36).ok_or(BAD)?, i16_at(head, 38).ok_or(BAD)?, i16_at(head, 40).ok_or(BAD)?, i16_at(head, 42).ok_or(BAD)?];
139        let mac_style = u16_at(head, 44).ok_or(BAD)?;
140        let maxp = self.table(b"maxp").ok_or(Error::Font("no maxp table"))?;
141        let glyphs = u16_at(maxp, 4).ok_or(BAD)?;
142        if glyphs == 0 {
143            return Err(Error::Font("a font without glyphs"));
144        }
145        let hhea = self.table(b"hhea").ok_or(Error::Font("no hhea table"))?;
146        let (h_asc, h_desc, h_gap) = (i16_at(hhea, 4).ok_or(BAD)?, i16_at(hhea, 6).ok_or(BAD)?, i16_at(hhea, 8).ok_or(BAD)?);
147        let nhm = u16_at(hhea, 34).ok_or(BAD)?;
148        if nhm == 0 || nhm > glyphs {
149            return Err(BAD);
150        }
151        let hmtx = self.table(b"hmtx").ok_or(Error::Font("no hmtx table"))?;
152        if hmtx.len() < nhm as usize * 4 + (glyphs - nhm) as usize * 2 {
153            return Err(BAD);
154        }
155        let mut advances = Vec::with_capacity(glyphs as usize);
156        for g in 0..glyphs as usize {
157            let i = g.min(nhm as usize - 1);
158            advances.push(u16_at(hmtx, 4 * i).ok_or(BAD)?);
159        }
160        if self.cff {
161            if self.table(b"CFF ").is_none() {
162                return Err(if self.table(b"CFF2").is_some() { Error::Unsupported("CFF2 (variable OpenType) fonts") } else { Error::Font("no CFF table") });
163            }
164            let info = cff::info(self.table(b"CFF ").ok_or(BAD)?).map_err(Error::Font)?;
165            if info.glyphs != glyphs {
166                return Err(Error::Font("the CFF table and maxp disagree on the glyph count"));
167            }
168        } else {
169            let loca = self.table(b"loca").ok_or(Error::Font("no glyf outlines (bitmap-only fonts are not supported)"))?;
170            self.table(b"glyf").ok_or(Error::Font("no glyf table"))?;
171            let long = i16_at(head, 50).ok_or(BAD)? != 0;
172            if loca.len() < (glyphs as usize + 1) * if long { 4 } else { 2 } {
173                return Err(BAD);
174            }
175        }
176        // OS/2: embedding rights, weight, the typographic metrics
177        let (mut asc, mut desc, mut gap) = (h_asc, h_desc, h_gap);
178        let (mut cap, mut xh, mut weight, mut serif, mut italic) = (0i16, 0i16, 400u16, false, mac_style & 2 != 0);
179        let (mut no_subset, mut italic_angle) = (false, 0.0f64);
180        if let Some(os2) = self.table(b"OS/2") {
181            let fs_type = u16_at(os2, 8).unwrap_or(0);
182            if fs_type & 0x000F == 0x0002 {
183                return Err(Error::FontLicense("the font's licence forbids embedding (OS/2 fsType: restricted)"));
184            }
185            if fs_type & 0x0100 != 0 {
186                return Err(Error::FontLicense("the font's licence allows embedding its bitmaps only"));
187            }
188            no_subset = fs_type & 0x0200 != 0;
189            weight = u16_at(os2, 4).unwrap_or(400);
190            let class = u16_at(os2, 30).unwrap_or(0) >> 8;
191            serif = matches!(class, 1..=5 | 7);
192            let sel = u16_at(os2, 62).unwrap_or(0);
193            italic |= sel & 1 != 0;
194            if let (Some(ta), Some(td), Some(tg)) = (i16_at(os2, 68), i16_at(os2, 70), i16_at(os2, 72)) {
195                if sel & 0x80 != 0 || (asc == 0 && desc == 0) {
196                    (asc, desc, gap) = (ta, td, tg);
197                }
198            }
199            if u16_at(os2, 0).unwrap_or(0) >= 2 {
200                xh = i16_at(os2, 86).unwrap_or(0);
201                cap = i16_at(os2, 88).unwrap_or(0);
202            }
203        }
204        if cap <= 0 {
205            cap = (asc as i32 * 7 / 10) as i16;
206        }
207        if xh <= 0 {
208            xh = (asc as i32 / 2) as i16;
209        }
210        let mut fixed = false;
211        if let Some(post) = self.table(b"post") {
212            let a = u32_at(post, 4).unwrap_or(0) as i32;
213            italic_angle = a as f64 / 65536.0;
214            fixed = u32_at(post, 12).unwrap_or(0) != 0;
215        }
216        italic |= italic_angle != 0.0;
217        self.no_subset = no_subset;
218        self.italic_angle = italic_angle;
219        self.ps_name = self.postscript_name();
220        self.upem = upem;
221        self.glyphs = glyphs;
222        self.advances = advances;
223        self.bbox = bbox;
224        self.flags = 4 | if fixed { 1 } else { 0 } | if serif { 2 } else { 0 } | if italic { 64 } else { 0 };
225        self.stem_v = ((10.0 + 220.0 * (weight.clamp(50, 1000) as f64 - 50.0) / 900.0) + 0.5) as i64 as f64;
226        self.metrics = FontMetrics { units_per_em: upem, ascent: asc, descent: desc, line_gap: gap, cap_height: cap, x_height: xh, glyphs };
227        Ok(())
228    }
229
230    /// name ID 6, only the characters a PDF name and PostScript allow
231    fn postscript_name(&self) -> Vec<u8> {
232        let mut out = Vec::new();
233        if let Some(t) = self.table(b"name") {
234            let count = u16_at(t, 2).unwrap_or(0) as usize;
235            let strings = u16_at(t, 4).unwrap_or(0) as usize;
236            let mut best: Option<(u8, Vec<u8>)> = None;
237            for i in 0..count {
238                let r = 6 + 12 * i;
239                let (Some(pid), Some(eid), Some(nid), Some(len), Some(off)) = (u16_at(t, r), u16_at(t, r + 2), u16_at(t, r + 6), u16_at(t, r + 8), u16_at(t, r + 10)) else { break };
240                if nid != 6 {
241                    continue;
242                }
243                let Some(raw) = t.get(strings + off as usize..strings + off as usize + len as usize) else { continue };
244                let (rank, s): (u8, Vec<u8>) = match (pid, eid) {
245                    (3, 1) | (0, _) => (0, raw.chunks_exact(2).filter(|c| c[0] == 0).map(|c| c[1]).collect()),
246                    (1, 0) => (1, raw.to_vec()),
247                    _ => continue,
248                };
249                if best.as_ref().is_none_or(|b| rank < b.0) {
250                    best = Some((rank, s));
251                }
252            }
253            if let Some((_, s)) = best {
254                out = s.into_iter().filter(|c| (0x21..=0x7E).contains(c) && !b"[](){}<>/%#".contains(c)).take(63).collect();
255            }
256        }
257        if out.is_empty() {
258            out.extend_from_slice(b"JFLibFont");
259        }
260        out
261    }
262
263    pub(crate) fn advance(&self, gid: u16) -> u16 {
264        self.advances.get(gid as usize).copied().unwrap_or(0)
265    }
266
267    /// a glyph drawn; `unicode`: the text it stands for (the first mapping wins)
268    pub(crate) fn mark(&mut self, gid: u16, unicode: Option<String>) {
269        let e = self.used.entry(gid).or_insert(None);
270        if e.is_none() {
271            *e = unicode;
272        }
273    }
274
275    /// width in thousandths of an em (PDF glyph space)
276    fn width(&self, gid: u16) -> f64 {
277        self.advance(gid) as f64 * 1000.0 / self.upem as f64
278    }
279
280    fn keep(&self) -> Vec<bool> {
281        let mut keep = vec![self.no_subset || self.full; self.glyphs as usize];
282        keep[0] = true;
283        for &g in self.used.keys() {
284            if let Some(k) = keep.get_mut(g as usize) {
285                *k = true;
286            }
287        }
288        keep
289    }
290
291    /// six capitals from the glyphs used (the same glyphs always give the same tag)
292    pub(crate) fn subset_tag(&self) -> [u8; 6] {
293        // the name, head (dates, checksum) and the glyph count tell fonts of one name apart
294        let mut b = Vec::with_capacity(self.used.len() * 2 + self.ps_name.len() + 64);
295        b.extend_from_slice(&self.ps_name);
296        b.extend_from_slice(self.table(b"head").unwrap_or(&[]));
297        b.extend_from_slice(&self.glyphs.to_be_bytes());
298        for &g in self.used.keys() {
299            b.extend_from_slice(&g.to_be_bytes());
300        }
301        let mut h = obj::hash64(0x5044_4654, &b);
302        let mut tag = [0u8; 6];
303        for t in tag.iter_mut() {
304            *t = b'A' + (h % 26) as u8;
305            h /= 26;
306        }
307        tag
308    }
309
310    /// TAG+PostScriptName (the name alone for a font embedded in full)
311    pub(crate) fn base_font(&self) -> Vec<u8> {
312        if self.full {
313            return self.ps_name.clone();
314        }
315        let mut n = self.subset_tag().to_vec();
316        n.push(b'+');
317        n.extend_from_slice(&self.ps_name);
318        n
319    }
320
321    /// the font program for FontFile2 (an sfnt) or FontFile3 /CIDFontType0C (a bare CFF)
322    pub(crate) fn program(&self) -> Result<Vec<u8>, Error> {
323        let keep = self.keep();
324        if self.cff {
325            return cff::subset(self.table(b"CFF ").ok_or(BAD)?, &keep).map_err(Error::Font);
326        }
327        self.truetype_subset(keep)
328    }
329
330    fn truetype_subset(&self, mut keep: Vec<bool>) -> Result<Vec<u8>, Error> {
331        let head = self.table(b"head").ok_or(BAD)?;
332        let loca = self.table(b"loca").ok_or(BAD)?;
333        let glyf = self.table(b"glyf").ok_or(BAD)?;
334        let n = self.glyphs as usize;
335        let long = i16_at(head, 50).ok_or(BAD)? != 0;
336        let mut offs = Vec::with_capacity(n + 1);
337        for i in 0..=n {
338            let o = if long { u32_at(loca, 4 * i).ok_or(BAD)? as usize } else { u16_at(loca, 2 * i).ok_or(BAD)? as usize * 2 };
339            offs.push(o);
340        }
341        let range = |g: usize| -> Option<(usize, usize)> {
342            let (s, e) = (offs[g], offs[g + 1]);
343            // a glyph whose end comes before its start is empty (as readers treat it)
344            if s <= e && e <= glyf.len() { Some((s, e)) } else if s > e { Some((0, 0)) } else { None }
345        };
346        // composite glyphs need their components
347        let mut work: Vec<usize> = (0..n).filter(|&g| keep[g]).collect();
348        while let Some(g) = work.pop() {
349            let (s, e) = range(g).ok_or(BAD)?;
350            let gl = &glyf[s..e];
351            if gl.len() < 10 || i16_at(gl, 0).ok_or(BAD)? >= 0 {
352                continue;
353            }
354            let mut p = 10;
355            loop {
356                let flags = u16_at(gl, p).ok_or(BAD)?;
357                let comp = u16_at(gl, p + 2).ok_or(BAD)? as usize;
358                if comp >= n {
359                    return Err(BAD);
360                }
361                if !keep[comp] {
362                    keep[comp] = true;
363                    work.push(comp);
364                }
365                p += 4 + if flags & 1 != 0 { 4 } else { 2 };
366                p += if flags & 8 != 0 {
367                    2
368                } else if flags & 0x40 != 0 {
369                    4
370                } else if flags & 0x80 != 0 {
371                    8
372                } else {
373                    0
374                };
375                if flags & 0x20 == 0 {
376                    break;
377                }
378            }
379        }
380        let mut new_glyf = Vec::new();
381        let mut new_loca = Vec::with_capacity((n + 1) * 4);
382        for (g, &k) in keep.iter().enumerate() {
383            new_loca.extend_from_slice(&(new_glyf.len() as u32).to_be_bytes());
384            if k {
385                let (s, e) = range(g).ok_or(BAD)?;
386                new_glyf.extend_from_slice(&glyf[s..e]);
387                while new_glyf.len() % 4 != 0 {
388                    new_glyf.push(0);
389                }
390            }
391        }
392        new_loca.extend_from_slice(&(new_glyf.len() as u32).to_be_bytes());
393        let mut new_head = head.to_vec();
394        if new_head.len() < 54 {
395            return Err(BAD);
396        }
397        new_head[8..12].copy_from_slice(&[0; 4]);
398        new_head[50..52].copy_from_slice(&1u16.to_be_bytes());
399        // hmtx with the unused glyphs' metrics zeroed
400        let hhea = self.table(b"hhea").ok_or(BAD)?;
401        let nhm = u16_at(hhea, 34).ok_or(BAD)? as usize;
402        let mut hmtx = self.table(b"hmtx").ok_or(BAD)?[..nhm * 4 + (n - nhm) * 2].to_vec();
403        for (g, &k) in keep.iter().enumerate() {
404            if !k {
405                let (o, l) = if g < nhm { (4 * g, 4) } else { (nhm * 4 + (g - nhm) * 2, 2) };
406                hmtx[o..o + l].fill(0);
407            }
408        }
409        let mut post = Vec::with_capacity(32);
410        match self.table(b"post") {
411            Some(p) if p.len() >= 32 => post.extend_from_slice(&p[..32]),
412            _ => post.resize(32, 0),
413        }
414        post[..4].copy_from_slice(&0x0003_0000u32.to_be_bytes());
415        // a cmap that maps nothing: CIDFontType2 selects glyphs by CIDToGIDMap
416        let cmap: Vec<u8> = [0u16, 1, 3, 1, 0, 12, 4, 24, 0, 2, 2, 0, 0, 0xFFFF, 0, 0xFFFF, 1, 0].iter().flat_map(|v| v.to_be_bytes()).collect();
417        let mut tables: Vec<([u8; 4], Vec<u8>)> = vec![
418            (*b"head", new_head),
419            (*b"hhea", hhea.to_vec()),
420            (*b"maxp", self.table(b"maxp").ok_or(BAD)?.to_vec()),
421            (*b"hmtx", hmtx),
422            (*b"loca", new_loca),
423            (*b"glyf", new_glyf),
424            (*b"post", post),
425            (*b"cmap", cmap),
426        ];
427        for tag in [b"cvt ", b"fpgm", b"prep", b"OS/2", b"name", b"gasp"] {
428            if let Some(t) = self.table(tag) {
429                tables.push((*tag, t.to_vec()));
430            }
431        }
432        Ok(write_sfnt(0x0001_0000, tables))
433    }
434
435    /// the W array of the glyphs used: `[first [w w ...] first [...]]`
436    pub(crate) fn widths(&self) -> Vec<u8> {
437        let mut o = Vec::new();
438        o.push(b'[');
439        if self.full {
440            // every glyph, one run from 0
441            o.extend_from_slice(b"0 [");
442            for g in 0..self.glyphs {
443                if g > 0 {
444                    o.push(b' ');
445                }
446                num(&mut o, self.width(g));
447            }
448            o.extend_from_slice(b"]]");
449            return o;
450        }
451        let mut prev: Option<u16> = None;
452        for &g in self.used.keys().chain(core::iter::once(&0)).collect::<alloc::collections::BTreeSet<_>>() {
453            if prev.is_some_and(|p| p + 1 == g) {
454                o.push(b' ');
455            } else {
456                if prev.is_some() {
457                    o.extend_from_slice(b"] ");
458                }
459                obj::int(&mut o, g as i64);
460                o.extend_from_slice(b" [");
461            }
462            num(&mut o, self.width(g));
463            prev = Some(g);
464        }
465        o.extend_from_slice(b"]]");
466        o
467    }
468
469    /// the FontDescriptor's entries (without FontFile)
470    pub(crate) fn descriptor(&self, o: &mut Vec<u8>) {
471        let s = 1000.0 / self.upem as f64;
472        o.extend_from_slice(b"/Type /FontDescriptor /FontName ");
473        obj::name(o, &self.base_font());
474        o.extend_from_slice(b" /Flags ");
475        obj::int(o, self.flags as i64);
476        o.extend_from_slice(b" /FontBBox ");
477        obj::nums(o, &[self.bbox[0] as f64 * s, self.bbox[1] as f64 * s, self.bbox[2] as f64 * s, self.bbox[3] as f64 * s]);
478        o.extend_from_slice(b" /ItalicAngle ");
479        num(o, self.italic_angle);
480        o.extend_from_slice(b" /Ascent ");
481        num(o, self.metrics.ascent as f64 * s);
482        o.extend_from_slice(b" /Descent ");
483        num(o, self.metrics.descent as f64 * s);
484        o.extend_from_slice(b" /CapHeight ");
485        num(o, self.metrics.cap_height as f64 * s);
486        o.extend_from_slice(b" /XHeight ");
487        num(o, self.metrics.x_height as f64 * s);
488        o.extend_from_slice(b" /StemV ");
489        num(o, self.stem_v);
490    }
491
492    /// the ToUnicode CMap of the glyphs that stand for text
493    pub(crate) fn to_unicode(&self) -> Vec<u8> {
494        let mut o = Vec::new();
495        o.extend_from_slice(
496            b"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
497/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n\
498/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n\
4991 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
500        );
501        let maps: Vec<(u16, Vec<u8>)> = self
502            .used
503            .iter()
504            .filter_map(|(&g, t)| t.as_ref().map(|t| (g, obj::utf16be(t, 256))))
505            .filter(|(_, u)| !u.is_empty())
506            .collect();
507        for chunk in maps.chunks(100) {
508            obj::int(&mut o, chunk.len() as i64);
509            o.extend_from_slice(b" beginbfchar\n");
510            for (g, u) in chunk {
511                obj::hex(&mut o, &g.to_be_bytes());
512                o.push(b' ');
513                obj::hex(&mut o, u);
514                o.push(b'\n');
515            }
516            o.extend_from_slice(b"endbfchar\n");
517        }
518        o.extend_from_slice(b"endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
519        o
520    }
521}
522
523fn checksum(d: &[u8]) -> u32 {
524    let mut s = 0u32;
525    for c in d.chunks(4) {
526        let mut b = [0u8; 4];
527        b[..c.len()].copy_from_slice(c);
528        s = s.wrapping_add(u32::from_be_bytes(b));
529    }
530    s
531}
532
533/// an sfnt of the tables (sorted by tag, each 4-byte aligned), head's checkSumAdjustment set
534fn write_sfnt(version: u32, mut tables: Vec<([u8; 4], Vec<u8>)>) -> Vec<u8> {
535    tables.sort_by(|a, b| a.0.cmp(&b.0));
536    let n = tables.len() as u16;
537    let mut sel = 0u16;
538    while (2u16 << sel) <= n {
539        sel += 1;
540    }
541    let range = 16u16 << sel;
542    let mut o = Vec::new();
543    o.extend_from_slice(&version.to_be_bytes());
544    o.extend_from_slice(&n.to_be_bytes());
545    o.extend_from_slice(&range.to_be_bytes());
546    o.extend_from_slice(&sel.to_be_bytes());
547    o.extend_from_slice(&(n * 16 - range).to_be_bytes());
548    let mut off = 12 + 16 * tables.len();
549    let mut head_at = None;
550    for (tag, t) in &tables {
551        o.extend_from_slice(tag);
552        o.extend_from_slice(&checksum(t).to_be_bytes());
553        o.extend_from_slice(&(off as u32).to_be_bytes());
554        o.extend_from_slice(&(t.len() as u32).to_be_bytes());
555        if tag == b"head" {
556            head_at = Some(off);
557        }
558        off += t.len().div_ceil(4) * 4;
559    }
560    for (_, t) in &tables {
561        o.extend_from_slice(t);
562        while o.len() % 4 != 0 {
563            o.push(0);
564        }
565    }
566    if let Some(h) = head_at {
567        let adj = 0xB1B0_AFBAu32.wrapping_sub(checksum(&o));
568        o[h + 8..h + 12].copy_from_slice(&adj.to_be_bytes());
569    }
570    o
571}