Skip to content

Commit

Permalink
Merge pull request #2544 from signalwire/SWITCH_RAND_MAX
Browse files Browse the repository at this point in the history
[Core] Introduce SWITCH_RAND_MAX to switch_rand()
  • Loading branch information
andywolk authored Jul 29, 2024
2 parents 56981d1 + a99ed5c commit be3c0b3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
7 changes: 7 additions & 0 deletions src/include/switch_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,13 @@ SWITCH_DECLARE_DATA extern switch_filenames SWITCH_GLOBAL_filenames;

#define SWITCH_ACCEPTABLE_INTERVAL(_i) (_i && _i <= SWITCH_MAX_INTERVAL && (_i % 10) == 0)

/* Check if RAND_MAX is a power of 2 minus 1 or in other words all bits set */
#if ((RAND_MAX) & ((RAND_MAX) + 1)) == 0 && (RAND_MAX) != 0
#define SWITCH_RAND_MAX RAND_MAX
#else
#define SWITCH_RAND_MAX 0x7fff
#endif

typedef enum {
SWITCH_RW_READ,
SWITCH_RW_WRITE
Expand Down
8 changes: 4 additions & 4 deletions src/switch_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -4835,8 +4835,8 @@ SWITCH_DECLARE(int) switch_rand(void)

BCryptCloseAlgorithmProvider(hAlgorithm, 0);

/* Make sure we return from 0 to RAND_MAX */
return (random_number & 0x7FFF);
/* Make sure we return from 0 to SWITCH_RAND_MAX */
return (random_number & (SWITCH_RAND_MAX));
#elif defined(__unix__) || defined(__APPLE__)
int random_fd = open("/dev/urandom", O_RDONLY);
ssize_t result;
Expand Down Expand Up @@ -4865,8 +4865,8 @@ SWITCH_DECLARE(int) switch_rand(void)

close(random_fd);

/* Make sure we return from 0 to RAND_MAX */
return (random_number & 0x7FFF);
/* Make sure we return from 0 to SWITCH_RAND_MAX */
return (random_number & (SWITCH_RAND_MAX));
#else
return rand();
#endif
Expand Down

0 comments on commit be3c0b3

Please sign in to comment.