github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/mahonia/shiftjis.go (about) 1 package mahonia 2 3 // Converters for the Shift-JIS encoding. 4 5 import ( 6 "unicode/utf8" 7 ) 8 9 func init() { 10 RegisterCharset(&Charset{ 11 Name: "Shift_JIS", 12 Aliases: []string{"MS_Kanji", "csShiftJIS", "SJIS", "ibm-943", "windows-31j", "cp932", "windows-932"}, 13 NewDecoder: func() Decoder { 14 return decodeSJIS 15 }, 16 NewEncoder: func() Encoder { 17 shiftJISOnce.Do(reverseShiftJISTable) 18 return encodeSJIS 19 }, 20 }) 21 } 22 23 func decodeSJIS(p []byte) (c rune, size int, status Status) { 24 if len(p) == 0 { 25 return 0, 0, NO_ROOM 26 } 27 28 b := p[0] 29 if b < 0x80 { 30 return rune(b), 1, SUCCESS 31 } 32 33 if 0xa1 <= b && b <= 0xdf { 34 return rune(b) + (0xff61 - 0xa1), 1, SUCCESS 35 } 36 37 if b == 0x80 || b == 0xa0 { 38 return utf8.RuneError, 1, INVALID_CHAR 39 } 40 41 if len(p) < 2 { 42 return 0, 0, NO_ROOM 43 } 44 45 jis := int(b)<<8 + int(p[1]) 46 c = rune(shiftJISToUnicode[jis]) 47 48 if c == 0 { 49 return utf8.RuneError, 2, INVALID_CHAR 50 } 51 return c, 2, SUCCESS 52 } 53 54 func encodeSJIS(p []byte, c rune) (size int, status Status) { 55 if len(p) == 0 { 56 return 0, NO_ROOM 57 } 58 59 if c < 0x80 { 60 p[0] = byte(c) 61 return 1, SUCCESS 62 } 63 64 if 0xff61 <= c && c <= 0xff9f { 65 // half-width katakana 66 p[0] = byte(c - (0xff61 - 0xa1)) 67 return 1, SUCCESS 68 } 69 70 if len(p) < 2 { 71 return 0, NO_ROOM 72 } 73 74 if c > 0xffff { 75 p[0] = '?' 76 return 1, INVALID_CHAR 77 } 78 79 jis := unicodeToShiftJIS[c] 80 if jis == 0 { 81 p[0] = '?' 82 return 1, INVALID_CHAR 83 } 84 85 p[0] = byte(jis >> 8) 86 p[1] = byte(jis) 87 return 2, SUCCESS 88 }