summaryrefslogtreecommitdiffstats
path: root/include/c/rand/rand/rand_uniform.h
blob: 60ceb4c7fb1c6fa9e41964aa338a7e029d3ed129 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2022 - 2023 Alejandro Colomar <alx@kernel.org>
// SPDX-License-Identifier:  LGPL-3.0-or-later WITH LGPL-3.0-linking-exception


#ifndef INCLUDE_C_RAND_RAND_RAND_UNIFORM_H_
#define INCLUDE_C_RAND_RAND_RAND_UNIFORM_H_


#include <assert.h>
#include <stdint.h>

#include <c/bit/ceil.h>
#include <c/rand/rand/rand.h>


#pragma clang assume_nonnull begin
inline int c_rand_uniform(unsigned int n);
inline int c_rand_interval(unsigned int min, unsigned int max);


inline int
c_rand_uniform(unsigned int n)
{
	unsigned int  r, max, mask;

	static_assert(sizeof(int) == sizeof(uint32_t));

	max = n - 1;
	mask = c_bit_ceil_wrap_32(n) - 1;

	do {
		r = c_rand();
		r &= mask;
	} while (r > max);

	return r;
}


inline int
c_rand_interval(unsigned int min, unsigned int max)
{
	return c_rand_uniform(max - min + 1) + min;
}
#pragma clang assume_nonnull end


#endif  // Header guard