Debian Codegraph @

gbk.go

raw symbols SCIP
1 package mahonia
2
3 // Converters for GBK encoding.
4
5 func init() {
6 RegisterCharset(&Charset{
7 Name: "GBK",
8 NewDecoder: func() Decoder {
9 return decodeGBKRune
10 },
11 NewEncoder: func() Encoder {
12 return encodeGBKRune
13 },
14 })
15 }
16
17 func decodeGBKRune(p []byte) (r rune, size int, status Status) {
18 if len(p) == 0 {
19 status = NO_ROOM
20 return
21 }
22
23 b := p[0]
24 if b < 128 {
25 return rune(b), 1, SUCCESS
26 }
27
28 if len(p) < 2 {
29 status = NO_ROOM
30 return
31 }
32
33 c := uint16(p[0])<<8 + uint16(p[1])
34 r = rune(gbkToUnicode[c])
35 if r == 0 {
36 r = gbkToUnicodeExtra[c]
37 }
38
39 if r != 0 {
40 return r, 2, SUCCESS
41 }
42
43 return 0xfffd, 1, INVALID_CHAR
44 }
45
46 func encodeGBKRune(p []byte, r rune) (size int, status Status) {
47 if len(p) == 0 {
48 status = NO_ROOM
49 return
50 }
51
52 if r < 128 {
53 p[0] = byte(r)
54 return 1, SUCCESS
55 }
56
57 if len(p) < 2 {
58 status = NO_ROOM
59 return
60 }
61
62 var c uint16
63 if r < 0x10000 {
64 c = unicodeToGBK[r]
65 } else {
66 c = unicodeToGBKExtra[r]
67 }
68
69 if c != 0 {
70 p[0] = byte(c >> 8)
71 p[1] = byte(c)
72 return 2, SUCCESS
73 }
74
75 p[0] = 0x1a
76 return 1, INVALID_CHAR
77 }