...
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
44
45
46
47
48
49
50
51 func decoderune(s string, k int) (r rune, pos int) {
52 pos = k
53
54 if k >= len(s) {
55 return runeError, k + 1
56 }
57
58 s = s[k:]
59
60 switch {
61 case t2 <= s[0] && s[0] < t3:
62
63 if len(s) > 1 && (locb <= s[1] && s[1] <= hicb) {
64 r = rune(s[0]&mask2)<<6 | rune(s[1]&maskx)
65 pos += 2
66 if rune1Max < r {
67 return
68 }
69 }
70 case t3 <= s[0] && s[0] < t4:
71
72 if len(s) > 2 && (locb <= s[1] && s[1] <= hicb) && (locb <= s[2] && s[2] <= hicb) {
73 r = rune(s[0]&mask3)<<12 | rune(s[1]&maskx)<<6 | rune(s[2]&maskx)
74 pos += 3
75 if rune2Max < r && !(surrogateMin <= r && r <= surrogateMax) {
76 return
77 }
78 }
79 case t4 <= s[0] && s[0] < t5:
80
81 if len(s) > 3 && (locb <= s[1] && s[1] <= hicb) && (locb <= s[2] && s[2] <= hicb) && (locb <= s[3] && s[3] <= hicb) {
82 r = rune(s[0]&mask4)<<18 | rune(s[1]&maskx)<<12 | rune(s[2]&maskx)<<6 | rune(s[3]&maskx)
83 pos += 4
84 if rune3Max < r && r <= maxRune {
85 return
86 }
87 }
88 }
89
90 return runeError, k + 1
91 }
92
93
94
95 func encoderune(p []byte, r rune) int {
96
97 switch i := uint32(r); {
98 case i <= rune1Max:
99 p[0] = byte(r)
100 return 1
101 case i <= rune2Max:
102 _ = p[1]
103 p[0] = t2 | byte(r>>6)
104 p[1] = tx | byte(r)&maskx
105 return 2
106 case i > maxRune, surrogateMin <= i && i <= surrogateMax:
107 r = runeError
108 fallthrough
109 case i <= rune3Max:
110 _ = p[2]
111 p[0] = t3 | byte(r>>12)
112 p[1] = tx | byte(r>>6)&maskx
113 p[2] = tx | byte(r)&maskx
114 return 3
115 default:
116 _ = p[3]
117 p[0] = t4 | byte(r>>18)
118 p[1] = tx | byte(r>>12)&maskx
119 p[2] = tx | byte(r>>6)&maskx
120 p[3] = tx | byte(r)&maskx
121 return 4
122 }
123 }
124
View as plain text