1
2
3
4
5
6 package utf16
7
8
9
10
11
12 const (
13 replacementChar = '\uFFFD'
14 maxRune = '\U0010FFFF'
15 )
16
17 const (
18
19
20
21 surr1 = 0xd800
22 surr2 = 0xdc00
23 surr3 = 0xe000
24
25 surrSelf = 0x10000
26 )
27
28
29
30 func IsSurrogate(r rune) bool {
31 return surr1 <= r && r < surr3
32 }
33
34
35
36
37 func DecodeRune(r1, r2 rune) rune {
38 if surr1 <= r1 && r1 < surr2 && surr2 <= r2 && r2 < surr3 {
39 return (r1-surr1)<<10 | (r2 - surr2) + surrSelf
40 }
41 return replacementChar
42 }
43
44
45
46
47 func EncodeRune(r rune) (r1, r2 rune) {
48 if r < surrSelf || r > maxRune {
49 return replacementChar, replacementChar
50 }
51 r -= surrSelf
52 return surr1 + (r>>10)&0x3ff, surr2 + r&0x3ff
53 }
54
55
56
57 func RuneLen(r rune) int {
58 switch {
59 case 0 <= r && r < surr1, surr3 <= r && r < surrSelf:
60 return 1
61 case surrSelf <= r && r <= maxRune:
62 return 2
63 default:
64 return -1
65 }
66 }
67
68
69 func Encode(s []rune) []uint16 {
70 n := len(s)
71 for _, v := range s {
72 if v >= surrSelf {
73 n++
74 }
75 }
76
77 a := make([]uint16, n)
78 n = 0
79 for _, v := range s {
80 switch RuneLen(v) {
81 case 1:
82 a[n] = uint16(v)
83 n++
84 case 2:
85 r1, r2 := EncodeRune(v)
86 a[n] = uint16(r1)
87 a[n+1] = uint16(r2)
88 n += 2
89 default:
90 a[n] = uint16(replacementChar)
91 n++
92 }
93 }
94 return a[:n]
95 }
96
97
98
99
100 func AppendRune(a []uint16, r rune) []uint16 {
101
102 switch {
103 case 0 <= r && r < surr1, surr3 <= r && r < surrSelf:
104
105 return append(a, uint16(r))
106 case surrSelf <= r && r <= maxRune:
107
108 r1, r2 := EncodeRune(r)
109 return append(a, uint16(r1), uint16(r2))
110 }
111 return append(a, replacementChar)
112 }
113
114
115
116 func Decode(s []uint16) []rune {
117
118
119 buf := make([]rune, 0, 64)
120 return decode(s, buf)
121 }
122
123
124
125 func decode(s []uint16, buf []rune) []rune {
126 for i := 0; i < len(s); i++ {
127 var ar rune
128 switch r := s[i]; {
129 case r < surr1, surr3 <= r:
130
131 ar = rune(r)
132 case surr1 <= r && r < surr2 && i+1 < len(s) &&
133 surr2 <= s[i+1] && s[i+1] < surr3:
134
135 ar = DecodeRune(rune(r), rune(s[i+1]))
136 i++
137 default:
138
139 ar = replacementChar
140 }
141 buf = append(buf, ar)
142 }
143 return buf
144 }
145
View as plain text