v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
wrapping_math.h
Go to the documentation of this file.
1// Copyright 2023 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_WRAPPING_MATH_H_
9#define V8_BASE_NUMERICS_WRAPPING_MATH_H_
10
11#include <type_traits>
12
13namespace v8::base {
14
15// Returns `a + b` with overflow defined to wrap around, i.e. modulo 2^N where N
16// is the bit width of `T`.
17template <typename T>
18inline constexpr T WrappingAdd(T a, T b) {
19 static_assert(std::is_integral_v<T>);
20 // Unsigned arithmetic wraps, so convert to the corresponding unsigned type.
21 // Note that, if `T` is smaller than `int`, e.g. `int16_t`, the values are
22 // promoted to `int`, which brings us back to undefined overflow. This is fine
23 // here because the sum of any two `int16_t`s fits in `int`, but `WrappingMul`
24 // will need a more complex implementation.
25 using Unsigned = std::make_unsigned_t<T>;
26 return static_cast<T>(static_cast<Unsigned>(a) + static_cast<Unsigned>(b));
27}
28
29// Returns `a - b` with overflow defined to wrap around, i.e. modulo 2^N where N
30// is the bit width of `T`.
31template <typename T>
32inline constexpr T WrappingSub(T a, T b) {
33 static_assert(std::is_integral_v<T>);
34 // Unsigned arithmetic wraps, so convert to the corresponding unsigned type.
35 // Note that, if `T` is smaller than `int`, e.g. `int16_t`, the values are
36 // promoted to `int`, which brings us back to undefined overflow. This is fine
37 // here because the difference of any two `int16_t`s fits in `int`, but
38 // `WrappingMul` will need a more complex implementation.
39 using Unsigned = std::make_unsigned_t<T>;
40 return static_cast<T>(static_cast<Unsigned>(a) - static_cast<Unsigned>(b));
41}
42
43} // namespace v8::base
44
45#endif // V8_BASE_NUMERICS_WRAPPING_MATH_H_
std::optional< TNode< JSArray > > a
constexpr T WrappingSub(T a, T b)
constexpr T WrappingAdd(T a, T b)