-
Notifications
You must be signed in to change notification settings - Fork 14
/
cidr.go
62 lines (52 loc) · 1.19 KB
/
cidr.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
package egoscale
import (
"bytes"
"encoding/json"
"fmt"
"net"
)
// CIDR represents a nicely JSON serializable net.IPNet
type CIDR struct {
net.IPNet
}
// UnmarshalJSON unmarshals the raw JSON into the MAC address
func (cidr *CIDR) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
c, err := ParseCIDR(s)
if err != nil {
return err
}
*cidr = CIDR{c.IPNet}
return nil
}
// MarshalJSON converts the CIDR to a string representation
func (cidr CIDR) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", cidr)), nil
}
// String returns the string representation of a CIDR
func (cidr CIDR) String() string {
return cidr.IPNet.String()
}
// ParseCIDR parses a CIDR from a string
func ParseCIDR(s string) (*CIDR, error) {
_, net, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
return &CIDR{*net}, nil
}
// MustParseCIDR forces parseCIDR or panics
func MustParseCIDR(s string) *CIDR {
cidr, err := ParseCIDR(s)
if err != nil {
panic(err)
}
return cidr
}
// Equal compare two CIDR
func (cidr CIDR) Equal(c CIDR) bool {
return (cidr.IPNet.IP.Equal(c.IPNet.IP) && bytes.Equal(cidr.IPNet.Mask, c.IPNet.Mask))
}