github.com/cilium/statedb@v0.3.2/index/netip.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package index
     5  
     6  import (
     7  	"bytes"
     8  	"net"
     9  	"net/netip"
    10  )
    11  
    12  func NetIP(ip net.IP) Key {
    13  	// Use the 16-byte form to have a constant-size key.
    14  	return bytes.Clone(ip.To16())
    15  }
    16  
    17  func NetIPAddr(addr netip.Addr) Key {
    18  	// Use the 16-byte form to have a constant-size key.
    19  	buf := addr.As16()
    20  	return buf[:]
    21  }
    22  
    23  func NetIPAddrString(s string) (Key, error) {
    24  	addr, err := netip.ParseAddr(s)
    25  	if err != nil {
    26  		return Key{}, err
    27  	}
    28  	return NetIPAddr(addr), nil
    29  }
    30  
    31  func NetIPPrefix(prefix netip.Prefix) Key {
    32  	// Use the 16-byte form plus bits to have a constant-size key.
    33  	addrBytes := prefix.Addr().As16()
    34  	return append(addrBytes[:], uint8(prefix.Bits()))
    35  }
    36  
    37  func NetIPPrefixString(s string) (Key, error) {
    38  	prefix, err := netip.ParsePrefix(s)
    39  	if err != nil {
    40  		return Key{}, err
    41  	}
    42  	return NetIPPrefix(prefix), nil
    43  }