Skip to content

Commit

Permalink
refactor, move generic cidr code to lib/cidr.go
Browse files Browse the repository at this point in the history
  • Loading branch information
talhahwahla committed Nov 21, 2023
1 parent 24eb46a commit 3a82aba
Showing 1 changed file with 0 additions and 63 deletions.
63 changes: 0 additions & 63 deletions lib/cmd_tool_aggregate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@ package lib

import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"net"
"os"
"sort"
"strings"

"github.com/spf13/pflag"
Expand Down Expand Up @@ -38,12 +34,6 @@ func (f *CmdToolAggregateFlags) Init() {
)
}

// CIDR represens a Classless Inter-Domain Routing structure.
type CIDR struct {
IP net.IP
Network *net.IPNet
}

// CmdToolAggregate is the common core logic for aggregating IPs, IP ranges and CIDRs.
func CmdToolAggregate(
f CmdToolAggregateFlags,
Expand Down Expand Up @@ -180,59 +170,6 @@ func CmdToolAggregate(
return nil
}

// newCidr creates a newCidr CIDR structure.
func newCidr(s string) *CIDR {
ip, ipnet, err := net.ParseCIDR(s)
if err != nil {
panic(err)
}
return &CIDR{
IP: ip,
Network: ipnet,
}
}

func (c *CIDR) String() string {
return c.Network.String()
}

// MaskLen returns a network mask length.
func (c *CIDR) MaskLen() uint32 {
i, _ := c.Network.Mask.Size()
return uint32(i)
}

// PrefixUint32 returns a prefix.
func (c *CIDR) PrefixUint32() uint32 {
return binary.BigEndian.Uint32(c.IP.To4())
}

// Size returns a size of a CIDR range.
func (c *CIDR) Size() int {
ones, bits := c.Network.Mask.Size()
return int(math.Pow(2, float64(bits-ones)))
}

// list returns a slice of sorted CIDR structures.
func list(s []string) []*CIDR {
out := make([]*CIDR, 0)
for _, c := range s {
out = append(out, newCidr(c))
}
sort.Sort(cidrSort(out))
return out
}

type cidrSort []*CIDR

func (s cidrSort) Len() int { return len(s) }
func (s cidrSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func (s cidrSort) Less(i, j int) bool {
cmp := bytes.Compare(s[i].IP, s[j].IP)
return cmp < 0 || (cmp == 0 && s[i].MaskLen() < s[j].MaskLen())
}

// stripOverlapping returns a slice of CIDR structures with overlapping ranges
// stripped.
func stripOverlapping(s []*CIDR) []*CIDR {
Expand Down

0 comments on commit 3a82aba

Please sign in to comment.