Added bx::narrowCast.

This commit is contained in:
Бранимир Караџић
2024-03-29 16:36:05 -07:00
parent f433d1c4c3
commit 3072cf37df
5 changed files with 131 additions and 101 deletions

View File

@@ -8,9 +8,9 @@
#include <alloca.h> // alloca
#include <stdarg.h> // va_list
#include <stddef.h> // ptrdiff_t
#include <stdint.h> // uint32_t
#include <stdlib.h> // size_t
#include <stddef.h> // ptrdiff_t
#include "platform.h"
#include "config.h"
@@ -214,9 +214,14 @@ namespace bx
template<typename Ty>
constexpr bool isPowerOf2(Ty _a);
/// Returns a value of type To by reinterpreting the object representation of From.
/// Returns a value of type `Ty` by reinterpreting the object representation of `FromT`.
template <typename Ty, typename FromT>
constexpr Ty bit_cast(const FromT& _from);
constexpr Ty bitCast(const FromT& _from);
/// Performs `static_cast` of value `_from`, and in debug build runtime verifies/asserts
/// that the value didn't change.
template<typename Ty, typename FromT>
constexpr Ty narrowCast(const FromT& _from, Location _location = Location::current() );
/// Copy memory block.
///

View File

@@ -6,7 +6,8 @@
#ifndef BX_DEBUG_H_HEADER_GUARD
#define BX_DEBUG_H_HEADER_GUARD
#include "bx.h"
#include <stdint.h> // uint32_t
#include <stdarg.h> // va_list
namespace bx
{

View File

@@ -148,12 +148,28 @@ namespace bx
}
template <typename Ty, typename FromT>
inline constexpr Ty bit_cast(const FromT& _from)
inline constexpr Ty bitCast(const FromT& _from)
{
static_assert(sizeof(Ty) == sizeof(FromT), "Ty and FromT must be the same size.");
static_assert(isTriviallyConstructible<Ty>(), "Destination target must be trivially constructible.");
static_assert(sizeof(Ty) == sizeof(FromT)
, "bx::bitCast failed! Ty and FromT must be the same size."
);
static_assert(isTriviallyConstructible<Ty>()
, "bx::bitCast failed! Destination target must be trivially constructible."
);
Ty to;
bx::memCopy(&to, &_from, sizeof(Ty) );
memCopy(&to, &_from, sizeof(Ty) );
return to;
}
template<typename Ty, typename FromT>
inline constexpr Ty narrowCast(const FromT& _from, Location _location)
{
Ty to = static_cast<Ty>(_from);
BX_ASSERT_LOC(_location, static_cast<FromT>(to) == _from
, "bx::narrowCast failed! Value is truncated!"
);
return to;
}