-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencoding.go
79 lines (61 loc) · 1.33 KB
/
encoding.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
package encoding
import (
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
type GB18030 []byte
// Encode to GB18030
func (s GB18030) Encode() []byte {
e := simplifiedchinese.GB18030
es, _, err := transform.Bytes(e.NewEncoder(), s)
if err != nil {
return s
}
return es
}
// Decode from GB18030
func (s GB18030) Decode() []byte {
e := simplifiedchinese.GB18030
es, _, err := transform.Bytes(e.NewDecoder(), s)
if err != nil {
return s
}
return es
}
// UCS2 text codec.
type UCS2 []byte
// Encode to UCS2.
func (s UCS2) Encode() []byte {
e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)
es, _, err := transform.Bytes(e.NewEncoder(), s)
if err != nil {
return s
}
return es
}
// Decode from UCS2.
func (s UCS2) Decode() []byte {
e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)
es, _, err := transform.Bytes(e.NewDecoder(), s)
if err != nil {
return s
}
return es
}
func GBK2UCS2(msg []byte) []byte {
// GBK -> UTF-8 -> UCS2
return UCS2(GB18030(msg).Decode()).Encode()
}
func GBK2UTF8(msg []byte) []byte {
return GB18030(msg).Decode()
}
func UTF82GBK(msg []byte) []byte {
return GB18030(msg).Encode()
}
func UTF82UCS2(msg []byte) []byte {
return UCS2(msg).Encode()
}
func UCS22UTF8(msg []byte) []byte {
return UCS2(msg).Decode()
}