oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// Package fontstest builds altered TrueType files for tests: a
2// Liberation face with a table added or replaced, or with other
3// embedding flags. Only tests import it.
4package fontstest
5
6import (
7 "encoding/binary"
8 "sort"
9 "testing"
10)
11
12// table is one entry of a TrueType table directory.
13type table struct {
14 tag string
15 body []byte
16}
17
18// tables reads data's table directory.
19func tables(tb testing.TB, data []byte) []table {
20 tb.Helper()
21 if len(data) < 12 {
22 tb.Fatal("fontstest: not a TrueType file")
23 }
24 n := int(binary.BigEndian.Uint16(data[4:]))
25 var out []table
26 for i := 0; i < n; i++ {
27 at := 12 + i*16
28 off := int(binary.BigEndian.Uint32(data[at+8:]))
29 length := int(binary.BigEndian.Uint32(data[at+12:]))
30 if at+16 > len(data) || off+length > len(data) {
31 tb.Fatal("fontstest: table directory runs past the file")
32 }
33 out = append(out, table{string(data[at : at+4]), data[off : off+length]})
34 }
35 return out
36}
37
38// build writes a TrueType file from tables, in tag order, each padded
39// to four bytes. Checksums are left zero: nothing under test reads them.
40func build(version []byte, ts []table) []byte {
41 sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag })
42 head := make([]byte, 12+16*len(ts))
43 copy(head, version)
44 binary.BigEndian.PutUint16(head[4:], uint16(len(ts)))
45 var body []byte
46 for i, t := range ts {
47 at := 12 + i*16
48 copy(head[at:], t.tag)
49 binary.BigEndian.PutUint32(head[at+8:], uint32(len(head)+len(body)))
50 binary.BigEndian.PutUint32(head[at+12:], uint32(len(t.body)))
51 body = append(body, t.body...)
52 for len(body)%4 != 0 {
53 body = append(body, 0)
54 }
55 }
56 return append(head, body...)
57}
58
59// WithTable is data with table tag set to body: replaced when data has
60// one, added when it does not.
61func WithTable(tb testing.TB, data []byte, tag string, body []byte) []byte {
62 tb.Helper()
63 ts := tables(tb, data)
64 replaced := false
65 for i := range ts {
66 if ts[i].tag == tag {
67 ts[i].body, replaced = body, true
68 }
69 }
70 if !replaced {
71 ts = append(ts, table{tag, body})
72 }
73 return build(data[:4], ts)
74}
75
76// WithFsType is data with its OS/2 embedding flags set to fsType.
77func WithFsType(tb testing.TB, data []byte, fsType uint16) []byte {
78 tb.Helper()
79 for _, t := range tables(tb, data) {
80 if t.tag == "OS/2" {
81 os2 := append([]byte(nil), t.body...)
82 binary.BigEndian.PutUint16(os2[8:], fsType)
83 return WithTable(tb, data, "OS/2", os2)
84 }
85 }
86 tb.Fatal("fontstest: no OS/2 table")
87 return nil
88}
89