Skip to content

Commit f0574a3

Browse files
committed
Refactor comparison function to be branch-free
Refactored the 'cmp' function to use (a > b) - (a < b), making it branch-free and reducing the risk of side-channel attacks caused by branching. Updated the function signature to match "qsort's" expected type, eliminating the need for an explicit cast. Change-Id: I296aa12a57e5b89abc39e6467183c8520c2d1248
1 parent fef71b0 commit f0574a3

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

dudect/fixture.c

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ static int64_t percentile(const int64_t *a_sorted, double which, size_t size)
6767
return a_sorted[pos];
6868
}
6969

70-
static int cmp(const int64_t *a, const int64_t *b)
70+
/* leverages the fact that comparison expressions return 1 or 0. */
71+
static int cmp(const void *aa, const void *bb)
7172
{
72-
if (*a == *b)
73-
return 0;
74-
return (*a - *b) > 0 ? 1 : -1;
73+
int64_t a = *(const int64_t *) aa, b = *(const int64_t *) bb;
74+
return (a > b) - (a < b);
7575
}
7676

7777
/* This function is used to set different thresholds for cropping measurements.
@@ -82,8 +82,7 @@ static int cmp(const int64_t *a, const int64_t *b)
8282
*/
8383
static void prepare_percentiles(int64_t *exec_times, int64_t *percentiles)
8484
{
85-
qsort(exec_times, N_MEASURES, sizeof(int64_t),
86-
(int (*)(const void *, const void *)) cmp);
85+
qsort(exec_times, N_MEASURES, sizeof(int64_t), cmp);
8786

8887
for (size_t i = 0; i < NUM_PERCENTILES; i++) {
8988
percentiles[i] = percentile(

0 commit comments

Comments
 (0)