github.com/fafucoder/cilium@v1.6.11/pkg/cidr/cidr.go (about)

     1  // Copyright 2019 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cidr
    16  
    17  import (
    18  	"fmt"
    19  	"net"
    20  )
    21  
    22  // NewCIDR returns a new CIDR using a net.IPNet
    23  func NewCIDR(ipnet *net.IPNet) *CIDR {
    24  	if ipnet == nil {
    25  		return nil
    26  	}
    27  
    28  	return &CIDR{ipnet}
    29  }
    30  
    31  // CIDR is a network CIDR representation based on net.IPNet
    32  type CIDR struct {
    33  	*net.IPNet
    34  }
    35  
    36  // DeepCopy creates a deep copy of a CIDR
    37  func (n *CIDR) DeepCopy() *CIDR {
    38  	if n == nil {
    39  		return nil
    40  	}
    41  	out := &CIDR{
    42  		&net.IPNet{
    43  			IP:   make([]byte, len(n.IP)),
    44  			Mask: make([]byte, len(n.Mask)),
    45  		},
    46  	}
    47  	copy(out.IP, n.IP)
    48  	copy(out.Mask, n.Mask)
    49  	return out
    50  }
    51  
    52  // ParseCIDR parses the CIDR string using net.ParseCIDR
    53  func ParseCIDR(str string) (*CIDR, error) {
    54  	_, ipnet, err := net.ParseCIDR(str)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	return NewCIDR(ipnet), nil
    59  }
    60  
    61  // MustParseCIDR parses the CIDR string using net.ParseCIDR and panics if the
    62  // CIDR cannot be parsed
    63  func MustParseCIDR(str string) *CIDR {
    64  	c, err := ParseCIDR(str)
    65  	if err != nil {
    66  		panic(fmt.Sprintf("Unable to parse CIDR '%s': %s", str, err))
    67  	}
    68  	return c
    69  }