Debian Codegraph @

Source/Core/Common/BitUtils.h

raw symbols SCIP
1 // Copyright 2017 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <array>
7 #include <bit>
8 #include <climits>
9 #include <cstddef>
10 #include <cstring>
11 #include <initializer_list>
12 #include <span>
13 #include <type_traits>
14 #include <utility>
15
16 #include "Common/CommonTypes.h"
17
18 namespace Common
19 {
20 ///
21 /// Retrieves the size of a type in bits.
22 ///
23 /// @tparam T Type to get the size of.
24 ///
25 /// @return the size of the type in bits.
26 ///
27 template <typename T>
28 constexpr size_t BitSize() noexcept
29 {
30 return sizeof(T) * CHAR_BIT;
31 }
32
33 ///
34 /// Extracts a bit from a value.
35 ///
36 /// @param src The value to extract a bit from.
37 /// @param bit The bit to extract.
38 ///
39 /// @tparam T The type of the value.
40 ///
41 /// @return The extracted bit.
42 ///
43 template <typename T>
44 constexpr T ExtractBit(const T src, const size_t bit) noexcept
45 {
46 return (src >> bit) & static_cast<T>(1);
47 }
48
49 ///
50 /// Extracts a bit from a value.
51 ///
52 /// @param src The value to extract a bit from.
53 ///
54 /// @tparam bit The bit to extract.
55 /// @tparam T The type of the value.
56 ///
57 /// @return The extracted bit.
58 ///
59 template <size_t bit, typename T>
60 constexpr T ExtractBit(const T src) noexcept
61 {
62 static_assert(bit < BitSize<T>(), "Specified bit must be within T's bit width.");
63
64 return ExtractBit(src, bit);
65 }
66
67 ///
68 /// Extracts a range of bits from a value.
69 ///
70 /// @param src The value to extract the bits from.
71 /// @param begin The beginning of the bit range. This is inclusive.
72 /// @param end The ending of the bit range. This is inclusive.
73 ///
74 /// @tparam T The type of the value.
75 /// @tparam Result The returned result type. This is the unsigned analog
76 /// of a signed type if a signed type is passed as T.
77 ///
78 /// @return The extracted bits.
79 ///
80 template <typename T, typename Result = std::make_unsigned_t<T>>
81 constexpr Result ExtractBits(const T src, const size_t begin, const size_t end) noexcept
82 {
83 return static_cast<Result>(((static_cast<Result>(src) << ((BitSize<T>() - 1) - end)) >>
84 (BitSize<T>() - end + begin - 1)));
85 }
86
87 ///
88 /// Extracts a range of bits from a value.
89 ///
90 /// @param src The value to extract the bits from.
91 ///
92 /// @tparam begin The beginning of the bit range. This is inclusive.
93 /// @tparam end The ending of the bit range. This is inclusive.
94 /// @tparam T The type of the value.
95 /// @tparam Result The returned result type. This is the unsigned analog
96 /// of a signed type if a signed type is passed as T.
97 ///
98 /// @return The extracted bits.
99 ///
100 template <size_t begin, size_t end, typename T, typename Result = std::make_unsigned_t<T>>
101 constexpr Result ExtractBits(const T src) noexcept
102 {
103 static_assert(begin < end, "Beginning bit must be less than the ending bit.");
104 static_assert(begin < BitSize<T>(), "Beginning bit is larger than T's bit width.");
105 static_assert(end < BitSize<T>(), "Ending bit is larger than T's bit width.");
106
107 return ExtractBits<T, Result>(src, begin, end);
108 }
109
110 ///
111 /// Verifies whether the supplied value is a valid bit mask of the form 0b00...0011...11.
112 /// Both edge cases of all zeros and all ones are considered valid masks, too.
113 ///
114 /// @param mask The mask value to test for validity.
115 ///
116 /// @tparam T The type of the value.
117 ///
118 /// @return A bool indicating whether the mask is valid.
119 ///
120 template <typename T>
121 constexpr bool IsValidLowMask(const T mask) noexcept
122 {
123 static_assert(std::is_integral_v<T>, "Mask must be an integral type.");
124 static_assert(std::is_unsigned_v<T>, "Signed masks can introduce hard to find bugs.");
125
126 // Can be efficiently determined without looping or bit counting. It's the counterpart
127 // to https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
128 // and doesn't require special casing either edge case.
129 return (mask & (mask + 1)) == 0;
130 }
131
132 template <typename T, typename PtrType>
133 class BitCastPtrType
134 {
135 public:
136 static_assert(std::is_trivially_copyable<PtrType>(),
137 "BitCastPtr source type must be trivially copyable.");
138 static_assert(std::is_trivially_copyable<T>(),
139 "BitCastPtr destination type must be trivially copyable.");
140
141 explicit BitCastPtrType(PtrType* ptr) : m_ptr(ptr) {}
142
143 // Enable operator= only for pointers to non-const data
144 auto& operator=(const T& source) requires(!std::is_const_v<PtrType>)
145 {
146 std::memcpy(m_ptr, &source, sizeof(source));
147 return *this;
148 }
149
150 inline operator T() const
151 {
152 T result;
153 std::memcpy(&result, m_ptr, sizeof(result));
154 return result;
155 }
156
157 inline auto operator[](std::size_t index) const
158 {
159 using S = std::conditional_t<std::is_const<PtrType>::value, const std::byte, std::byte>;
160 S* const target = reinterpret_cast<S*>(m_ptr) + index * sizeof(T);
161 return BitCastPtrType<T, S>{target};
162 }
163
164 private:
165 PtrType* m_ptr;
166 };
167
168 // Provides an aliasing-safe alternative to reinterpret_cast'ing pointers to structs
169 // Conversion constructor and operator= provided for a convenient syntax.
170 // Usage:
171 // MyStruct s = BitCastPtr<MyStruct>(some_ptr);
172 // BitCastPtr<MyStruct>(some_ptr) = s;
173 //
174 // Array example:
175 // BitCastPtr<MyStruct> unaligned_array(unaligned_ptr);
176 // MyStruct s = unaligned_array[2];
177 // unaligned_array[2] = s;
178 template <typename T, typename PtrType>
179 inline auto BitCastPtr(PtrType* ptr) noexcept -> BitCastPtrType<T, PtrType>
180 {
181 return BitCastPtrType<T, PtrType>{ptr};
182 }
183
184 // Similar to BitCastPtr, but specifically for aliasing structs to arrays.
185 template <typename ValueType, typename From>
186 [[nodiscard]] constexpr auto BitCastToArray(const From& obj) noexcept
187 {
188 return std::bit_cast<std::array<ValueType, sizeof(From) / sizeof(ValueType)>>(obj);
189 }
190
191 template <typename T>
192 constexpr void SetBit(T& value, size_t bit_number, bool bit_value)
193 {
194 static_assert(std::is_unsigned<T>(), "SetBit is only sane on unsigned types.");
195
196 if (bit_value)
197 value |= (T{1} << bit_number);
198 else
199 value &= ~(T{1} << bit_number);
200 }
201
202 template <size_t bit_number, typename T>
203 constexpr void SetBit(T& value, bool bit_value)
204 {
205 SetBit(value, bit_number, bit_value);
206 }
207
208 template <typename T>
209 class FlagBit
210 {
211 public:
212 FlagBit(T* bits, std::type_identity_t<T> bit) : m_bits(*bits), m_bit(bit) {}
213 explicit operator bool() const { return (m_bits & m_bit) != 0; }
214 FlagBit& operator=(const bool rhs) requires(!std::is_const_v<T>)
215 {
216 if (rhs)
217 m_bits |= m_bit;
218 else
219 m_bits &= ~m_bit;
220 return *this;
221 }
222
223 private:
224 T& m_bits;
225 const T m_bit;
226 };
227
228 template <typename T>
229 class Flags
230 {
231 public:
232 constexpr Flags() = default;
233 constexpr Flags(std::initializer_list<T> bits)
234 {
235 for (auto bit : bits)
236 {
237 m_hex |= static_cast<std::underlying_type_t<T>>(bit);
238 }
239 }
240 auto operator[](T bit) { return FlagBit(&m_hex, std::to_underlying(bit)); }
241 auto operator[](T bit) const { return FlagBit(&m_hex, std::to_underlying(bit)); }
242
243 std::underlying_type_t<T> m_hex = 0;
244 };
245
246 // Left-shift a value and set new LSBs to that of the supplied LSB.
247 // Converts a value from a N-bit range to an (N+X)-bit range. e.g. 0x101 -> 0x10111
248 template <typename T>
249 T ExpandValue(T value, size_t left_shift_amount)
250 {
251 static_assert(std::is_unsigned<T>(), "ExpandValue is only sane on unsigned types.");
252
253 return (value << left_shift_amount) |
254 (T(-ExtractBit<0>(value)) >> (BitSize<T>() - left_shift_amount));
255 }
256
257 // Convert a contiguous range of a trivially-copyable type to a `span<const u8>`
258 template <std::ranges::contiguous_range T>
259 requires(std::is_trivially_copyable_v<std::ranges::range_value_t<T>>)
260 constexpr auto AsU8Span(const T& range)
261 {
262 return std::span{reinterpret_cast<const u8*>(range.data()), range.size() * sizeof(*range.data())};
263 }
264
265 // Convert a contiguous range of a non-const trivially-copyable type to a `span<u8>`
266 template <std::ranges::contiguous_range T>
267 requires(std::is_trivially_copyable_v<std::ranges::range_value_t<T>>)
268 constexpr auto AsWritableU8Span(T& range)
269 {
270 return std::span{reinterpret_cast<u8*>(range.data()), range.size() * sizeof(*range.data())};
271 }
272
273 // Convert a trivially-copyable object to a `span<const u8>`
274 template <typename T>
275 requires(!std::ranges::contiguous_range<T> && std::is_trivially_copyable_v<T>)
276 constexpr auto AsU8Span(const T& obj)
277 {
278 return std::span{reinterpret_cast<const u8*>(std::addressof(obj)), sizeof(obj)};
279 }
280
281 // Convert a non-const trivially-copyable object to a `span<u8>`
282 template <typename T>
283 requires(!std::ranges::contiguous_range<T> && std::is_trivially_copyable_v<T>)
284 constexpr auto AsWritableU8Span(T& obj)
285 {
286 return std::span{reinterpret_cast<u8*>(std::addressof(obj)), sizeof(obj)};
287 }
288
289 } // namespace Common