chromium/third_party/webrtc/rtc_base/numerics/safe_minmax.h

/*
 *  Copyright 2017 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Minimum and maximum
// ===================
//
//   rtc::SafeMin(x, y)
//   rtc::SafeMax(x, y)
//
// (These are both constexpr.)
//
// Accept two arguments of either any two integral or any two floating-point
// types, and return the smaller and larger value, respectively, with no
// truncation or wrap-around. If only one of the input types is statically
// guaranteed to be able to represent the result, the return type is that type;
// if either one would do, the result type is the smaller type. (One of these
// two cases always applies.)
//
//   * The case with one floating-point and one integral type is not allowed,
//     because the floating-point type will have greater range, but may not
//     have sufficient precision to represent the integer value exactly.)
//
// Clamp (a.k.a. constrain to a given interval)
// ============================================
//
//   rtc::SafeClamp(x, a, b)
//
// Accepts three arguments of any mix of integral types or any mix of
// floating-point types, and returns the value in the closed interval [a, b]
// that is closest to x (that is, if x < a it returns a; if x > b it returns b;
// and if a <= x <= b it returns x). As for SafeMin() and SafeMax(), there is
// no truncation or wrap-around. The result type
//
//   1. is statically guaranteed to be able to represent the result;
//
//   2. is no larger than the largest of the three argument types; and
//
//   3. has the same signedness as the type of the first argument, if this is
//      possible without violating the First or Second Law.
//
// There is always at least one type that meets criteria 1 and 2. If more than
// one type meets these criteria equally well, the result type is one of the
// types that is smallest. Note that unlike SafeMin() and SafeMax(),
// SafeClamp() will sometimes pick a return type that isn't the type of any of
// its arguments.
//
//   * In this context, a type A is smaller than a type B if it has a smaller
//     range; that is, if A::max() - A::min() < B::max() - B::min(). For
//     example, int8_t < int16_t == uint16_t < int32_t, and all integral types
//     are smaller than all floating-point types.)
//
//   * As for SafeMin and SafeMax, mixing integer and floating-point arguments
//     is not allowed, because floating-point types have greater range than
//     integer types, but do not have sufficient precision to represent the
//     values of most integer types exactly.
//
// Requesting a specific return type
// =================================
//
// All three functions allow callers to explicitly specify the return type as a
// template parameter, overriding the default return type. E.g.
//
//   rtc::SafeMin<int>(x, y)  // returns an int
//
// If the requested type is statically guaranteed to be able to represent the
// result, then everything's fine, and the return type is as requested. But if
// the requested type is too small, a static_assert is triggered.

#ifndef RTC_BASE_NUMERICS_SAFE_MINMAX_H_
#define RTC_BASE_NUMERICS_SAFE_MINMAX_H_

#include <cstdint>
#include <limits>
#include <type_traits>

#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_compare.h"
#include "rtc_base/type_traits.h"

namespace rtc {

namespace safe_minmax_impl {

// Make the range of a type available via something other than a constexpr
// function, to work around MSVC limitations. See
// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
template <typename T>
struct Limits {};

template <typename T, bool is_enum = std::is_enum<T>::value>
struct UnderlyingType;

UnderlyingType<T, false>;

UnderlyingType<T, true>;

// Given two types T1 and T2, find types that can hold the smallest (in
// ::min_t) and the largest (in ::max_t) of the two values.
template <typename T1,
          typename T2,
          bool int1 = IsIntlike<T1>::value,
          bool int2 = IsIntlike<T2>::value>
struct MType {};

// Specialization for when neither type is integral (and therefore presumably
// floating-point).
MType<T1, T2, false, false>;

// Specialization for when both types are integral.
MType<T1, T2, true, true>;

// A dummy type that we pass around at compile time but never actually use.
// Declared but not defined.
struct DefaultType;

// ::type is A, except we fall back to B if A is DefaultType. We static_assert
// that the chosen type can hold all values that B can hold.
template <typename A, typename B>
struct TypeOr {};

}  // namespace safe_minmax_impl

template <
    typename R = safe_minmax_impl::DefaultType,
    typename T1 = safe_minmax_impl::DefaultType,
    typename T2 = safe_minmax_impl::DefaultType,
    typename R2 = typename safe_minmax_impl::TypeOr<
        R,
        typename safe_minmax_impl::MType<
            typename safe_minmax_impl::UnderlyingType<T1>::type,
            typename safe_minmax_impl::UnderlyingType<T2>::type>::min_t>::type>
constexpr R2 SafeMin(T1 a, T2 b) {}

template <
    typename R = safe_minmax_impl::DefaultType,
    typename T1 = safe_minmax_impl::DefaultType,
    typename T2 = safe_minmax_impl::DefaultType,
    typename R2 = typename safe_minmax_impl::TypeOr<
        R,
        typename safe_minmax_impl::MType<
            typename safe_minmax_impl::UnderlyingType<T1>::type,
            typename safe_minmax_impl::UnderlyingType<T2>::type>::max_t>::type>
constexpr R2 SafeMax(T1 a, T2 b) {}

namespace safe_minmax_impl {

// Given three types T, L, and H, let ::type be a suitable return value for
// SafeClamp(T, L, H). See the docs at the top of this file for details.
template <typename T,
          typename L,
          typename H,
          bool int1 = IsIntlike<T>::value,
          bool int2 = IsIntlike<L>::value,
          bool int3 = IsIntlike<H>::value>
struct ClampType {};

// Specialization for when all three types are floating-point.
ClampType<T, L, H, false, false, false>;

// Specialization for when all three types are integral.
ClampType<T, L, H, true, true, true>;

}  // namespace safe_minmax_impl

template <
    typename R = safe_minmax_impl::DefaultType,
    typename T = safe_minmax_impl::DefaultType,
    typename L = safe_minmax_impl::DefaultType,
    typename H = safe_minmax_impl::DefaultType,
    typename R2 = typename safe_minmax_impl::TypeOr<
        R,
        typename safe_minmax_impl::ClampType<
            typename safe_minmax_impl::UnderlyingType<T>::type,
            typename safe_minmax_impl::UnderlyingType<L>::type,
            typename safe_minmax_impl::UnderlyingType<H>::type>::type>::type>
R2 SafeClamp(T x, L min, H max) {}

}  // namespace rtc

#endif  // RTC_BASE_NUMERICS_SAFE_MINMAX_H_