CheckedArithmetic.h (957B)
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 /* Provides checked integers operations, detecting overflow. */ 8 9 #ifndef mozilla_CheckedArithmetic_h 10 #define mozilla_CheckedArithmetic_h 11 12 namespace mozilla { 13 14 template <typename T> 15 [[nodiscard]] constexpr bool SafeAdd(T lhs, T rhs, T* res) { 16 return !__builtin_add_overflow(lhs, rhs, res); 17 } 18 19 template <typename T> 20 [[nodiscard]] constexpr bool SafeSub(T lhs, T rhs, T* res) { 21 return !__builtin_sub_overflow(lhs, rhs, res); 22 } 23 24 template <typename T> 25 [[nodiscard]] constexpr bool SafeMul(T lhs, T rhs, T* res) { 26 return !__builtin_mul_overflow(lhs, rhs, res); 27 } 28 29 } // namespace mozilla 30 31 #endif /* mozilla_CheckedArithmetic_h */