Coverage Report

Created: 2026-11-13 08:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/AK/Random.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2021, the SerenityOS developers.
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include <AK/Random.h>
8
9
namespace AK {
10
11
u32 get_random_uniform(u32 max_bounds)
12
3.92k
{
13
    // If we try to divide all 2**32 numbers into groups of "max_bounds" numbers, we may end up
14
    // with one group that is a bit too small. For this reason, the implementation
15
    // `arc4random() % max_bounds` would be insufficient. Here we compute the first number of
16
    // the first "full group" as 2**32 % max_bounds, and rely on the equivalence
17
    // `2**32 % x == (2**32 - x) % x` to keep calculations in u32 domain:
18
3.92k
    u32 const threshold = static_cast<u32>(-max_bounds) % max_bounds;
19
3.92k
    auto random_value = get_random<u32>();
20
3.92k
    for (int i = 0; i < 20 && random_value < threshold; ++i) {
21
        // By chance we picked a value from the incomplete group. Note that this group has size at
22
        // most 2**31-1, so picking this group has a chance of less than 50%.
23
        // In practice, this means that for the worst possible input, there is still only a
24
        // once-in-a-million chance to get to iteration 20. In theory we should be able to loop
25
        // forever. Here we prefer marginally imperfect random numbers over weird runtime behavior.
26
0
        random_value = get_random<u32>();
27
0
    }
28
3.92k
    return random_value % max_bounds;
29
3.92k
}
30
31
u64 get_random_uniform_64(u64 max_bounds)
32
0
{
33
    // Uses the same algorithm as `get_random_uniform`,
34
    // by replacing u32 with u64.
35
0
    u64 const threshold = static_cast<u64>(-max_bounds) % max_bounds;
36
0
    auto random_value = get_random<u64>();
37
0
    for (int i = 0; i < 20 && random_value < threshold; ++i) {
38
0
        random_value = get_random<u64>();
39
0
    }
40
0
    return random_value % max_bounds;
41
0
}
42
43
}