bit_field.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. /*
  36. * Abstract bitfield class
  37. *
  38. * Allows endianness-independent access to individual bitfields within some raw
  39. * integer value. The assembly generated by this class is identical to the
  40. * usage of raw bitfields, so it's a perfectly fine replacement.
  41. *
  42. * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
  43. * raw value, Y is the length in bits of the bitfield. Z is an integer type
  44. * which determines the sign of the bitfield. Z must have the same size as the
  45. * raw integer.
  46. *
  47. *
  48. * General usage:
  49. *
  50. * Create a new union with the raw integer value as a member.
  51. * Then for each bitfield you want to expose, add a BitField member
  52. * in the union. The template parameters are the bit offset and the number
  53. * of desired bits.
  54. *
  55. * Changes in the bitfield members will then get reflected in the raw integer
  56. * value and vice-versa.
  57. *
  58. *
  59. * Sample usage:
  60. *
  61. * union SomeRegister
  62. * {
  63. * u32 hex;
  64. *
  65. * BitField<0,7,u32> first_seven_bits; // unsigned
  66. * BitField<7,8,u32> next_eight_bits; // unsigned
  67. * BitField<3,15,s32> some_signed_fields; // signed
  68. * };
  69. *
  70. * This is equivalent to the little-endian specific code:
  71. *
  72. * union SomeRegister
  73. * {
  74. * u32 hex;
  75. *
  76. * struct
  77. * {
  78. * u32 first_seven_bits : 7;
  79. * u32 next_eight_bits : 8;
  80. * };
  81. * struct
  82. * {
  83. * u32 : 3; // padding
  84. * s32 some_signed_fields : 15;
  85. * };
  86. * };
  87. *
  88. *
  89. * Caveats:
  90. *
  91. * 1)
  92. * BitField provides automatic casting from and to the storage type where
  93. * appropriate. However, when using non-typesafe functions like printf, an
  94. * explicit cast must be performed on the BitField object to make sure it gets
  95. * passed correctly, e.g.:
  96. * printf("Value: %d", (s32)some_register.some_signed_fields);
  97. *
  98. * 2)
  99. * Not really a caveat, but potentially irritating: This class is used in some
  100. * packed structures that do not guarantee proper alignment. Therefore we have
  101. * to use #pragma pack here not to pack the members of the class, but instead
  102. * to break GCC's assumption that the members of the class are aligned on
  103. * sizeof(StorageType).
  104. * TODO(neobrain): Confirm that this is a proper fix and not just masking
  105. * symptoms.
  106. */
  107. #pragma pack(1)
  108. template <std::size_t Position, std::size_t Bits, typename T, typename EndianTag = LETag>
  109. struct BitField {
  110. private:
  111. // UnderlyingType is T for non-enum types and the underlying type of T if
  112. // T is an enumeration. Note that T is wrapped within an enable_if in the
  113. // former case to workaround compile errors which arise when using
  114. // std::underlying_type<T>::type directly.
  115. using UnderlyingType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
  116. std::enable_if<true, T>>::type;
  117. // We store the value as the unsigned type to avoid undefined behaviour on value shifting
  118. using StorageType = std::make_unsigned_t<UnderlyingType>;
  119. using StorageTypeWithEndian = typename AddEndian<StorageType, EndianTag>::type;
  120. public:
  121. /// Constants to allow limited introspection of fields if needed
  122. static constexpr std::size_t position = Position;
  123. static constexpr std::size_t bits = Bits;
  124. static constexpr StorageType mask = (((StorageType)~0) >> (8 * sizeof(T) - bits)) << position;
  125. /**
  126. * Formats a value by masking and shifting it according to the field parameters. A value
  127. * containing several bitfields can be assembled by formatting each of their values and ORing
  128. * the results together.
  129. */
  130. [[nodiscard]] static constexpr StorageType FormatValue(const T& value) {
  131. return (static_cast<StorageType>(value) << position) & mask;
  132. }
  133. /**
  134. * Extracts a value from the passed storage. In most situations prefer use the member functions
  135. * (such as Value() or operator T), but this can be used to extract a value from a bitfield
  136. * union in a constexpr context.
  137. */
  138. [[nodiscard]] static constexpr T ExtractValue(const StorageType& storage) {
  139. if constexpr (std::numeric_limits<UnderlyingType>::is_signed) {
  140. std::size_t shift = 8 * sizeof(T) - bits;
  141. return static_cast<T>(static_cast<UnderlyingType>(storage << (shift - position)) >>
  142. shift);
  143. } else {
  144. return static_cast<T>((storage & mask) >> position);
  145. }
  146. }
  147. // This constructor and assignment operator might be considered ambiguous:
  148. // Would they initialize the storage or just the bitfield?
  149. // Hence, delete them. Use the Assign method to set bitfield values!
  150. BitField(T val) = delete;
  151. BitField& operator=(T val) = delete;
  152. constexpr BitField() noexcept = default;
  153. constexpr BitField(const BitField&) noexcept = default;
  154. constexpr BitField& operator=(const BitField&) noexcept = default;
  155. constexpr BitField(BitField&&) noexcept = default;
  156. constexpr BitField& operator=(BitField&&) noexcept = default;
  157. [[nodiscard]] constexpr operator T() const {
  158. return Value();
  159. }
  160. constexpr void Assign(const T& value) {
  161. storage = static_cast<StorageType>((storage & ~mask) | FormatValue(value));
  162. }
  163. [[nodiscard]] constexpr T Value() const {
  164. return ExtractValue(storage);
  165. }
  166. [[nodiscard]] constexpr explicit operator bool() const {
  167. return Value() != 0;
  168. }
  169. private:
  170. StorageTypeWithEndian storage;
  171. static_assert(bits + position <= 8 * sizeof(T), "Bitfield out of range");
  172. // And, you know, just in case people specify something stupid like bits=position=0x80000000
  173. static_assert(position < 8 * sizeof(T), "Invalid position");
  174. static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
  175. static_assert(bits > 0, "Invalid number of bits");
  176. static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable in a BitField");
  177. };
  178. #pragma pack()
  179. template <std::size_t Position, std::size_t Bits, typename T>
  180. using BitFieldBE = BitField<Position, Bits, T, BETag>;