-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbcd.go
89 lines (73 loc) · 1.71 KB
/
bcd.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
package main
import (
"fmt"
"strings"
"github.com/moov-io/iso8583/prefix"
)
type bcdVarPrefixer struct {
Digits int
}
type bcdFixedPrefixer struct {
}
var BCDPrefixer = prefix.Prefixers{
Fixed: &bcdFixedPrefixer{},
L: &bcdVarPrefixer{2},
LL: &bcdVarPrefixer{2},
LLL: &bcdVarPrefixer{3},
LLLL: &bcdVarPrefixer{4},
}
type bcdEncoder struct{}
var (
// _ encoding.Encoder = (*bcdEncoder)(nil)
BCDEncoder = &bcdEncoder{}
)
func (p *bcdVarPrefixer) EncodeLength(maxLen, dataLen int) ([]byte, error) {
if dataLen > maxLen {
return nil, fmt.Errorf("field length: %d is larger than maximum: %d", dataLen, maxLen)
}
var alloc int
if p.Digits <= 2 {
alloc = 1
} else {
alloc = 2
}
length := make([]byte, alloc)
if alloc == 1 {
length[0] = uint8(dataLen)
} else {
length[0] = byte(dataLen >> 8)
length[1] = uint8(dataLen)
}
return length, nil
}
func (p *bcdVarPrefixer) DecodeLength(maxLen int, data []byte) (int, int, error) {
var alloc int
if p.Digits <= 2 {
alloc = 1
} else {
alloc = 2
}
var dataLen int
if alloc == 1 {
dataLen = int(data[0])
} else {
dataLen = int(data[0])<<8 + int(data[1])
}
return dataLen, alloc, nil
}
func (p *bcdVarPrefixer) Inspect() string {
return fmt.Sprintf("BCD.%s", strings.Repeat("L", p.Digits))
}
func (p *bcdFixedPrefixer) 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
}
// Returns number of characters that should be decoded
func (p *bcdFixedPrefixer) DecodeLength(fixLen int, data []byte) (int, int, error) {
return fixLen, 0, nil
}
func (p *bcdFixedPrefixer) Inspect() string {
return "BCD.Fixed"
}