forked from yl2chen/cidranger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
version.go
77 lines (65 loc) · 1.64 KB
/
version.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
package cidranger
import (
"net"
rnet "github.com/yl2chen/cidranger/net"
)
type rangerFactory func(rnet.IPVersion) Ranger
type versionedRanger struct {
ipV4Ranger Ranger
ipV6Ranger Ranger
}
func newVersionedRanger(factory rangerFactory) Ranger {
return &versionedRanger{
ipV4Ranger: factory(rnet.IPv4),
ipV6Ranger: factory(rnet.IPv6),
}
}
func (v *versionedRanger) Insert(entry RangerEntry) error {
network := entry.Network()
ranger, err := v.getRangerForIP(network.IP)
if err != nil {
return err
}
return ranger.Insert(entry)
}
func (v *versionedRanger) Remove(network net.IPNet) (RangerEntry, error) {
ranger, err := v.getRangerForIP(network.IP)
if err != nil {
return nil, err
}
return ranger.Remove(network)
}
func (v *versionedRanger) Contains(ip net.IP) (bool, error) {
ranger, err := v.getRangerForIP(ip)
if err != nil {
return false, err
}
return ranger.Contains(ip)
}
func (v *versionedRanger) ContainingNetworks(ip net.IP) ([]RangerEntry, error) {
ranger, err := v.getRangerForIP(ip)
if err != nil {
return nil, err
}
return ranger.ContainingNetworks(ip)
}
func (v *versionedRanger) CoveredNetworks(network net.IPNet) ([]RangerEntry, error) {
ranger, err := v.getRangerForIP(network.IP)
if err != nil {
return nil, err
}
return ranger.CoveredNetworks(network)
}
// Len returns number of networks in ranger.
func (v *versionedRanger) Len() int {
return v.ipV4Ranger.Len() + v.ipV6Ranger.Len()
}
func (v *versionedRanger) getRangerForIP(ip net.IP) (Ranger, error) {
if ip.To4() != nil {
return v.ipV4Ranger, nil
}
if ip.To16() != nil {
return v.ipV6Ranger, nil
}
return nil, ErrInvalidNetworkNumberInput
}