// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ #include <stddef.h> #include <cmath> #include <concepts> #include <limits> #include <type_traits> #include "base/numerics/safe_conversions_impl.h" // IWYU pragma: export #if defined(__ARMEL__) && !defined(__native_client__) #include "base/numerics/safe_conversions_arm_impl.h" // IWYU pragma: export #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS … #else #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS … #endif namespace base { namespace internal { #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS template <typename Dst, typename Src> struct SaturateFastAsmOp { … }; #endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS // The following special case a few specific integer conversions where we can // eke out better performance than range checking. template <typename Dst, typename Src> struct IsValueInRangeFastOp { … }; // Signed to signed range comparison. IsValueInRangeFastOp<Dst, Src>; // Signed to unsigned range comparison. IsValueInRangeFastOp<Dst, Src>; // Convenience function that returns true if the supplied value is in range // for the destination type. template <typename Dst, typename Src> constexpr bool IsValueInRangeForNumericType(Src value) { … } // checked_cast<> is analogous to static_cast<> for numeric types, // except that it CHECKs that the specified numeric conversion will not // overflow or underflow. NaN source will always trigger a CHECK. template <typename Dst, class CheckHandler = internal::CheckOnFailure, typename Src> constexpr Dst checked_cast(Src value) { … } // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. // You may provide your own limits (e.g. to saturated_cast) so long as you // implement all of the static constexpr member functions in the class below. template <typename T> struct SaturationDefaultLimits : public std::numeric_limits<T> { … }; template <typename Dst, template <typename> class S, typename Src> constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { … } // We can reduce the number of conditions and get slightly better performance // for normal signed and unsigned integer ranges. And in the specific case of // Arm, we can use the optimized saturation instructions. template <typename Dst, typename Src> struct SaturateFastOp { … }; SaturateFastOp<Dst, Src>; SaturateFastOp<Dst, Src>; // saturated_cast<> is analogous to static_cast<> for numeric types, except // that the specified numeric conversion will saturate by default rather than // overflow or underflow, and NaN assignment to an integral will return 0. // All boundary condition behaviors can be overridden with a custom handler. template <typename Dst, template <typename> class SaturationHandler = SaturationDefaultLimits, typename Src> constexpr Dst saturated_cast(Src value) { … } // strict_cast<> is analogous to static_cast<> for numeric types, except that // it will cause a compile failure if the destination type is not large enough // to contain any value in the source type. It performs no runtime checking. template <typename Dst, typename Src> constexpr Dst strict_cast(Src value) { … } // Some wrappers to statically check that a type is in range. template <typename Dst, typename Src> struct IsNumericRangeContained { … }; IsNumericRangeContained<Dst, Src>; // StrictNumeric implements compile time range checking between numeric types by // wrapping assignment operations in a strict_cast. This class is intended to be // used for function arguments and return types, to ensure the destination type // can always contain the source type. This is essentially the same as enforcing // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied // incrementally at API boundaries, making it easier to convert code so that it // compiles cleanly with truncation warnings enabled. // This template should introduce no runtime overhead, but it also provides no // runtime checking of any of the associated mathematical operations. Use // CheckedNumeric for runtime range checks of the actual value being assigned. template <typename T> class StrictNumeric { … }; // Convenience wrapper returns a StrictNumeric from the provided arithmetic // type. template <typename T> constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum( const T value) { … } #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) … BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) } // namespace internal as_signed; as_unsigned; checked_cast; IsTypeInRangeForNumericType; IsValueInRangeForNumericType; IsValueNegative; MakeStrictNum; SafeUnsignedAbs; saturated_cast; strict_cast; StrictNumeric; // Explicitly make a shorter size_t alias for convenience. SizeT; // floating -> integral conversions that saturate and thus can actually return // an integral type. // // Generally, what you want is saturated_cast<Dst>(std::nearbyint(x)), which // rounds correctly according to IEEE-754 (round to nearest, ties go to nearest // even number; this avoids bias). If your code is performance-critical // and you are sure that you will never overflow, you can use std::lrint() // or std::llrint(), which return a long or long long directly. // // Below are convenience functions around similar patterns, except that // they round in nonstandard directions and will generally be slower. // Rounds towards negative infinity (i.e., down). template <typename Dst = int, typename Src> requires(std::integral<Dst> && std::floating_point<Src>) Dst ClampFloor(Src value) { … } // Rounds towards positive infinity (i.e., up). template <typename Dst = int, typename Src> requires(std::integral<Dst> && std::floating_point<Src>) Dst ClampCeil(Src value) { … } // Rounds towards nearest integer, with ties away from zero. // This means that 0.5 will be rounded to 1 and 1.5 will be rounded to 2. // Similarly, -0.5 will be rounded to -1 and -1.5 will be rounded to -2. // // This is normally not what you want accuracy-wise (it introduces a small bias // away from zero), and it is not the fastest option, but it is frequently what // existing code expects. Compare with saturated_cast<Dst>(std::nearbyint(x)) // or std::lrint(x), which would round 0.5 and -0.5 to 0 but 1.5 to 2 and // -1.5 to -2. template <typename Dst = int, typename Src> requires(std::integral<Dst> && std::floating_point<Src>) Dst ClampRound(Src value) { … } } // namespace base #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_