| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
| 2 |
/* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
| 3 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* Cast operations to supplement the built-in casting operations. */ |
| 8 |
|
| 9 |
#ifndef mozilla_Casting_h |
| 10 |
#define mozilla_Casting_h |
| 11 |
|
| 12 |
#include "mozilla/Assertions.h" |
| 13 |
#include "mozilla/Sprintf.h" |
| 14 |
|
| 15 |
#include "fmt/format.h" |
| 16 |
|
| 17 |
#include <cinttypes> |
| 18 |
#include <cstring> |
| 19 |
#include <type_traits> |
| 20 |
#include <limits> |
| 21 |
#include <cmath> |
| 22 |
|
| 23 |
namespace mozilla { |
| 24 |
|
| 25 |
/** |
| 26 |
* Sets the outparam value of type |To| with the same underlying bit pattern of |
| 27 |
* |aFrom|. |
| 28 |
* |
| 29 |
* |To| and |From| must be types of the same size; be careful of cross-platform |
| 30 |
* size differences, or this might fail to compile on some but not all |
| 31 |
* platforms. |
| 32 |
* |
| 33 |
* There is also a variant that returns the value directly. In most cases, the |
| 34 |
* two variants should be identical. However, in the specific case of x86 |
| 35 |
* chips, the behavior differs: returning floating-point values directly is done |
| 36 |
* through the x87 stack, and x87 loads and stores turn signaling NaNs into |
| 37 |
* quiet NaNs... silently. Returning floating-point values via outparam, |
| 38 |
* however, is done entirely within the SSE registers when SSE2 floating-point |
| 39 |
* is enabled in the compiler, which has semantics-preserving behavior you would |
| 40 |
* expect. |
| 41 |
* |
| 42 |
* If preserving the distinction between signaling NaNs and quiet NaNs is |
| 43 |
* important to you, you should use the outparam version. In all other cases, |
| 44 |
* you should use the direct return version. |
| 45 |
*/ |
| 46 |
template <typename To, typename From> |
| 47 |
inline void BitwiseCast(const From aFrom, To* aResult) { |
| 48 |
static_assert(sizeof(From) == sizeof(To), |
| 49 |
"To and From must have the same size"); |
| 50 |
|
| 51 |
// We could maybe downgrade these to std::is_trivially_copyable, but the |
| 52 |
// various STLs we use don't all provide it. |
| 53 |
static_assert(std::is_trivial<From>::value, |
| 54 |
"shouldn't bitwise-copy a type having non-trivial " |
| 55 |
"initialization"); |
| 56 |
static_assert(std::is_trivial<To>::value, |
| 57 |
"shouldn't bitwise-copy a type having non-trivial " |
| 58 |
"initialization"); |
| 59 |
|
| 60 |
std::memcpy(static_cast<void*>(aResult), static_cast<const void*>(&aFrom), |
| 61 |
sizeof(From)); |
| 62 |
} |
| 63 |
|
| 64 |
template <typename To, typename From> |
| 65 |
inline To BitwiseCast(const From aFrom) { |
| 66 |
To temp; |
| 67 |
BitwiseCast<To, From>(aFrom, &temp); |
| 68 |
return temp; |
| 69 |
} |
| 70 |
|
| 71 |
namespace detail { |
| 72 |
|
| 73 |
template <typename T> |
| 74 |
constexpr int64_t safe_integer() { |
| 75 |
static_assert(std::is_floating_point_v<T>); |
| 76 |
return std::pow(2, std::numeric_limits<T>::digits); |
| 77 |
} |
| 78 |
|
| 79 |
template <typename T> |
| 80 |
constexpr uint64_t safe_integer_unsigned() { |
| 81 |
static_assert(std::is_floating_point_v<T>); |
| 82 |
return std::pow(2, std::numeric_limits<T>::digits); |
| 83 |
} |
| 84 |
|
| 85 |
template <typename T> |
| 86 |
const char* TypeToStringFallback(); |
| 87 |
|
| 88 |
template <typename T> |
| 89 |
inline constexpr const char* TypeToString() { |
| 90 |
return TypeToStringFallback<T>(); |
| 91 |
} |
| 92 |
|
| 93 |
#define T2S(type) \ |
| 94 |
template <> \ |
| 95 |
inline constexpr const char* TypeToString<type>() { \ |
| 96 |
return #type; \ |
| 97 |
} |
| 98 |
|
| 99 |
#define T2SF(type) \ |
| 100 |
template <> \ |
| 101 |
inline constexpr const char* TypeToStringFallback<type>() { \ |
| 102 |
return #type; \ |
| 103 |
} |
| 104 |
|
| 105 |
T2S(uint8_t); |
| 106 |
T2S(uint16_t); |
| 107 |
T2S(uint32_t); |
| 108 |
T2S(uint64_t); |
| 109 |
T2S(int8_t); |
| 110 |
T2S(int16_t); |
| 111 |
T2S(int32_t); |
| 112 |
T2S(int64_t); |
| 113 |
T2S(char16_t); |
| 114 |
T2S(char32_t); |
| 115 |
T2SF(int); |
| 116 |
T2SF(unsigned int); |
| 117 |
T2SF(long); |
| 118 |
T2SF(unsigned long); |
| 119 |
T2S(float); |
| 120 |
T2S(double); |
| 121 |
|
| 122 |
#undef T2S |
| 123 |
#undef T2SF |
| 124 |
|
| 125 |
template <typename In, typename Out> |
| 126 |
inline void DiagnosticMessage(In aIn, char aDiagnostic[1024]) { |
| 127 |
if constexpr (std::is_same_v<In, char> || std::is_same_v<In, wchar_t> || |
| 128 |
std::is_same_v<In, char16_t> || std::is_same_v<In, char32_t>) { |
| 129 |
static_assert(sizeof(wchar_t) <= sizeof(int32_t)); |
| 130 |
// Characters types are printed in hexadecimal for two reasons: |
| 131 |
// - to easily debug problems with non-printable characters. |
| 132 |
// - {fmt} refuses to format a string with mixed character type. |
| 133 |
// It's always possible to cast them to int64_t for lossless printing of the |
| 134 |
// value. |
| 135 |
auto [out, size] = fmt::format_to_n( |
| 136 |
aDiagnostic, 1023, |
| 137 |
FMT_STRING("Cannot cast {:x} from {} to {}: out of range"), |
| 138 |
static_cast<int64_t>(aIn), TypeToString<In>(), TypeToString<Out>()); |
| 139 |
*out = 0; |
| 140 |
} else { |
| 141 |
auto [out, size] = fmt::format_to_n( |
| 142 |
aDiagnostic, 1023, |
| 143 |
FMT_STRING("Cannot cast {} from {} to {}: out of range"), aIn, |
| 144 |
TypeToString<In>(), TypeToString<Out>()); |
| 145 |
*out = 0; |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
// This is working around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81676, |
| 150 |
// fixed in gcc-10 |
| 151 |
#pragma GCC diagnostic push |
| 152 |
#pragma GCC diagnostic ignored "-Wunused-but-set-variable" |
| 153 |
template <typename In, typename Out> |
| 154 |
bool IsInBounds(In aIn) { |
| 155 |
constexpr bool inSigned = std::is_signed_v<In>; |
| 156 |
constexpr bool outSigned = std::is_signed_v<Out>; |
| 157 |
constexpr bool bothSigned = inSigned && outSigned; |
| 158 |
constexpr bool bothUnsigned = !inSigned && !outSigned; |
| 159 |
constexpr bool inFloat = std::is_floating_point_v<In>; |
| 160 |
constexpr bool outFloat = std::is_floating_point_v<Out>; |
| 161 |
constexpr bool bothFloat = inFloat && outFloat; |
| 162 |
constexpr bool noneFloat = !inFloat && !outFloat; |
| 163 |
constexpr Out outMax = std::numeric_limits<Out>::max(); |
| 164 |
constexpr Out outMin = std::numeric_limits<Out>::lowest(); |
| 165 |
|
| 166 |
// This selects the widest of two types, and is used to cast throughout. |
| 167 |
using select_widest = std::conditional_t<(sizeof(In) > sizeof(Out)), In, Out>; |
| 168 |
|
| 169 |
if constexpr (bothFloat) { |
| 170 |
if (aIn > select_widest(outMax) || aIn < select_widest(outMin)) { |
| 171 |
return false; |
| 172 |
} |
| 173 |
} |
| 174 |
// Normal casting applies, the floating point number is floored. |
| 175 |
if constexpr (inFloat && !outFloat) { |
| 176 |
static_assert(sizeof(aIn) <= sizeof(int64_t)); |
| 177 |
// Check if the input floating point is larger than the output bounds. This |
| 178 |
// catches situations where the input is a float larger than the max of the |
| 179 |
// output type. |
| 180 |
if (aIn < static_cast<double>(outMin) || |
| 181 |
aIn > static_cast<double>(outMax)) { |
| 182 |
return false; |
| 183 |
} |
| 184 |
// At this point we know that the input can be converted to an integer. |
| 185 |
// Check if it's larger than the bounds of the target integer. |
| 186 |
if (outSigned) { |
| 187 |
int64_t asInteger = static_cast<int64_t>(aIn); |
| 188 |
if (asInteger < outMin || asInteger > outMax) { |
| 189 |
return false; |
| 190 |
} |
| 191 |
} else { |
| 192 |
uint64_t asInteger = static_cast<uint64_t>(aIn); |
| 193 |
if (asInteger > outMax) { |
| 194 |
return false; |
| 195 |
} |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
// Checks if the integer is representable exactly as a floating point value of |
| 200 |
// a specific width. |
| 201 |
if constexpr (!inFloat && outFloat) { |
| 202 |
if constexpr (inSigned) { |
| 203 |
if (aIn < -safe_integer<Out>() || aIn > safe_integer<Out>()) { |
| 204 |
return false; |
| 205 |
} |
| 206 |
} else { |
| 207 |
if (aIn >= safe_integer_unsigned<Out>()) { |
| 208 |
return false; |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
if constexpr (noneFloat) { |
| 214 |
if constexpr (bothUnsigned) { |
| 215 |
if (aIn > select_widest(outMax)) { |
| 216 |
return false; |
| 217 |
} |
| 218 |
} |
| 219 |
if constexpr (bothSigned) { |
| 220 |
if (aIn > select_widest(outMax) || aIn < select_widest(outMin)) { |
| 221 |
return false; |
| 222 |
} |
| 223 |
} |
| 224 |
if constexpr (inSigned && !outSigned) { |
| 225 |
if (aIn < 0 || std::make_unsigned_t<In>(aIn) > outMax) { |
| 226 |
return false; |
| 227 |
} |
| 228 |
} |
| 229 |
if constexpr (!inSigned && outSigned) { |
| 230 |
if (aIn > select_widest(outMax)) { |
| 231 |
return false; |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
return true; |
| 236 |
} |
| 237 |
#pragma GCC diagnostic pop |
| 238 |
|
| 239 |
} // namespace detail |
| 240 |
|
| 241 |
/** |
| 242 |
* Cast a value of type |From| to a value of type |To|, asserting that the cast |
| 243 |
* will be a safe cast per C++ (that is, that |to| is in the range of values |
| 244 |
* permitted for the type |From|). |
| 245 |
* In particular, this will fail if a integer cannot be represented exactly as a |
| 246 |
* floating point value, because it's too large. |
| 247 |
*/ |
| 248 |
template <typename To, typename From> |
| 249 |
inline To AssertedCast(const From aFrom) { |
| 250 |
static_assert(std::is_arithmetic_v<To> && std::is_arithmetic_v<From>); |
| 251 |
#ifdef DEBUG |
| 252 |
if (!detail::IsInBounds<From, To>(aFrom)) { |
| 253 |
char buf[1024]; |
| 254 |
detail::DiagnosticMessage<From, To>(aFrom, buf); |
| 255 |
fprintf(stderr, "AssertedCast error: %s\n", buf); |
| 256 |
MOZ_CRASH(); |
| 257 |
} |
| 258 |
#endif |
| 259 |
return static_cast<To>(aFrom); |
| 260 |
} |
| 261 |
|
| 262 |
/** |
| 263 |
* Cast a value of numeric type |From| to a value of numeric type |To|, release |
| 264 |
* asserting that the cast will be a safe cast per C++ (that is, that |to| is in |
| 265 |
* the range of values permitted for the type |From|). |
| 266 |
* In particular, this will fail if a integer cannot be represented exactly as a |
| 267 |
* floating point value, because it's too large. |
| 268 |
*/ |
| 269 |
template <typename To, typename From> |
| 270 |
inline To ReleaseAssertedCast(const From aFrom) { |
| 271 |
static_assert(std::is_arithmetic_v<To> && std::is_arithmetic_v<From>); |
| 272 |
MOZ_RELEASE_ASSERT((detail::IsInBounds<From, To>(aFrom))); |
| 273 |
return static_cast<To>(aFrom); |
| 274 |
} |
| 275 |
|
| 276 |
/** |
| 277 |
* Cast from type From to type To, clamping to minimum and maximum value of the |
| 278 |
* destination type if needed. |
| 279 |
*/ |
| 280 |
template <typename To, typename From> |
| 281 |
inline To SaturatingCast(const From aFrom) { |
| 282 |
static_assert(std::is_arithmetic_v<To> && std::is_arithmetic_v<From>); |
| 283 |
// This implementation works up to 64-bits integers. |
| 284 |
static_assert(sizeof(From) <= 8 && sizeof(To) <= 8); |
| 285 |
constexpr bool fromFloat = std::is_floating_point_v<From>; |
| 286 |
constexpr bool toFloat = std::is_floating_point_v<To>; |
| 287 |
|
| 288 |
// It's not clear what the caller wants here, it could be round, truncate, |
| 289 |
// closest value, etc. |
| 290 |
static_assert((fromFloat && !toFloat) || (!fromFloat && !toFloat), |
| 291 |
"Handle manually depending on desired behaviour"); |
| 292 |
|
| 293 |
// If the source is floating point and the destination isn't, it can be that |
| 294 |
// casting changes the value unexpectedly. Casting to double and clamping to |
| 295 |
// the max of the destination type is correct, this also handles infinity. |
| 296 |
if constexpr (fromFloat) { |
| 297 |
if (aFrom > static_cast<double>(std::numeric_limits<To>::max())) { |
| 298 |
return std::numeric_limits<To>::max(); |
| 299 |
} |
| 300 |
if (aFrom < static_cast<double>(std::numeric_limits<To>::lowest())) { |
| 301 |
return std::numeric_limits<To>::lowest(); |
| 302 |
} |
| 303 |
return static_cast<To>(aFrom); |
| 304 |
} |
| 305 |
// Source and destination are of opposite signedness |
| 306 |
if constexpr (std::is_signed_v<From> != std::is_signed_v<To>) { |
| 307 |
// Input is negative, output is unsigned, return 0 |
| 308 |
if (std::is_signed_v<From> && aFrom < 0) { |
| 309 |
return 0; |
| 310 |
} |
| 311 |
// At this point the input is positive, cast everything to uint64_t for |
| 312 |
// simplicity and compare |
| 313 |
uint64_t inflated = AssertedCast<uint64_t>(aFrom); |
| 314 |
if (inflated > static_cast<uint64_t>(std::numeric_limits<To>::max())) { |
| 315 |
return std::numeric_limits<To>::max(); |
| 316 |
} |
| 317 |
return static_cast<To>(aFrom); |
| 318 |
} else { |
| 319 |
// Regular case: clamp to destination type range |
| 320 |
if (aFrom > std::numeric_limits<To>::max()) { |
| 321 |
return std::numeric_limits<To>::max(); |
| 322 |
} |
| 323 |
if (aFrom < std::numeric_limits<To>::lowest()) { |
| 324 |
return std::numeric_limits<To>::lowest(); |
| 325 |
} |
| 326 |
return static_cast<To>(aFrom); |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
namespace detail { |
| 331 |
|
| 332 |
template <typename From> |
| 333 |
class LazyAssertedCastT final { |
| 334 |
const From mVal; |
| 335 |
|
| 336 |
public: |
| 337 |
explicit LazyAssertedCastT(const From val) : mVal(val) {} |
| 338 |
|
| 339 |
template <typename To> |
| 340 |
operator To() const { |
| 341 |
return AssertedCast<To>(mVal); |
| 342 |
} |
| 343 |
}; |
| 344 |
|
| 345 |
} // namespace detail |
| 346 |
|
| 347 |
/** |
| 348 |
* Like AssertedCast, but infers |To| for AssertedCast lazily based on usage. |
| 349 |
* > uint8_t foo = LazyAssertedCast(1000); // boom |
| 350 |
*/ |
| 351 |
template <typename From> |
| 352 |
inline auto LazyAssertedCast(const From val) { |
| 353 |
return detail::LazyAssertedCastT<From>(val); |
| 354 |
} |
| 355 |
|
| 356 |
} // namespace mozilla |
| 357 |
|
| 358 |
#endif /* mozilla_Casting_h */ |