summaryrefslogtreecommitdiffstats
path: root/src/3rdparty/angle/src/common/third_party/base/anglebase/numerics/safe_conversions.h
blob: 43babc31a80370cf7731c3158b9f09a5d6cba0ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ANGLEBASE_NUMERICS_SAFE_CONVERSIONS_H_
#define ANGLEBASE_NUMERICS_SAFE_CONVERSIONS_H_

#include <stddef.h>

#include <limits>
#include <type_traits>

#include "anglebase/logging.h"
#include "anglebase/numerics/safe_conversions_impl.h"

namespace angle
{

namespace base
{

// 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)
{
    return internal::DstRangeRelationToSrcRange<Dst>(value) == internal::RANGE_VALID;
}

// Convenience function for determining if a numeric value is negative without
// throwing compiler warnings on: unsigned(value) < 0.
template <typename T>
constexpr typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type IsValueNegative(
    T value)
{
    static_assert(std::numeric_limits<T>::is_specialized, "Argument must be numeric.");
    return value < 0;
}

template <typename T>
constexpr typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type IsValueNegative(T)
{
    static_assert(std::numeric_limits<T>::is_specialized, "Argument must be numeric.");
    return false;
}

// 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, typename Src>
inline Dst checked_cast(Src value)
{
    CHECK(IsValueInRangeForNumericType<Dst>(value));
    return static_cast<Dst>(value);
}

// HandleNaN will cause this class to CHECK(false).
struct SaturatedCastNaNBehaviorCheck
{
    template <typename T>
    static T HandleNaN()
    {
        CHECK(false);
        return T();
    }
};

// HandleNaN will return 0 in this case.
struct SaturatedCastNaNBehaviorReturnZero
{
    template <typename T>
    static constexpr T HandleNaN()
    {
        return T();
    }
};

namespace internal
{
// This wrapper is used for C++11 constexpr support by avoiding the declaration
// of local variables in the saturated_cast template function.
template <typename Dst, class NaNHandler, typename Src>
constexpr Dst saturated_cast_impl(const Src value, const RangeConstraint constraint)
{
    return constraint == RANGE_VALID
               ? static_cast<Dst>(value)
               : (constraint == RANGE_UNDERFLOW
                      ? std::numeric_limits<Dst>::min()
                      : (constraint == RANGE_OVERFLOW
                             ? std::numeric_limits<Dst>::max()
                             : (constraint == RANGE_INVALID
                                    ? NaNHandler::template HandleNaN<Dst>()
                                    : (NOTREACHED(), static_cast<Dst>(value)))));
}
}  // namespace internal

// saturated_cast<> is analogous to static_cast<> for numeric types, except
// that the specified numeric conversion will saturate rather than overflow or
// underflow. NaN assignment to an integral will defer the behavior to a
// specified class. By default, it will return 0.
template <typename Dst, class NaNHandler = SaturatedCastNaNBehaviorReturnZero, typename Src>
constexpr Dst saturated_cast(Src value)
{
    return std::numeric_limits<Dst>::is_iec559
               ? static_cast<Dst>(value)  // Floating point optimization.
               : internal::saturated_cast_impl<Dst, NaNHandler>(
                     value, internal::DstRangeRelationToSrcRange<Dst>(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)
{
    static_assert(std::numeric_limits<Src>::is_specialized, "Argument must be numeric.");
    static_assert(std::numeric_limits<Dst>::is_specialized, "Result must be numeric.");
    static_assert((internal::StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
                   internal::NUMERIC_RANGE_CONTAINED),
                  "The numeric conversion is out of range for this type. You "
                  "should probably use one of the following conversion "
                  "mechanisms on the value you want to pass:\n"
                  "- base::checked_cast\n"
                  "- base::saturated_cast\n"
                  "- base::CheckedNumeric");

    return static_cast<Dst>(value);
}

// 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
{
  public:
    typedef T type;

    constexpr StrictNumeric() : value_(0) {}

    // Copy constructor.
    template <typename Src>
    constexpr StrictNumeric(const StrictNumeric<Src> &rhs) : value_(strict_cast<T>(rhs.value_))
    {
    }

    // This is not an explicit constructor because we implicitly upgrade regular
    // numerics to StrictNumerics to make them easier to use.
    template <typename Src>
    constexpr StrictNumeric(Src value) : value_(strict_cast<T>(value))
    {
    }

    // The numeric cast operator basically handles all the magic.
    template <typename Dst>
    constexpr operator Dst() const
    {
        return strict_cast<Dst>(value_);
    }

  private:
    const T value_;
};

// Explicitly make a shorter size_t typedef for convenience.
typedef StrictNumeric<size_t> SizeT;

}  // namespace base

}  // namespace angle

#endif  // ANGLEBASE_NUMERICS_SAFE_CONVERSIONS_H_