Line data Source code
1 : #include "testitall.h"
2 : #include <stdio.h>
3 : #include <stdlib.h>
4 : #include <stdint.h>
5 :
6 : /**
7 : * @brief Generates a random number within the specified [start..end] range (inclusive).
8 : *
9 : * Reads 8 bytes from /dev/urandom to obtain a 64-bit unsigned random value.
10 : * The value is then mapped to the given range and stored in the variable pointed to by random_number.
11 : *
12 : * @param random_number Pointer to an unsigned 64-bit integer where the result will be stored
13 : * @param start Beginning of the range (inclusive)
14 : * @param end End of the range (inclusive)
15 : */
16 755989 : Return random_number_generator(
17 : uint64_t *random_number,
18 : uint64_t start,
19 : uint64_t end)
20 : {
21 755989 : Return status = SUCCESS;
22 :
23 755989 : FILE *fp = fopen("/dev/urandom","rb");
24 :
25 755989 : if(fp == NULL)
26 : {
27 0 : echo(STDERR,"Can't open /dev/urandom\n");
28 0 : provide(FAILURE);
29 : }
30 :
31 : uint64_t random_value;
32 :
33 755989 : if(SUCCESS == status)
34 : {
35 755989 : if(fread(&random_value,sizeof(random_value),1,fp)!=1)
36 : {
37 0 : echo(STDERR,"Failed to read from /dev/urandom\n");
38 0 : status = FAILURE;
39 : }
40 : }
41 :
42 755989 : if(fp != NULL)
43 : {
44 755989 : fclose(fp);
45 : }
46 :
47 755989 : if(SUCCESS == status)
48 : {
49 755989 : if(end<start)
50 : {
51 0 : echo(STDERR,"Invalid range: end < start\n");
52 0 : status = FAILURE;
53 : }
54 :
55 755989 : uint64_t range = (end-start)+1;
56 755989 : *random_number = (random_value%range)+start;
57 : }
58 :
59 : #if 0
60 : printf("random:%zu\n",*random_number);
61 : #endif
62 :
63 755989 : provide(status);
64 : }
|