glib-aux: add NMIPAddrTyped struct for tagging NMIPAddr union

NMIPAddr is a union, so you always need to know the right addr_family.
Often we track the addr_family separately or know it implicitly. Then we
don't need to glue them together.

But also often we need to associate the address_family with the address
union. Add a struct that bundles the NMIPAddr with the addr_family,
making it a tagged union. The benefit is that we now also have one
implementation for equal, cmp and hash-update, instead of reimplementing
them.
This commit is contained in:
Thomas Haller 2023-03-08 10:00:46 +01:00
parent c4a8fce1a7
commit 9530553311
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -15,6 +15,11 @@ typedef union _NMIPAddr {
NMEtherAddr _ether_addr;
} NMIPAddr;
typedef struct _NMIPAddrTyped {
NMIPAddr addr;
gint8 addr_family;
} NMIPAddrTyped;
#define NM_IP_ADDR_INIT \
{ \
.addr_ptr = { 0 } \
@ -138,6 +143,30 @@ nm_ip_addr_from_packed_array(int addr_family, gconstpointer ipaddr_arr, gsize id
/*****************************************************************************/
static inline int
nm_ip_addr_typed_cmp(const NMIPAddrTyped *a, const NMIPAddrTyped *b)
{
NM_CMP_SELF(a, b);
NM_CMP_FIELD(a, b, addr_family);
NM_CMP_DIRECT_MEMCMP(&a->addr, &b->addr, nm_utils_addr_family_to_size(a->addr_family));
return 0;
}
static inline gboolean
nm_ip_addr_typed_equal(const NMIPAddrTyped *a, const NMIPAddrTyped *b)
{
return nm_ip_addr_typed_cmp(a, b) == 0;
}
static inline void
nm_ip_addr_typed_hash_update(NMHashState *h, const NMIPAddrTyped *addr)
{
nm_hash_update_vals(h, addr->addr_family);
nm_hash_update_mem(h, &addr->addr, nm_utils_addr_family_to_size(addr->addr_family));
}
/*****************************************************************************/
static inline guint32
nm_ip4_addr_netmask_to_prefix(in_addr_t subnetmask)
{