...
Source file
src/runtime/utf8.go
Documentation: runtime
1
2
3
4
5 package runtime
6
7
8 const (
9 runeError = '\uFFFD'
10 runeSelf = 0x80
11 maxRune = '\U0010FFFF'
12 )
13
14
15 const (
16 surrogateMin = 0xD800
17 surrogateMax = 0xDFFF
18 )
19
20 const (
21 t1 = 0x00
22 tx = 0x80
23 t2 = 0xC0
24 t3 = 0xE0
25 t4 = 0xF0
26 t5 = 0xF8
27
28 maskx = 0x3F
29 mask2 = 0x1F
30 mask3 = 0x0F
31 mask4 = 0x07
32
33 rune1Max = 1<<7 - 1
34 rune2Max = 1<<11 - 1
35 rune3Max = 1<<16 - 1
36
37
38 locb = 0x80
39 hicb = 0xBF
40 )
41
42
43 func countrunes(s string) int {
44 n := 0
45 for range s {
46 n++
47 }
48 return n
49 }
50
51
52
53
54
55
56
57
58
59
60 func decoderune(s string, k int) (r rune, pos int) {
61 pos = k
62
63 if k >= len(s) {
64 return runeError, k + 1
65 }
66
67 s = s[k:]
68
69 switch {
70 case t2 <= s[0] && s[0] < t3:
71
72 if len(s) > 1 && (locb <= s[1] && s[1] <= hicb) {
73 r = rune(s[0]&mask2)<<6 | rune(s[1]&maskx)
74 pos += 2
75 if rune1Max < r {
76 return
77 }
78 }
79 case t3 <= s[0] && s[0] < t4:
80
81 if len(s) > 2 && (locb <= s[1] && s[1] <= hicb) && (locb <= s[2] && s[2] <= hicb) {
82 r = rune(s[0]&mask3)<<12 | rune(s[1]&maskx)<<6 | rune(s[2]&maskx)
83 pos += 3
84 if rune2Max < r && !(surrogateMin <= r && r <= surrogateMax) {
85 return
86 }
87 }
88 case t4 <= s[0] && s[0] < t5:
89
90 if len(s) > 3 && (locb <= s[1] && s[1] <= hicb) && (locb <= s[2] && s[2] <= hicb) && (locb <= s[3] && s[3] <= hicb) {
91 r = rune(s[0]&mask4)<<18 | rune(s[1]&maskx)<<12 | rune(s[2]&maskx)<<6 | rune(s[3]&maskx)
92 pos += 4
93 if rune3Max < r && r <= maxRune {
94 return
95 }
96 }
97 }
98
99 return runeError, k + 1
100 }
101
102
103
104 func encoderune(p []byte, r rune) int {
105
106 switch i := uint32(r); {
107 case i <= rune1Max:
108 p[0] = byte(r)
109 return 1
110 case i <= rune2Max:
111 _ = p[1]
112 p[0] = t2 | byte(r>>6)
113 p[1] = tx | byte(r)&maskx
114 return 2
115 case i > maxRune, surrogateMin <= i && i <= surrogateMax:
116 r = runeError
117 fallthrough
118 case i <= rune3Max:
119 _ = p[2]
120 p[0] = t3 | byte(r>>12)
121 p[1] = tx | byte(r>>6)&maskx
122 p[2] = tx | byte(r)&maskx
123 return 3
124 default:
125 _ = p[3]
126 p[0] = t4 | byte(r>>18)
127 p[1] = tx | byte(r>>12)&maskx
128 p[2] = tx | byte(r>>6)&maskx
129 p[3] = tx | byte(r)&maskx
130 return 4
131 }
132 }
133
View as plain text