20 func (r *Range) String() string {
21 return fmt.Sprintf("%s-%s (%s)", r.First, r.Last, r.Description)
24 // Create a new IP list. The given range must already sorted by the lower IP
25 // in the range. Behaviour is undefined for lists of overlapping ranges.
26 func New(initSorted []Range) *IPList {
32 func (me *IPList) NumRanges() int {
39 // Return the range the given IP is in. Returns nil if no range is found.
40 func (me *IPList) Lookup(ip net.IP) (r *Range) {
44 // TODO: Perhaps all addresses should be converted to IPv6, if the future
45 // of IP is to always be backwards compatible. But this will cost 4x the
46 // memory for IPv4 addresses?
47 if v4 := ip.To4(); v4 != nil {
53 if v6 := ip.To16(); v6 != nil {
59 // Return the range the given IP is in. Returns nil if no range is found.
60 func (me *IPList) lookup(ip net.IP) (r *Range) {
61 // Find the index of the first range for which the following range exceeds
63 i := sort.Search(len(me.ranges), func(i int) bool {
64 if i+1 >= len(me.ranges) {
67 return bytes.Compare(ip, me.ranges[i+1].First) < 0
69 if i == len(me.ranges) {
73 if bytes.Compare(ip, r.First) < 0 || bytes.Compare(ip, r.Last) > 0 {
79 // Parse a line of the PeerGuardian Text Lists (P2P) Format. Returns !ok but
80 // no error if a line doesn't contain a range but isn't erroneous, such as
81 // comment and blank lines.
82 func ParseBlocklistP2PLine(l []byte) (r Range, ok bool, err error) {
83 l = bytes.TrimSpace(l)
84 if len(l) == 0 || bytes.HasPrefix(l, []byte("#")) {
87 colon := bytes.IndexByte(l, ':')
89 err = errors.New("missing colon")
92 hyphen := bytes.IndexByte(l[colon+1:], '-')
94 err = errors.New("missing hyphen")
98 r.Description = string(l[:colon])
99 r.First = net.ParseIP(string(l[colon+1 : hyphen]))
100 r.Last = net.ParseIP(string(l[hyphen+1:]))
101 if r.First == nil || r.Last == nil {