Merge pull request #270 from neobrain/bitfield_fixes

Bitfield fixes
This commit is contained in:
Pierre Bourdon
2014-04-14 20:24:01 +02:00
2 changed files with 58 additions and 3 deletions

View File

@ -36,6 +36,8 @@
#include <limits>
#include <type_traits>
#include "Common.h"
/*
* Abstract bitfield class
*
@ -92,13 +94,23 @@
*
* Caveats:
*
* 1)
* BitField provides automatic casting from and to the storage type where
* appropriate. However, when using non-typesafe functions like printf, an
* explicit cast must be performed on the BitField object to make sure it gets
* passed correctly, e.g.:
* printf("Value: %d", (s32)some_register.some_signed_fields);
*
* 2)
* Not really a caveat, but potentially irritating: This class is used in some
* packed structures that do not guarantee proper alignment. Therefore we have
* to use #pragma pack here not to pack the members of the class, but instead
* to break GCC's assumption that the members of the class are aligned on
* sizeof(StorageType).
* TODO(neobrain): Confirm that this is a proper fix and not just masking
* symptoms.
*/
#pragma pack(1)
template<std::size_t position, std::size_t bits, typename T>
struct BitField
{
@ -113,13 +125,13 @@ public:
// so that we can use this within unions
BitField() = default;
BitField& operator=(T val)
__forceinline BitField& operator=(T val)
{
storage = (storage & ~GetMask()) | ((val << position) & GetMask());
return *this;
}
operator T() const
__forceinline operator T() const
{
if (std::numeric_limits<T>::is_signed)
{
@ -144,7 +156,7 @@ private:
// Unsigned version of StorageType
typedef typename std::make_unsigned<StorageType>::type StorageTypeU;
StorageType GetMask() const
__forceinline StorageType GetMask() const
{
return ((~(StorageTypeU)0) >> (8*sizeof(T) - bits)) << position;
}
@ -158,3 +170,4 @@ private:
static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
static_assert(bits > 0, "Invalid number of bits");
};
#pragma pack()