v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
safe_conversions.h
Go to the documentation of this file.
1// Copyright 2014 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Slightly adapted for inclusion in V8.
6// Copyright 2025 the V8 project authors. All rights reserved.
7
8#ifndef V8_BASE_NUMERICS_SAFE_CONVERSIONS_H_
9#define V8_BASE_NUMERICS_SAFE_CONVERSIONS_H_
10
11#include <stddef.h>
12
13#include <cmath>
14#include <concepts>
15#include <limits>
16#include <type_traits>
17
18#include "src/base/numerics/safe_conversions_impl.h" // IWYU pragma: export
19
20#if defined(__ARMEL__) && !defined(__native_client__)
21#include "src/base/numerics/safe_conversions_arm_impl.h" // IWYU pragma: export
22#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1)
23#else
24#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0)
25#endif
26
27namespace v8::base {
28namespace internal {
29
30#if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
31template <typename Dst, typename Src>
32struct SaturateFastAsmOp {
33 static constexpr bool is_supported = false;
34 static constexpr Dst Do(Src) {
35 // Force a compile failure if instantiated.
36 return CheckOnFailure::template HandleFailure<Dst>();
37 }
38};
39#endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
40#undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
41
42// The following special case a few specific integer conversions where we can
43// eke out better performance than range checking.
44template <typename Dst, typename Src>
46 static constexpr bool is_supported = false;
47 static constexpr bool Do(Src) {
48 // Force a compile failure if instantiated.
49 return CheckOnFailure::template HandleFailure<bool>();
50 }
51};
52
53// Signed to signed range comparison.
54template <typename Dst, typename Src>
55 requires(std::signed_integral<Dst> && std::signed_integral<Src> &&
56 !kIsTypeInRangeForNumericType<Dst, Src>)
57struct IsValueInRangeFastOp<Dst, Src> {
58 static constexpr bool is_supported = true;
59
60 static constexpr bool Do(Src value) {
61 // Just downcast to the smaller type, sign extend it back to the original
62 // type, and then see if it matches the original value.
63 return value == static_cast<Dst>(value);
64 }
65};
66
67// Signed to unsigned range comparison.
68template <typename Dst, typename Src>
69 requires(std::unsigned_integral<Dst> && std::signed_integral<Src> &&
70 !kIsTypeInRangeForNumericType<Dst, Src>)
72 static constexpr bool is_supported = true;
73
74 static constexpr bool Do(Src value) {
75 // We cast a signed as unsigned to overflow negative values to the top,
76 // then compare against whichever maximum is smaller, as our upper bound.
78 }
79};
80
81// Convenience function that returns true if the supplied value is in range
82// for the destination type.
83template <typename Dst, typename Src>
84 requires(IsNumeric<Src> && std::is_arithmetic_v<Dst> &&
85 std::numeric_limits<Dst>::lowest() < std::numeric_limits<Dst>::max())
86constexpr bool IsValueInRangeForNumericType(Src value) {
87 using SrcType = UnderlyingType<Src>;
88 const auto underlying_value = static_cast<SrcType>(value);
91 underlying_value)
93 .IsValid();
94}
95
96// checked_cast<> is analogous to static_cast<> for numeric types,
97// except that it CHECKs that the specified numeric conversion will not
98// overflow or underflow. NaN source will always trigger a CHECK.
99template <typename Dst, class CheckHandler = internal::CheckOnFailure,
100 typename Src>
101 requires(IsNumeric<Src> && std::is_arithmetic_v<Dst> &&
102 std::numeric_limits<Dst>::lowest() < std::numeric_limits<Dst>::max())
103constexpr Dst checked_cast(Src value) {
104 // This throws a compile-time error on evaluating the constexpr if it can be
105 // determined at compile-time as failing, otherwise it will CHECK at runtime.
106 if (IsValueInRangeForNumericType<Dst>(value)) [[likely]] {
107 return static_cast<Dst>(static_cast<UnderlyingType<Src>>(value));
108 }
109 return CheckHandler::template HandleFailure<Dst>();
110}
111
112// Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
113// You may provide your own limits (e.g. to saturated_cast) so long as you
114// implement all of the static constexpr member functions in the class below.
115template <typename T>
116struct SaturationDefaultLimits : public std::numeric_limits<T> {
117 static constexpr T NaN() {
118 if constexpr (std::numeric_limits<T>::has_quiet_NaN) {
119 return std::numeric_limits<T>::quiet_NaN();
120 } else {
121 return T();
122 }
123 }
124 using std::numeric_limits<T>::max;
125 static constexpr T Overflow() {
126 if constexpr (std::numeric_limits<T>::has_infinity) {
127 return std::numeric_limits<T>::infinity();
128 } else {
129 return std::numeric_limits<T>::max();
130 }
131 }
132 using std::numeric_limits<T>::lowest;
133 static constexpr T Underflow() {
134 if constexpr (std::numeric_limits<T>::has_infinity) {
135 return std::numeric_limits<T>::infinity() * -1;
136 } else {
137 return std::numeric_limits<T>::lowest();
138 }
139 }
140};
141
142template <typename Dst, template <typename> class S, typename Src>
143constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
144 // For some reason clang generates much better code when the branch is
145 // structured exactly this way, rather than a sequence of checks.
146 return !constraint.IsOverflowFlagSet()
147 ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
148 : S<Dst>::Underflow())
149 // Skip this check for integral Src, which cannot be NaN.
150 : (std::is_integral_v<Src> || !constraint.IsUnderflowFlagSet()
151 ? S<Dst>::Overflow()
152 : S<Dst>::NaN());
153}
154
155// We can reduce the number of conditions and get slightly better performance
156// for normal signed and unsigned integer ranges. And in the specific case of
157// Arm, we can use the optimized saturation instructions.
158template <typename Dst, typename Src>
160 static constexpr bool is_supported = false;
161 static constexpr Dst Do(Src) {
162 // Force a compile failure if instantiated.
163 return CheckOnFailure::template HandleFailure<Dst>();
164 }
165};
166
167template <typename Dst, typename Src>
168 requires(std::integral<Src> && std::integral<Dst> &&
170struct SaturateFastOp<Dst, Src> {
171 static constexpr bool is_supported = true;
172 static constexpr Dst Do(Src value) {
174 }
175};
176
177template <typename Dst, typename Src>
178 requires(std::integral<Src> && std::integral<Dst> &&
181 static constexpr bool is_supported = true;
182 static constexpr Dst Do(Src value) {
183 // The exact order of the following is structured to hit the correct
184 // optimization heuristics across compilers. Do not change without
185 // checking the emitted code.
186 const Dst saturated = CommonMaxOrMin<Dst, Src>(
189 if (IsValueInRangeForNumericType<Dst>(value)) [[likely]] {
190 return static_cast<Dst>(value);
191 }
192 return saturated;
193 }
194};
195
196// saturated_cast<> is analogous to static_cast<> for numeric types, except
197// that the specified numeric conversion will saturate by default rather than
198// overflow or underflow, and NaN assignment to an integral will return 0.
199// All boundary condition behaviors can be overridden with a custom handler.
200template <typename Dst,
201 template <typename> class SaturationHandler = SaturationDefaultLimits,
202 typename Src>
203constexpr Dst saturated_cast(Src value) {
204 using SrcType = UnderlyingType<Src>;
205 const auto underlying_value = static_cast<SrcType>(value);
206 return !std::is_constant_evaluated() &&
208 std::is_same_v<SaturationHandler<Dst>,
210 ? SaturateFastOp<Dst, SrcType>::Do(underlying_value)
212 underlying_value,
214 underlying_value));
215}
216
217// strict_cast<> is analogous to static_cast<> for numeric types, except that
218// it will cause a compile failure if the destination type is not large enough
219// to contain any value in the source type. It performs no runtime checking.
220template <typename Dst, typename Src, typename SrcType = UnderlyingType<Src>>
221 requires(
222 IsNumeric<Src> && std::is_arithmetic_v<Dst> &&
223 // If you got here from a compiler error, it's because you tried to assign
224 // from a source type to a destination type that has insufficient range.
225 // The solution may be to change the destination type you're assigning to,
226 // and use one large enough to represent the source.
227 // Alternatively, you may be better served with the checked_cast<> or
228 // saturated_cast<> template functions for your particular use case.
231constexpr Dst strict_cast(Src value) {
232 return static_cast<Dst>(static_cast<SrcType>(value));
233}
234
235// Some wrappers to statically check that a type is in range.
236template <typename Dst, typename Src>
237inline constexpr bool kIsNumericRangeContained = false;
238
239template <typename Dst, typename Src>
240 requires(std::is_arithmetic_v<ArithmeticOrUnderlyingEnum<Dst>> &&
241 std::is_arithmetic_v<ArithmeticOrUnderlyingEnum<Src>>)
245
246// StrictNumeric implements compile time range checking between numeric types by
247// wrapping assignment operations in a strict_cast. This class is intended to be
248// used for function arguments and return types, to ensure the destination type
249// can always contain the source type. This is essentially the same as enforcing
250// -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
251// incrementally at API boundaries, making it easier to convert code so that it
252// compiles cleanly with truncation warnings enabled.
253// This template should introduce no runtime overhead, but it also provides no
254// runtime checking of any of the associated mathematical operations. Use
255// CheckedNumeric for runtime range checks of the actual value being assigned.
256template <typename T>
257 requires std::is_arithmetic_v<T>
258class StrictNumeric {
259 public:
260 using type = T;
261
262 constexpr StrictNumeric() : value_(0) {}
263
264 // Copy constructor.
265 template <typename Src>
266 constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
267 : value_(strict_cast<T>(rhs.value_)) {}
268
269 // This is not an explicit constructor because we implicitly upgrade regular
270 // numerics to StrictNumerics to make them easier to use.
271 template <typename Src>
272 // NOLINTNEXTLINE(runtime/explicit)
273 constexpr StrictNumeric(Src value) : value_(strict_cast<T>(value)) {}
274
275 // If you got here from a compiler error, it's because you tried to assign
276 // from a source type to a destination type that has insufficient range.
277 // The solution may be to change the destination type you're assigning to,
278 // and use one large enough to represent the source.
279 // If you're assigning from a CheckedNumeric<> class, you may be able to use
280 // the AssignIfValid() member function, specify a narrower destination type to
281 // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
282 // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
283 // If you've encountered an _ambiguous overload_ you can use a static_cast<>
284 // to explicitly cast the result to the destination type.
285 // If none of that works, you may be better served with the checked_cast<> or
286 // saturated_cast<> template functions for your particular use case.
287 template <typename Dst>
289 constexpr operator Dst() const { // NOLINT(runtime/explicit)
290 return static_cast<ArithmeticOrUnderlyingEnum<Dst>>(value_);
291 }
292
293 // Unary negation does not require any conversions.
294 constexpr bool operator!() const { return !value_; }
295
296 private:
297 template <typename U>
298 requires std::is_arithmetic_v<U>
299 friend class StrictNumeric;
300
302};
303
304template <typename T>
306
307// Convenience wrapper returns a StrictNumeric from the provided arithmetic
308// type.
309template <typename T>
311 return value;
312}
313
314#define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \
315 template <typename L, typename R> \
316 requires(internal::Is##CLASS##Op<L, R>) \
317 constexpr bool operator OP(L lhs, R rhs) { \
318 return SafeCompare<NAME, UnderlyingType<L>, UnderlyingType<R>>(lhs, rhs); \
319 }
320
321BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <)
322BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=)
323BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >)
324BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=)
325BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==)
326BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=)
327
328} // namespace internal
329
330using internal::as_signed;
331using internal::as_unsigned;
332using internal::checked_cast;
333using internal::IsValueInRangeForNumericType;
334using internal::IsValueNegative;
335using internal::kIsTypeInRangeForNumericType;
336using internal::MakeStrictNum;
337using internal::SafeUnsignedAbs;
338using internal::saturated_cast;
339using internal::strict_cast;
340using internal::StrictNumeric;
341
342// Explicitly make a shorter size_t alias for convenience.
343using SizeT = StrictNumeric<size_t>;
344
345// floating -> integral conversions that saturate and thus can actually return
346// an integral type.
347//
348// Generally, what you want is saturated_cast<Dst>(std::nearbyint(x)), which
349// rounds correctly according to IEEE-754 (round to nearest, ties go to nearest
350// even number; this avoids bias). If your code is performance-critical
351// and you are sure that you will never overflow, you can use std::lrint()
352// or std::llrint(), which return a long or long long directly.
353//
354// Below are convenience functions around similar patterns, except that
355// they round in nonstandard directions and will generally be slower.
356
357// Rounds towards negative infinity (i.e., down).
358template <typename Dst = int, typename Src>
359 requires(std::integral<Dst> && std::floating_point<Src>)
360Dst ClampFloor(Src value) {
361 return saturated_cast<Dst>(std::floor(value));
362}
363
364// Rounds towards positive infinity (i.e., up).
365template <typename Dst = int, typename Src>
366 requires(std::integral<Dst> && std::floating_point<Src>)
367Dst ClampCeil(Src value) {
368 return saturated_cast<Dst>(std::ceil(value));
369}
370
371// Rounds towards nearest integer, with ties away from zero.
372// This means that 0.5 will be rounded to 1 and 1.5 will be rounded to 2.
373// Similarly, -0.5 will be rounded to -1 and -1.5 will be rounded to -2.
374//
375// This is normally not what you want accuracy-wise (it introduces a small bias
376// away from zero), and it is not the fastest option, but it is frequently what
377// existing code expects. Compare with saturated_cast<Dst>(std::nearbyint(x))
378// or std::lrint(x), which would round 0.5 and -0.5 to 0 but 1.5 to 2 and
379// -1.5 to -2.
380template <typename Dst = int, typename Src>
381 requires(std::integral<Dst> && std::floating_point<Src>)
382Dst ClampRound(Src value) {
383 const Src rounded = std::round(value);
384 return saturated_cast<Dst>(rounded);
385}
386
387} // namespace v8::base
388
389#endif // V8_BASE_NUMERICS_SAFE_CONVERSIONS_H_
#define T
constexpr bool IsUnderflowFlagSet() const
constexpr bool IsOverflowFlagSet() const
constexpr StrictNumeric(const StrictNumeric< Src > &rhs)
STL namespace.
constexpr bool IsValueNegative(T value)
constexpr auto kStaticDstRangeRelationToSrcRange
StrictNumeric(T) -> StrictNumeric< T >
constexpr auto as_unsigned(Src value)
UnderlyingTypeImpl< T >::type UnderlyingType
constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint)
constexpr Dst strict_cast(Src value)
constexpr bool kIsNumericRangeContained
constexpr bool kIsMaxInRangeForNumericType
constexpr bool kIsNumericRangeContained< Dst, Src >
constexpr Dst checked_cast(Src value)
constexpr bool IsValueInRangeForNumericType(Src value)
constexpr Dst CommonMaxOrMin(bool is_min)
constexpr StrictNumeric< UnderlyingType< T > > MakeStrictNum(const T value)
typename std::conditional_t< std::is_enum_v< T >, std::underlying_type< T >, ArithmeticOrIntegralConstant< T > >::type ArithmeticOrUnderlyingEnum
constexpr RangeCheck DstRangeRelationToSrcRange(Src value)
constexpr bool kIsMinInRangeForNumericType
constexpr Dst saturated_cast(Src value)
Dst ClampRound(Src value)
Dst ClampFloor(Src value)
Dst ClampCeil(Src value)
#define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP)
std::unique_ptr< ValueMirror > value