glib-aux: add nm_ip_addr_cmp_for_sort() helper for sorting IP addresses

It's similar to nm_ip_addr_cmp(), but it can be used as an argument
to g_qsort_with_data() to sort a list of NMIPAddr (or in_addr_t or
struct in6_addr).

The address family needs to be given as user-data.
This commit is contained in:
Thomas Haller 2022-07-25 15:36:50 +02:00
parent 76d63c66d7
commit 1f7db38dd7
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 14 additions and 0 deletions

View file

@ -44,6 +44,15 @@ G_STATIC_ASSERT(_nm_alignof(struct in_addr) <= _nm_alignof(NMIPAddr));
G_STATIC_ASSERT(_nm_alignof(struct in6_addr) <= _nm_alignof(NMIPAddr));
G_STATIC_ASSERT(_nm_alignof(NMEtherAddr) <= _nm_alignof(NMIPAddr));
int
nm_ip_addr_cmp_for_sort(gconstpointer a, gconstpointer b, gpointer user_data)
{
/* This is a compare function that can be used for sorting IP addresses.
* Essentially, it calls memcmp(). @user_data must be GINT_TO_POINTER(addr_family).
* @a and @b must be either pointers to in_addr_t, struct in6_addr or NMIPAddr. */
return nm_ip_addr_cmp(GPOINTER_TO_INT(user_data), a, b);
}
/* this initializes a struct in_addr/in6_addr and allows for untrusted
* arguments (like unsuitable @addr_family or @src_len). It's almost safe
* in the sense that it verifies input arguments strictly. Also, it

View file

@ -243,11 +243,16 @@ extern const NMIPAddr nm_ip_addr_zero;
static inline int
nm_ip_addr_cmp(int addr_family, gconstpointer a, gconstpointer b)
{
/* Note that @a and @b are not required to be full NMIPAddr unions.
* Depending on @addr_family, they can also be only in_addr_t or
* struct in6_addr. */
NM_CMP_SELF(a, b);
NM_CMP_DIRECT_MEMCMP(a, b, nm_utils_addr_family_to_size(addr_family));
return 0;
}
int nm_ip_addr_cmp_for_sort(gconstpointer a, gconstpointer b, gpointer user_data);
static inline gboolean
nm_ip_addr_equal(int addr_family, gconstpointer a, gconstpointer b)
{