Skip to content

Commit

Permalink
timer: add ni_timeout_random() function
Browse files Browse the repository at this point in the history
  • Loading branch information
cfconrad committed Jun 15, 2023
1 parent 4f405a3 commit 424a5b4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/wicked/time.h
Expand Up @@ -100,4 +100,6 @@ extern ni_timeout_t ni_timeout_left(const struct timeval *, const struct timeva

extern ni_bool_t ni_timeval_add_timeout(struct timeval *, ni_timeout_t);

extern ni_timeout_t ni_timeout_random_range(ni_timeout_t min, ni_timeout_t max);

#endif /* WICKED_TIME_H */
31 changes: 31 additions & 0 deletions src/timer.c
Expand Up @@ -430,6 +430,37 @@ ni_timeout_randomize(ni_timeout_t timeout, const ni_int_range_t *jitter)
return rtimeout;
}

ni_timeout_t
ni_timeout_random_range(ni_timeout_t min, ni_timeout_t max)
{
ni_timeout_t randval = 0;
ni_timeout_t range;

if (max <= min)
return min;

if (min >= NI_TIMEOUT_INFINITE || max >= NI_TIMEOUT_INFINITE)
return NI_TIMEOUT_INFINITE;

range = max - min + 1;

if (range > RAND_MAX) {
/*
* Assume the largest number RAND_MAX is INT_MAX,
* even random returns long int (64 or 32bit)...
*/
size_t count = sizeof(ni_timeout_t) / sizeof(int);
size_t i, bits = (sizeof(int) * 8) - 1;

for (i = 0; i < count; i++)
randval |= (ni_timeout_t)random() << (i * bits);
} else {
randval = (ni_timeout_t)random();
}

return min + (randval % range);
}

static ni_timeout_t
ni_timeout_arm_randomized(struct timeval *deadline, ni_timeout_t timeout, const ni_int_range_t *jitter)
{
Expand Down

0 comments on commit 424a5b4

Please sign in to comment.