forked from gogs/gogs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iso2022jp.go
124 lines (109 loc) · 2.2 KB
/
iso2022jp.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package mahonia
import (
"unicode/utf8"
)
// converters for ISO-2022-JP encoding
const esc = 27
func init() {
type jpEncoding int
const (
ascii jpEncoding = iota
jisX0201Roman
jisX0208
)
RegisterCharset(&Charset{
Name: "ISO-2022-JP",
NewDecoder: func() Decoder {
encoding := ascii
return func(p []byte) (c rune, size int, status Status) {
if len(p) == 0 {
return 0, 0, NO_ROOM
}
b := p[0]
if b == esc {
if len(p) < 3 {
return 0, 0, NO_ROOM
}
switch p[1] {
case '(':
switch p[2] {
case 'B':
encoding = ascii
return 0, 3, STATE_ONLY
case 'J':
encoding = jisX0201Roman
return 0, 3, STATE_ONLY
}
case '$':
switch p[2] {
case '@', 'B':
encoding = jisX0208
return 0, 3, STATE_ONLY
}
}
}
switch encoding {
case ascii:
if b > 127 {
return utf8.RuneError, 1, INVALID_CHAR
}
return rune(b), 1, SUCCESS
case jisX0201Roman:
if b > 127 {
return utf8.RuneError, 1, INVALID_CHAR
}
switch b {
case '\\':
return 0xA5, 1, SUCCESS
case '~':
return 0x203E, 1, SUCCESS
}
return rune(b), 1, SUCCESS
case jisX0208:
return jis0208Table.DecodeLow(p)
}
panic("unreachable")
}
},
NewEncoder: func() Encoder {
jis0208Table.Reverse()
encoding := ascii
return func(p []byte, c rune) (size int, status Status) {
if len(p) == 0 {
return 0, NO_ROOM
}
if c < 128 {
if encoding != ascii {
if len(p) < 4 {
return 0, NO_ROOM
}
p[0], p[1], p[2] = esc, '(', 'B'
p[3] = byte(c)
encoding = ascii
return 4, SUCCESS
}
p[0] = byte(c)
return 1, SUCCESS
}
if c > 65535 {
return 0, INVALID_CHAR
}
jis := jis0208Table.FromUnicode[c]
if jis == [2]byte{0, 0} && c != rune(jis0208Table.Data[0][0]) {
return 0, INVALID_CHAR
}
if encoding != jisX0208 {
if len(p) < 3 {
return 0, NO_ROOM
}
p[0], p[1], p[2] = esc, '$', 'B'
encoding = jisX0208
return 3, STATE_ONLY
}
p[0] = jis[0] + 0x21
p[1] = jis[1] + 0x21
return 2, SUCCESS
}
},
})
}