OXYGENHUB
◆ main openmsx / src / utils / power_of_two.hh
732 B · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#ifndef POWER_OF_TWO_HH
2
#define POWER_OF_TWO_HH
3
4
#include "narrow.hh"
5
#include <bit>
6
#include <cassert>
7
#include <concepts>
8
#include <cstdint>
9
10
namespace openmsx {
11
12
/**
13
 * A constexpr power_of_two struct for power of two numbers, with compact
14
 * storage and built-in value correctness assertion. Additionally, the compiler
15
 * optimises multiplication / division / modulo operations to bit shifts.
16
 */
17
template<std::unsigned_integral T>
18
struct power_of_two {
19
	constexpr power_of_two(T size)
20
		: exponent(narrow_cast<uint8_t>(std::bit_width(size - 1)))
21
	{
22
		assert(std::has_single_bit(size));
23
	};
24
25
	[[nodiscard]] constexpr operator T() const
26
	{
27
		return T{1} << exponent;
28
	}
29
30
	uint8_t exponent = 0;
31
};
32
33
} // namespace openmsx
34
35
#endif