forked from metal-stack/go-ipam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
65 lines (59 loc) · 1.83 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
package ipam
import (
"encoding/json"
"fmt"
)
type prefixJSON struct {
Prefix
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 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
}