diff options
Diffstat (limited to 'vendor/github.com/apparentlymart/go-cidr/cidr/wrangling.go')
-rw-r--r-- | vendor/github.com/apparentlymart/go-cidr/cidr/wrangling.go | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/vendor/github.com/apparentlymart/go-cidr/cidr/wrangling.go b/vendor/github.com/apparentlymart/go-cidr/cidr/wrangling.go new file mode 100644 index 0000000..861a5f6 --- /dev/null +++ b/vendor/github.com/apparentlymart/go-cidr/cidr/wrangling.go | |||
@@ -0,0 +1,38 @@ | |||
1 | package cidr | ||
2 | |||
3 | import ( | ||
4 | "fmt" | ||
5 | "math/big" | ||
6 | "net" | ||
7 | ) | ||
8 | |||
9 | func ipToInt(ip net.IP) (*big.Int, int) { | ||
10 | val := &big.Int{} | ||
11 | val.SetBytes([]byte(ip)) | ||
12 | if len(ip) == net.IPv4len { | ||
13 | return val, 32 | ||
14 | } else if len(ip) == net.IPv6len { | ||
15 | return val, 128 | ||
16 | } else { | ||
17 | panic(fmt.Errorf("Unsupported address length %d", len(ip))) | ||
18 | } | ||
19 | } | ||
20 | |||
21 | func intToIP(ipInt *big.Int, bits int) net.IP { | ||
22 | ipBytes := ipInt.Bytes() | ||
23 | ret := make([]byte, bits/8) | ||
24 | // Pack our IP bytes into the end of the return array, | ||
25 | // since big.Int.Bytes() removes front zero padding. | ||
26 | for i := 1; i <= len(ipBytes); i++ { | ||
27 | ret[len(ret)-i] = ipBytes[len(ipBytes)-i] | ||
28 | } | ||
29 | return net.IP(ret) | ||
30 | } | ||
31 | |||
32 | func insertNumIntoIP(ip net.IP, num int, prefixLen int) net.IP { | ||
33 | ipInt, totalBits := ipToInt(ip) | ||
34 | bigNum := big.NewInt(int64(num)) | ||
35 | bigNum.Lsh(bigNum, uint(totalBits-prefixLen)) | ||
36 | ipInt.Or(ipInt, bigNum) | ||
37 | return intToIP(ipInt, totalBits) | ||
38 | } | ||