зеркало из https://github.com/mozilla/gecko-dev.git
Bug 798179 - Implement To BitwiseCast<To>(From), abstracting the treatment of a value's bits as being of another type. r=froydnj
--HG-- extra : rebase_source : e6c57c10f7035b2654eafdd5fa2b3c5d8882f282
This commit is contained in:
Родитель
6c380ca721
Коммит
38cfd84ad8
|
@ -15,6 +15,27 @@
|
|||
|
||||
namespace mozilla {
|
||||
|
||||
/**
|
||||
* Return a value of type |To|, containing the underlying bit pattern of |from|.
|
||||
*
|
||||
* |To| and |From| must be types of the same size; be careful of cross-platform
|
||||
* size differences, or this might fail to compile on some but not all
|
||||
* platforms.
|
||||
*/
|
||||
template<typename To, typename From>
|
||||
inline To
|
||||
BitwiseCast(const From from)
|
||||
{
|
||||
MOZ_STATIC_ASSERT(sizeof(From) == sizeof(To),
|
||||
"To and From must have the same size");
|
||||
union {
|
||||
From from;
|
||||
To to;
|
||||
} u;
|
||||
u.from = from;
|
||||
return u.to;
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
enum ToSignedness { ToIsSigned, ToIsUnsigned };
|
||||
|
|
|
@ -6,8 +6,33 @@
|
|||
#include "mozilla/Casting.h"
|
||||
#include "mozilla/StandardInteger.h"
|
||||
|
||||
using mozilla::BitwiseCast;
|
||||
using mozilla::detail::IsInBounds;
|
||||
|
||||
template<typename Uint, typename Ulong, bool = (sizeof(Uint) == sizeof(Ulong))>
|
||||
struct UintUlongBitwiseCast;
|
||||
|
||||
template<typename Uint, typename Ulong>
|
||||
struct UintUlongBitwiseCast<Uint, Ulong, true>
|
||||
{
|
||||
static void test() {
|
||||
MOZ_ASSERT(BitwiseCast<Ulong>(Uint(8675309)) == Ulong(8675309));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Uint, typename Ulong>
|
||||
struct UintUlongBitwiseCast<Uint, Ulong, false>
|
||||
{
|
||||
static void test() { }
|
||||
};
|
||||
|
||||
static void
|
||||
TestBitwiseCast()
|
||||
{
|
||||
MOZ_ASSERT(BitwiseCast<int>(int(8675309)) == int(8675309));
|
||||
UintUlongBitwiseCast<unsigned int, unsigned long>::test();
|
||||
}
|
||||
|
||||
static void
|
||||
TestSameSize()
|
||||
{
|
||||
|
@ -74,6 +99,8 @@ TestToSmallerSize()
|
|||
int
|
||||
main()
|
||||
{
|
||||
TestBitwiseCast();
|
||||
|
||||
TestSameSize();
|
||||
TestToBiggerSize();
|
||||
TestToSmallerSize();
|
||||
|
|
Загрузка…
Ссылка в новой задаче