bit_field.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Licensed under GPLv2 or any later version
  2. // Refer to the license.txt file included.
  3. // Copyright 2014 Tony Wasserka
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above copyright
  12. // notice, this list of conditions and the following disclaimer in the
  13. // documentation and/or other materials provided with the distribution.
  14. // * Neither the name of the owner nor the names of its contributors may
  15. // be used to endorse or promote products derived from this software
  16. // without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #pragma once
  30. #include <cstddef>
  31. #include <limits>
  32. #include <type_traits>
  33. #include "common/common_funcs.h"
  34. #include "common/swap.h"
  35. // Inlining
  36. #ifdef _WIN32
  37. #define FORCE_INLINE __forceinline
  38. #else
  39. #define FORCE_INLINE inline __attribute__((always_inline))
  40. #endif
  41. /*
  42. * Abstract bitfield class
  43. *
  44. * Allows endianness-independent access to individual bitfields within some raw
  45. * integer value. The assembly generated by this class is identical to the
  46. * usage of raw bitfields, so it's a perfectly fine replacement.
  47. *
  48. * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
  49. * raw value, Y is the length in bits of the bitfield. Z is an integer type
  50. * which determines the sign of the bitfield. Z must have the same size as the
  51. * raw integer.
  52. *
  53. *
  54. * General usage:
  55. *
  56. * Create a new union with the raw integer value as a member.
  57. * Then for each bitfield you want to expose, add a BitField member
  58. * in the union. The template parameters are the bit offset and the number
  59. * of desired bits.
  60. *
  61. * Changes in the bitfield members will then get reflected in the raw integer
  62. * value and vice-versa.
  63. *
  64. *
  65. * Sample usage:
  66. *
  67. * union SomeRegister
  68. * {
  69. * u32 hex;
  70. *
  71. * BitField<0,7,u32> first_seven_bits; // unsigned
  72. * BitField<7,8,u32> next_eight_bits; // unsigned
  73. * BitField<3,15,s32> some_signed_fields; // signed
  74. * };
  75. *
  76. * This is equivalent to the little-endian specific code:
  77. *
  78. * union SomeRegister
  79. * {
  80. * u32 hex;
  81. *
  82. * struct
  83. * {
  84. * u32 first_seven_bits : 7;
  85. * u32 next_eight_bits : 8;
  86. * };
  87. * struct
  88. * {
  89. * u32 : 3; // padding
  90. * s32 some_signed_fields : 15;
  91. * };
  92. * };
  93. *
  94. *
  95. * Caveats:
  96. *
  97. * 1)
  98. * BitField provides automatic casting from and to the storage type where
  99. * appropriate. However, when using non-typesafe functions like printf, an
  100. * explicit cast must be performed on the BitField object to make sure it gets
  101. * passed correctly, e.g.:
  102. * printf("Value: %d", (s32)some_register.some_signed_fields);
  103. *
  104. * 2)
  105. * Not really a caveat, but potentially irritating: This class is used in some
  106. * packed structures that do not guarantee proper alignment. Therefore we have
  107. * to use #pragma pack here not to pack the members of the class, but instead
  108. * to break GCC's assumption that the members of the class are aligned on
  109. * sizeof(StorageType).
  110. * TODO(neobrain): Confirm that this is a proper fix and not just masking
  111. * symptoms.
  112. */
  113. #pragma pack(1)
  114. template <std::size_t Position, std::size_t Bits, typename T, typename EndianTag = LETag>
  115. struct BitField {
  116. private:
  117. // UnderlyingType is T for non-enum types and the underlying type of T if
  118. // T is an enumeration. Note that T is wrapped within an enable_if in the
  119. // former case to workaround compile errors which arise when using
  120. // std::underlying_type<T>::type directly.
  121. using UnderlyingType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
  122. std::enable_if<true, T>>::type;
  123. // We store the value as the unsigned type to avoid undefined behaviour on value shifting
  124. using StorageType = std::make_unsigned_t<UnderlyingType>;
  125. using StorageTypeWithEndian = typename AddEndian<StorageType, EndianTag>::type;
  126. public:
  127. /// Constants to allow limited introspection of fields if needed
  128. static constexpr std::size_t position = Position;
  129. static constexpr std::size_t bits = Bits;
  130. static constexpr StorageType mask = (((StorageType)~0) >> (8 * sizeof(T) - bits)) << position;
  131. /**
  132. * Formats a value by masking and shifting it according to the field parameters. A value
  133. * containing several bitfields can be assembled by formatting each of their values and ORing
  134. * the results together.
  135. */
  136. static constexpr FORCE_INLINE StorageType FormatValue(const T& value) {
  137. return ((StorageType)value << position) & mask;
  138. }
  139. /**
  140. * Extracts a value from the passed storage. In most situations prefer use the member functions
  141. * (such as Value() or operator T), but this can be used to extract a value from a bitfield
  142. * union in a constexpr context.
  143. */
  144. static constexpr FORCE_INLINE T ExtractValue(const StorageType& storage) {
  145. if constexpr (std::numeric_limits<UnderlyingType>::is_signed) {
  146. std::size_t shift = 8 * sizeof(T) - bits;
  147. return static_cast<T>(static_cast<UnderlyingType>(storage << (shift - position)) >>
  148. shift);
  149. } else {
  150. return static_cast<T>((storage & mask) >> position);
  151. }
  152. }
  153. // This constructor and assignment operator might be considered ambiguous:
  154. // Would they initialize the storage or just the bitfield?
  155. // Hence, delete them. Use the Assign method to set bitfield values!
  156. BitField(T val) = delete;
  157. BitField& operator=(T val) = delete;
  158. constexpr BitField() noexcept = default;
  159. constexpr BitField(const BitField&) noexcept = default;
  160. constexpr BitField& operator=(const BitField&) noexcept = default;
  161. constexpr BitField(BitField&&) noexcept = default;
  162. constexpr BitField& operator=(BitField&&) noexcept = default;
  163. constexpr operator T() const {
  164. return Value();
  165. }
  166. constexpr void Assign(const T& value) {
  167. storage = (static_cast<StorageType>(storage) & ~mask) | FormatValue(value);
  168. }
  169. constexpr T Value() const {
  170. return ExtractValue(storage);
  171. }
  172. constexpr explicit operator bool() const {
  173. return Value() != 0;
  174. }
  175. private:
  176. StorageTypeWithEndian storage;
  177. static_assert(bits + position <= 8 * sizeof(T), "Bitfield out of range");
  178. // And, you know, just in case people specify something stupid like bits=position=0x80000000
  179. static_assert(position < 8 * sizeof(T), "Invalid position");
  180. static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
  181. static_assert(bits > 0, "Invalid number of bits");
  182. static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable in a BitField");
  183. };
  184. #pragma pack()
  185. template <std::size_t Position, std::size_t Bits, typename T>
  186. using BitFieldBE = BitField<Position, Bits, T, BETag>;