From 953055331117bf5cc0edca464d3038ba38b7fe28 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Wed, 8 Mar 2023 10:00:46 +0100 Subject: [PATCH] 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. --- src/libnm-glib-aux/nm-inet-utils.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/libnm-glib-aux/nm-inet-utils.h b/src/libnm-glib-aux/nm-inet-utils.h index 40ba60c653..572a80c2b1 100644 --- a/src/libnm-glib-aux/nm-inet-utils.h +++ b/src/libnm-glib-aux/nm-inet-utils.h @@ -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) {