forked from metal-stack/go-ipam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
91 lines (83 loc) · 2.43 KB
/
json.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
90
91
package ipam
import (
"encoding/json"
"fmt"
)
type prefixJSON struct {
Prefix
Namespace string
AvailableChildPrefixes map[string]bool // available child prefixes of this prefix
// TODO remove this in the next release
ChildPrefixLength int // the length of the child prefixes. Legacy to migrate existing prefixes stored in the db to set the IsParent on reads.
IsParent bool // set to true if there are child prefixes
IPs map[string]bool // The ips contained in this prefix
Version int64 // Version is used for optimistic locking
}
func (p prefixJSON) toPrefix() Prefix {
// Legacy support only on reading from database, convert to isParent.
// TODO remove this in the next release
if p.ChildPrefixLength > 0 {
p.IsParent = true
}
return Prefix{
Cidr: p.Cidr,
ParentCidr: p.ParentCidr,
availableChildPrefixes: p.AvailableChildPrefixes,
childPrefixLength: p.ChildPrefixLength,
isParent: p.IsParent,
ips: p.IPs,
version: p.Version,
}
}
func (p Prefix) toPrefixJSON() prefixJSON {
return prefixJSON{
Prefix: Prefix{
Cidr: p.Cidr,
ParentCidr: p.ParentCidr,
},
AvailableChildPrefixes: p.availableChildPrefixes,
IsParent: p.isParent,
// TODO remove this in the next release
ChildPrefixLength: p.childPrefixLength,
IPs: p.ips,
Version: p.version,
}
}
func (p Prefix) toJSON() ([]byte, error) {
pj, err := json.Marshal(p.toPrefixJSON())
if err != nil {
return nil, fmt.Errorf("unable to marshal prefix:%w", err)
}
return pj, nil
}
func (ps Prefixes) toJSON() ([]byte, error) {
var pfxjs []prefixJSON
for _, p := range ps {
pfxjs = append(pfxjs, p.toPrefixJSON())
}
pj, err := json.Marshal(pfxjs)
if err != nil {
return nil, fmt.Errorf("unable to marshal prefixes:%w", err)
}
return pj, nil
}
func fromJSON(js []byte) (Prefix, error) {
var pre prefixJSON
err := json.Unmarshal(js, &pre)
if err != nil {
return Prefix{}, fmt.Errorf("unable to unmarshal prefix:%w", err)
}
return pre.toPrefix(), nil
}
func fromJSONs(js []byte) (Prefixes, error) {
var pres []prefixJSON
err := json.Unmarshal(js, &pres)
if err != nil {
return Prefixes{}, fmt.Errorf("unable to unmarshal prefixes:%w", err)
}
var pfxs Prefixes
for _, pj := range pres {
pfxs = append(pfxs, pj.toPrefix())
}
return pfxs, nil
}