-
Notifications
You must be signed in to change notification settings - Fork 6
/
optladdr.go
66 lines (58 loc) · 1.13 KB
/
optladdr.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
package fields
import (
"bytes"
"fmt"
)
// Optional address
type OptionalAddress struct {
Exist Bool
Addr Address
}
func NewEmptyOptionalAddress() OptionalAddress {
return OptionalAddress{
Exist: CreateBool(false),
Addr: nil,
}
}
func (elm OptionalAddress) Size() uint32 {
if elm.Exist.Check() {
return 1 + AddressSize
} else {
return 1
}
}
func (elm OptionalAddress) Serialize() ([]byte, error) {
var buf = bytes.NewBuffer(nil)
bt1, _ := elm.Exist.Serialize()
buf.Write(bt1)
if elm.Exist.Check() {
bt2, _ := elm.Addr.Serialize()
buf.Write(bt2)
}
return buf.Bytes(), nil
}
func (elm *OptionalAddress) Parse(buf []byte, seek uint32) (uint32, error) {
var e error = nil
if seek >= uint32(len(buf)) {
return 0, fmt.Errorf("[OptionalAddress.Parse] seek out of buf len.")
}
seek, e = elm.Exist.Parse(buf, seek)
if e != nil {
return 0, e
}
if elm.Exist.Check() {
seek, e = elm.Addr.Parse(buf, seek)
if e != nil {
return 0, e
}
}
return seek, nil
}
// display address
func (elm OptionalAddress) ShowReadableOrEmpty() string {
if elm.Exist.Check() {
return elm.Addr.ToReadable()
} else {
return ""
}
}