github.com/DataDog/datadog-agent/pkg/security/secl@v0.55.0-devel.0.20240517055856-10c4965fea94/compiler/eval/utils.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the Apache License Version 2.0.
     3  // This product includes software developed at Datadog (https://www.datadoghq.com/).
     4  // Copyright 2016-present Datadog, Inc.
     5  
     6  // Package eval holds eval related files
     7  package eval
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"math/big"
    13  	"net"
    14  )
    15  
    16  // NotOfValue returns the NOT of a value
    17  func NotOfValue(value interface{}) (interface{}, error) {
    18  	switch v := value.(type) {
    19  	case int:
    20  		return ^v, nil
    21  	case string:
    22  		// ensure the not value is different
    23  		if v == "" {
    24  			return "<NOT>", nil
    25  		}
    26  		return "", nil
    27  	case bool:
    28  		return !v, nil
    29  	}
    30  
    31  	return nil, errors.New("value type unknown")
    32  }
    33  
    34  // IPToInt transforms an IP to a big Int
    35  func IPToInt(ip net.IP) (*big.Int, int, error) {
    36  	val := &big.Int{}
    37  	val.SetBytes(ip)
    38  	if len(ip) == net.IPv4len {
    39  		return val, 32, nil
    40  	} else if len(ip) == net.IPv6len {
    41  		return val, 128, nil
    42  	}
    43  	return nil, 0, fmt.Errorf("unsupported address length %d", len(ip))
    44  }
    45  
    46  // IntToIP transforms a big Int to an IP
    47  func IntToIP(ipInt *big.Int, bits int) net.IP {
    48  	ipBytes := ipInt.Bytes()
    49  	ret := make([]byte, bits/8)
    50  	// Pack our IP bytes into the end of the return array,
    51  	// since big.Int.Bytes() removes front zero padding.
    52  	for i := 1; i <= len(ipBytes); i++ {
    53  		ret[len(ret)-i] = ipBytes[len(ipBytes)-i]
    54  	}
    55  	return ret
    56  }
    57  
    58  // KeysOfMap returns a slice of the keys contained in the given map
    59  func KeysOfMap[M ~map[K]V, K comparable, V any](m M) []K {
    60  	r := make([]K, 0, len(m))
    61  	for k := range m {
    62  		r = append(r, k)
    63  	}
    64  	return r
    65  }