forked from moov-io/iso8583
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary.go
57 lines (50 loc) · 1.22 KB
/
binary.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
// Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package iso8583
import (
"errors"
"fmt"
)
// Binary contains binary value
type Binary struct {
Value []byte
FixLen int
}
// NewBinary create new Binary field
func NewBinary(d []byte) *Binary {
return &Binary{d, -1}
}
// IsEmpty check Binary field for empty value
func (b *Binary) IsEmpty() bool {
return len(b.Value) == 0
}
// Bytes encode Binary field to bytes
func (b *Binary) Bytes(encoder, lenEncoder, l int) ([]byte, error) {
length := l
if b.FixLen != -1 {
length = b.FixLen
}
if length == -1 {
return nil, errors.New(ErrMissingLength)
}
if len(b.Value) > length {
return nil, fmt.Errorf(ErrValueTooLong, "Binary", length, len(b.Value))
}
if len(b.Value) < length {
return append(b.Value, make([]byte, length-len(b.Value))...), nil
}
return b.Value, nil
}
// Load decode Binary field from bytes
func (b *Binary) Load(raw []byte, encoder, lenEncoder, length int) (int, error) {
if length == -1 {
return 0, errors.New(ErrMissingLength)
}
if len(raw) < length {
return 0, errors.New(ErrBadRaw)
}
b.Value = raw[:length]
b.FixLen = length
return length, nil
}