File: ilog2.cpp

package info (click to toggle)
foonathan-memory 0.7.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,644 kB
  • sloc: cpp: 12,425; xml: 139; sh: 48; makefile: 25
file content (62 lines) | stat: -rw-r--r-- 1,940 bytes parent folder | download
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (C) 2015-2025 Jonathan Müller and foonathan/memory contributors
// SPDX-License-Identifier: Zlib

#include <foonathan/memory/detail/ilog2.hpp>

#include <doctest/doctest.h>

using namespace foonathan::memory;
using namespace detail;

TEST_CASE("detail::ilog2()")
{
    // Check everything up to 2^16.
    for (std::size_t i = 0; i != 16; ++i)
    {
        auto power      = 1u << i;
        auto next_power = 2 * power;
        for (auto x = power; x != next_power; ++x)
            CHECK(ilog2(x) == i);
    }

    // Check some higher values.
    CHECK(ilog2(std::uint64_t(1) << 32) == 32);
    CHECK(ilog2((std::uint64_t(1) << 32) + 44) == 32);
    CHECK(ilog2((std::uint64_t(1) << 32) + 2048) == 32);

    CHECK(ilog2(std::uint64_t(1) << 48) == 48);
    CHECK(ilog2((std::uint64_t(1) << 48) + 44) == 48);
    CHECK(ilog2((std::uint64_t(1) << 48) + 2048) == 48);

    CHECK(ilog2(std::uint64_t(1) << 63) == 63);
    CHECK(ilog2((std::uint64_t(1) << 63) + 44) == 63);
    CHECK(ilog2((std::uint64_t(1) << 63) + 2063) == 63);
}

TEST_CASE("detail::ilog2_ceil()")
{
    // Check everything up to 2^16.
    for (std::size_t i = 0; i != 16; ++i)
    {
        auto power = 1u << i;
        CHECK(ilog2_ceil(power) == i);

        auto next_power = 2 * power;
        for (auto x = power + 1; x != next_power; ++x)
            CHECK(ilog2_ceil(x) == i + 1);
    }

    // Check some higher values.
    CHECK(ilog2_ceil(std::uint64_t(1) << 32) == 32);
    CHECK(ilog2_ceil((std::uint64_t(1) << 32) + 44) == 33);
    CHECK(ilog2_ceil((std::uint64_t(1) << 32) + 2048) == 33);

    CHECK(ilog2_ceil(std::uint64_t(1) << 48) == 48);
    CHECK(ilog2_ceil((std::uint64_t(1) << 48) + 44) == 49);
    CHECK(ilog2_ceil((std::uint64_t(1) << 48) + 2048) == 49);

    CHECK(ilog2_ceil(std::uint64_t(1) << 63) == 63);
    CHECK(ilog2_ceil((std::uint64_t(1) << 63) + 44) == 64);
    CHECK(ilog2_ceil((std::uint64_t(1) << 63) + 2063) == 64);
}