From: Filipe Brandenburger Date: Thu, 6 Dec 2018 08:02:51 +0000 (-0800) Subject: lldp: simplify compare_func, using ?: to chain comparisons X-Git-Tag: v240~55^2 X-Git-Url: http://git.ipfire.org/?p=thirdparty%2Fsystemd.git;a=commitdiff_plain;h=dc6bf94d68c38bd20d0abb94a4440441e13eaba3 lldp: simplify compare_func, using ?: to chain comparisons The ?: operator is very useful for chaining comparison functions (strcmp, memcmp, CMP), since its behavior is to return the result of the comparison function call if non-zero, or continue evaluating the chain of comparison functions. This simplifies the code in that using a temporary `r` variable to store the function results is no longer necessary and the checks for non-zero to return are no longer needed either, resulting in a typical three-fold reduction to the number of lines in the code. Introduce a new memcmp_nn() to compare two memory buffers in lexicographic order, taking length in consideration. Tested: $ ninja -C build/ test All test cases pass. In particular, test_multiple_neighbors_sorted() in test-lldp would catch regressions introduced by this commit. --- diff --git a/src/basic/util.h b/src/basic/util.h index 85a7a15843c..f009d37d4c6 100644 --- a/src/basic/util.h +++ b/src/basic/util.h @@ -147,6 +147,12 @@ static inline int memcmp_safe(const void *s1, const void *s2, size_t n) { return memcmp(s1, s2, n); } +/* Compare s1 (length n1) with s2 (length n2) in lexicographic order. */ +static inline int memcmp_nn(const void *s1, size_t n1, const void *s2, size_t n2) { + return memcmp_safe(s1, s2, MIN(n1, n2)) + ?: CMP(n1, n2); +} + int on_ac_power(void); #define memzero(x,l) \ diff --git a/src/libsystemd-network/lldp-neighbor.c b/src/libsystemd-network/lldp-neighbor.c index 952197e7149..199d8aee0ac 100644 --- a/src/libsystemd-network/lldp-neighbor.c +++ b/src/libsystemd-network/lldp-neighbor.c @@ -9,6 +9,7 @@ #include "lldp-neighbor.h" #include "missing.h" #include "unaligned.h" +#include "util.h" static void lldp_neighbor_id_hash_func(const LLDPNeighborID *id, struct siphash *state) { siphash24_compress(id->chassis_id, id->chassis_id_size, state); @@ -18,21 +19,8 @@ static void lldp_neighbor_id_hash_func(const LLDPNeighborID *id, struct siphash } int lldp_neighbor_id_compare_func(const LLDPNeighborID *x, const LLDPNeighborID *y) { - int r; - - r = memcmp(x->chassis_id, y->chassis_id, MIN(x->chassis_id_size, y->chassis_id_size)); - if (r != 0) - return r; - - r = CMP(x->chassis_id_size, y->chassis_id_size); - if (r != 0) - return r; - - r = memcmp(x->port_id, y->port_id, MIN(x->port_id_size, y->port_id_size)); - if (r != 0) - return r; - - return CMP(x->port_id_size, y->port_id_size); + return memcmp_nn(x->chassis_id, x->chassis_id_size, y->chassis_id, y->chassis_id_size) + ?: memcmp_nn(x->port_id, x->port_id_size, y->port_id, y->port_id_size); } DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(lldp_neighbor_hash_ops, LLDPNeighborID, lldp_neighbor_id_hash_func, lldp_neighbor_id_compare_func,