1
0
mirror of https://github.com/systemd/systemd.git synced 2024-10-28 03:25:31 +03:00

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.
This commit is contained in:
Filipe Brandenburger 2018-12-06 00:02:51 -08:00
parent dd102e4d0c
commit dc6bf94d68
2 changed files with 9 additions and 15 deletions

View File

@ -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) \

View File

@ -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,