-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathebcdic1047.go
84 lines (66 loc) · 2.13 KB
/
ebcdic1047.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
package prefix
import (
"fmt"
"strconv"
"strings"
"github.com/moov-io/iso8583/encoding"
)
var EBCDIC1047 = Prefixers{
Fixed: &ebcdic1047FixedPrefixer{},
L: &ebcdic1047Prefixer{1},
LL: &ebcdic1047Prefixer{2},
LLL: &ebcdic1047Prefixer{3},
LLLL: &ebcdic1047Prefixer{4},
LLLLL: &ebcdic1047Prefixer{5},
LLLLLL: &ebcdic1047Prefixer{6},
}
type ebcdic1047Prefixer struct {
digits int
}
func (p *ebcdic1047Prefixer) EncodeLength(maxLen, dataLen int) ([]byte, error) {
if dataLen > maxLen {
return nil, fmt.Errorf("field length [%d] is larger than maximum [%d]", dataLen, maxLen)
}
if len(strconv.Itoa(dataLen)) > p.digits {
return nil, fmt.Errorf("number of digits in data [%d] exceeds its maximum indicator [%d]", dataLen, p.digits)
}
strLen := fmt.Sprintf("%0*d", p.digits, dataLen)
res, err := encoding.EBCDIC1047.Encode([]byte(strLen))
if err != nil {
return nil, err
}
return res, nil
}
func (p *ebcdic1047Prefixer) DecodeLength(maxLen int, data []byte) (int, int, error) {
if len(data) < p.digits {
return 0, 0, fmt.Errorf("not enough data length [%d] to read [%d] byte digits", len(data), p.digits)
}
decodedData, _, err := encoding.EBCDIC1047.Decode(data[:p.digits], p.digits)
if err != nil {
return 0, 0, err
}
dataLen, err := strconv.Atoi(string(decodedData))
if err != nil {
return 0, 0, fmt.Errorf("length [%s] is not a valid integer length field", string(decodedData))
}
if dataLen > maxLen {
return 0, 0, fmt.Errorf("data length [%d] is larger than maximum [%d]", dataLen, maxLen)
}
return dataLen, p.digits, nil
}
func (p *ebcdic1047Prefixer) Inspect() string {
return fmt.Sprintf("EBCDIC1047.%s", strings.Repeat("L", p.digits))
}
type ebcdic1047FixedPrefixer struct{}
func (p *ebcdic1047FixedPrefixer) EncodeLength(fixLen, dataLen int) ([]byte, error) {
if dataLen != fixLen {
return nil, fmt.Errorf("field length [%d] should be fixed [%d]", dataLen, fixLen)
}
return []byte{}, nil
}
func (p *ebcdic1047FixedPrefixer) DecodeLength(fixLen int, data []byte) (int, int, error) {
return fixLen, 0, nil
}
func (p *ebcdic1047FixedPrefixer) Inspect() string {
return "EBCDIC1047.Fixed"
}