-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtable_svg.go
105 lines (91 loc) · 2.36 KB
/
table_svg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package truetype
import (
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"io"
"sort"
"github.com/benoitkugler/textlayout/fonts"
"github.com/benoitkugler/textlayout/fonts/binaryreader"
)
var tagSVG = NewTag('S', 'V', 'G', ' ')
// sorted by startGlyphID
type tableSVG []svgDocumentIndexEntry
func (s tableSVG) glyphData(gid GID) (fonts.GlyphSVG, bool) {
data, ok := s.rawGlyphData(gid)
if !ok {
return fonts.GlyphSVG{}, false
}
// un-compress if needed
if r, err := gzip.NewReader(bytes.NewReader(data)); err == nil {
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err == nil {
data = buf.Bytes()
}
}
return fonts.GlyphSVG{Source: data}, true
}
func (s tableSVG) rawGlyphData(gid GID) ([]byte, bool) {
// binary search
for i, j := 0, len(s); i < j; {
h := i + (j-i)/2
entry := s[h]
if gid < GID(entry.first) {
j = h
} else if GID(entry.last) < gid {
i = h + 1
} else {
return entry.svg, true
}
}
return nil, false
}
type svgDocumentIndexEntry struct {
// svg document
// each glyph description must be written
// in an element with id=glyphXXX
svg []byte
first gid // The first glyph ID in the range described by this index entry.
last gid // The last glyph ID in the range described by this index entry. Must be >= startGlyphID.
}
func parseTableSVG(buf []byte) (tableSVG, error) {
if len(buf) < 6 {
return nil, errors.New("invalid SVG table (EOF)")
}
// version := binary.BigEndian.Uint16(buf)
offset := binary.BigEndian.Uint32(buf[2:])
if len(buf) < int(offset) {
return nil, errors.New("invalid SVG table (invalid offset)")
}
buf = buf[offset:]
r := binaryreader.NewReader(buf)
numEntries, err := r.Uint16()
if err != nil {
return nil, err
}
type docHeader struct {
StartGlyphID, EndGlyphID gid
Offset uint32
Length uint32
}
headers := make([]docHeader, numEntries)
err = r.ReadStruct(&headers)
if err != nil {
return nil, err
}
out := make(tableSVG, numEntries)
for i, header := range headers {
endOffset := header.Offset + header.Length
if int(endOffset) > len(buf) {
return nil, errors.New("invalid SVG table (invalid offset)")
}
out[i].first = header.StartGlyphID
out[i].last = header.EndGlyphID
out[i].svg = buf[header.Offset:endOffset]
}
sort.Slice(out, func(i, j int) bool {
return out[i].first < out[j].first
})
return out, nil
}