-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw.go
121 lines (108 loc) · 2.23 KB
/
raw.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package goemoji
import (
"bufio"
"embed"
"fmt"
"io"
"strconv"
"strings"
)
func newDictTree() *node {
return &node{NodeMap: make(map[int]*node)}
}
type node struct {
Char int
IsEnd bool
NodeMap map[int]*node
}
func (n *node) addNode(code int, isEnd bool) {
_, ok := n.NodeMap[code]
if !ok {
n.NodeMap[code] = &node{Char: code, NodeMap: make(map[int]*node), IsEnd: isEnd}
}
}
func (n *node) getNode(code int) *node {
node, ok := n.NodeMap[code]
if ok {
return node
}
return nil
}
//go:embed official/emoji-sequences.txt
//go:embed official/emoji-zwj-sequences.txt
var fs embed.FS
func readAllEmoji() (*node, error) {
tree := newDictTree()
seqFile, err := fs.Open("official/emoji-sequences.txt")
if seqFile != nil {
defer seqFile.Close()
}
if err != nil {
return nil, err
}
err = convertOfficialEmoji(seqFile, tree)
if err != nil {
return nil, err
}
zwjFile, err := fs.Open("official/emoji-zwj-sequences.txt")
if zwjFile != nil {
defer zwjFile.Close()
}
if err != nil {
return nil, err
}
err = convertOfficialEmoji(zwjFile, tree)
if err != nil {
return nil, err
}
return tree, nil
}
func convertOfficialEmoji(reader io.Reader, tree *node) error {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
if len(line) > 0 && line[0] != '#' {
line = line[:strings.Index(line, ";")]
line = strings.TrimRight(line, " ")
codeList := strings.Split(line, " ")
if len(codeList) > 0 {
err := handleCodes(codeList, tree)
if err != nil {
return err
}
}
}
}
return nil
}
func handleCodes(codeList []string, root *node) error {
next := root
l := len(codeList)
for i, codeRange := range codeList {
start, end, found := strings.Cut(codeRange, "..")
if found {
if len(codeList) > 1 {
return fmt.Errorf("code range error: %v", codeRange)
}
a, err := strconv.ParseInt(start, 16, 32)
if err != nil {
return err
}
b, err := strconv.ParseInt(end, 16, 32)
if err != nil {
return err
}
for i := a; i <= b; i++ {
next.addNode(int(i), true)
}
} else {
a, err := strconv.ParseInt(start, 16, 32)
if err != nil {
return err
}
next.addNode(int(a), i == l-1)
next = next.getNode(int(a))
}
}
return nil
}