-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathebcdic.go
62 lines (50 loc) · 1.21 KB
/
ebcdic.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
/**
* Copyright 2019 indece UG (haftungsbeschränkt)
**/
package ebcdic
import (
"errors"
)
const mapLength = 0xFF
// Encode encodes an unicode string to an EBCDIC byte array
func Encode(unicodeStr string, codePage int) ([]byte, error) {
ebcdicMap, ok := mapsUnicodeToEBCDIC[codePage]
if !ok {
return nil, errors.New("Unknown code page")
}
runes := []rune(unicodeStr)
ebcdic := make([]byte, len(runes))
for i, r := range runes {
switch {
case ebcdicMap.HasEuroPatch && r == '€':
// Apply EURO-Patch (character outside of mapLength)
ebcdic[i] = ebcdicMap.EuroChar
break
case r <= mapLength:
ebcdic[i] = ebcdicMap.Map[r]
break
default:
// If outside of map, replace with 0x00
ebcdic[i] = 0x00
break
}
}
return ebcdic, nil
}
// Decode decodes an EBCDIC byte array to an unicode string
func Decode(ebcdic []byte, codePage int) (string, error) {
ebcdicMap, ok := mapsEBCDICToUnicode[codePage]
if !ok {
return "", errors.New("Unknown code page")
}
buf := make([]rune, len(ebcdic))
for i, b := range ebcdic {
if ebcdicMap.HasEuroPatch && b == ebcdicMap.EuroChar {
// Apply Euro-Patch
buf[i] = '€'
} else {
buf[i] = ebcdicMap.Map[b]
}
}
return string(buf), nil
}