bit_util.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <bit>
  5. #include <climits>
  6. #include <cstddef>
  7. #include <type_traits>
  8. #include "common/common_types.h"
  9. namespace Common {
  10. /// Gets the size of a specified type T in bits.
  11. template <typename T>
  12. [[nodiscard]] constexpr std::size_t BitSize() {
  13. return sizeof(T) * CHAR_BIT;
  14. }
  15. [[nodiscard]] constexpr u32 MostSignificantBit32(const u32 value) {
  16. return 31U - static_cast<u32>(std::countl_zero(value));
  17. }
  18. [[nodiscard]] constexpr u32 MostSignificantBit64(const u64 value) {
  19. return 63U - static_cast<u32>(std::countl_zero(value));
  20. }
  21. [[nodiscard]] constexpr u32 Log2Floor32(const u32 value) {
  22. return MostSignificantBit32(value);
  23. }
  24. [[nodiscard]] constexpr u32 Log2Floor64(const u64 value) {
  25. return MostSignificantBit64(value);
  26. }
  27. [[nodiscard]] constexpr u32 Log2Ceil32(const u32 value) {
  28. const u32 log2_f = Log2Floor32(value);
  29. return log2_f + static_cast<u32>((value ^ (1U << log2_f)) != 0U);
  30. }
  31. [[nodiscard]] constexpr u32 Log2Ceil64(const u64 value) {
  32. const u64 log2_f = Log2Floor64(value);
  33. return static_cast<u32>(log2_f + static_cast<u64>((value ^ (1ULL << log2_f)) != 0ULL));
  34. }
  35. template <typename T>
  36. requires std::is_unsigned_v<T>
  37. [[nodiscard]] constexpr bool IsPow2(T value) {
  38. return std::has_single_bit(value);
  39. }
  40. template <typename T>
  41. requires std::is_integral_v<T>
  42. [[nodiscard]] T NextPow2(T value) {
  43. return static_cast<T>(1ULL << ((8U * sizeof(T)) - std::countl_zero(value - 1U)));
  44. }
  45. template <size_t bit_index, typename T>
  46. requires std::is_integral_v<T>
  47. [[nodiscard]] constexpr bool Bit(const T value) {
  48. static_assert(bit_index < BitSize<T>(), "bit_index must be smaller than size of T");
  49. return ((value >> bit_index) & T(1)) == T(1);
  50. }
  51. } // namespace Common