aboutsummaryrefslogtreecommitdiff
path: root/src/common/bit_util.h
blob: ce916e6162e5b2630b85d2bd2106225f7b46d811 (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
49
50
51
52
53
54
55
56
57
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <bit>
#include <climits>
#include <cstddef>
#include <type_traits>

#include "common/common_types.h"

namespace Common {

/// Gets the size of a specified type T in bits.
template <typename T>
    requires std::is_integral_v<T>
[[nodiscard]] constexpr std::size_t BitSize() {
    return std::size_t(sizeof(T) * CHAR_BIT);
}

template<typename T>
    requires std::is_integral_v<T>
[[nodiscard]] constexpr u32 MostSignificantBit(const T value) {
    return u32(sizeof(T) * CHAR_BIT - 1 - std::countl_zero(value));
}

template<typename T>
    requires std::is_integral_v<T>
[[nodiscard]] constexpr T Log2Floor(const T value) {
    return T(MostSignificantBit<T>(value));
}

template<typename T>
    requires std::is_integral_v<T>
[[nodiscard]] constexpr T Log2Ceil(const T value) {
    const T log2_f = Log2Floor<T>(value);
    return T(log2_f + T((value ^ (T(1ULL) << log2_f)) != T(0ULL)));
}

template <typename T>
    requires std::is_integral_v<T>
[[nodiscard]] T NextPow2(T value) {
    return T(1ULL << (sizeof(T) * CHAR_BIT - std::countl_zero(value - 1U)));
}

template <size_t bit_index, typename T>
    requires std::is_integral_v<T>
[[nodiscard]] constexpr bool Bit(const T value) {
    static_assert(bit_index < BitSize<T>(), "bit_index must be smaller than size of T");
    return ((value >> bit_index) & T(1)) == T(1);
}

} // namespace Common