Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(3)

Side by Side Diff: base/numerics/safe_conversions_impl.h

Issue 1659323003: Convert base/numerics conversions to constexpr (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: assert Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/numerics/safe_conversions.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_ 5 #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
6 #define BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_ 6 #define BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
7 7
8 #include <assert.h>
brucedawson 2016/02/04 20:39:58 Delete - presumably not needed?
8 #include <limits.h> 9 #include <limits.h>
9 #include <stdint.h> 10 #include <stdint.h>
10 11
11 namespace base { 12 namespace base {
12 namespace internal { 13 namespace internal {
13 14
14 // The std library doesn't provide a binary max_exponent for integers, however 15 // The std library doesn't provide a binary max_exponent for integers, however
15 // we can compute one by adding one to the number of non-sign bits. This allows 16 // we can compute one by adding one to the number of non-sign bits. This allows
16 // for accurate range comparisons between floating point and integer types. 17 // for accurate range comparisons between floating point and integer types.
17 template <typename NumericType> 18 template <typename NumericType>
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
85 }; 86 };
86 87
87 enum RangeConstraint { 88 enum RangeConstraint {
88 RANGE_VALID = 0x0, // Value can be represented by the destination type. 89 RANGE_VALID = 0x0, // Value can be represented by the destination type.
89 RANGE_UNDERFLOW = 0x1, // Value would overflow. 90 RANGE_UNDERFLOW = 0x1, // Value would overflow.
90 RANGE_OVERFLOW = 0x2, // Value would underflow. 91 RANGE_OVERFLOW = 0x2, // Value would underflow.
91 RANGE_INVALID = RANGE_UNDERFLOW | RANGE_OVERFLOW // Invalid (i.e. NaN). 92 RANGE_INVALID = RANGE_UNDERFLOW | RANGE_OVERFLOW // Invalid (i.e. NaN).
92 }; 93 };
93 94
94 // Helper function for coercing an int back to a RangeContraint. 95 // Helper function for coercing an int back to a RangeContraint.
95 inline RangeConstraint GetRangeConstraint(int integer_range_constraint) { 96 inline constexpr RangeConstraint GetRangeConstraint(
96 DCHECK(integer_range_constraint >= RANGE_VALID && 97 int integer_range_constraint) {
97 integer_range_constraint <= RANGE_INVALID); 98 // TODO(jschuh): Once we get full C++14 support we want this
99 // assert(integer_range_constraint >= RANGE_VALID &&
100 // integer_range_constraint <= RANGE_INVALID)
98 return static_cast<RangeConstraint>(integer_range_constraint); 101 return static_cast<RangeConstraint>(integer_range_constraint);
99 } 102 }
100 103
101 // This function creates a RangeConstraint from an upper and lower bound 104 // This function creates a RangeConstraint from an upper and lower bound
102 // check by taking advantage of the fact that only NaN can be out of range in 105 // check by taking advantage of the fact that only NaN can be out of range in
103 // both directions at once. 106 // both directions at once.
104 inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound, 107 constexpr inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound,
105 bool is_in_lower_bound) { 108 bool is_in_lower_bound) {
106 return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) | 109 return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) |
107 (is_in_lower_bound ? 0 : RANGE_UNDERFLOW)); 110 (is_in_lower_bound ? 0 : RANGE_UNDERFLOW));
108 } 111 }
109 112
110 // The following helper template addresses a corner case in range checks for 113 // The following helper template addresses a corner case in range checks for
111 // conversion from a floating-point type to an integral type of smaller range 114 // conversion from a floating-point type to an integral type of smaller range
112 // but larger precision (e.g. float -> unsigned). The problem is as follows: 115 // but larger precision (e.g. float -> unsigned). The problem is as follows:
113 // 1. Integral maximum is always one less than a power of two, so it must be 116 // 1. Integral maximum is always one less than a power of two, so it must be
114 // truncated to fit the mantissa of the floating point. The direction of 117 // truncated to fit the mantissa of the floating point. The direction of
115 // rounding is implementation defined, but by default it's always IEEE 118 // rounding is implementation defined, but by default it's always IEEE
116 // floats, which round to nearest and thus result in a value of larger 119 // floats, which round to nearest and thus result in a value of larger
117 // magnitude than the integral value. 120 // magnitude than the integral value.
118 // Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX 121 // Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX
119 // // is 4294967295u. 122 // // is 4294967295u.
120 // 2. If the floating point value is equal to the promoted integral maximum 123 // 2. If the floating point value is equal to the promoted integral maximum
121 // value, a range check will erroneously pass. 124 // value, a range check will erroneously pass.
122 // Example: (4294967296f <= 4294967295u) // This is true due to a precision 125 // Example: (4294967296f <= 4294967295u) // This is true due to a precision
123 // // loss in rounding up to float. 126 // // loss in rounding up to float.
124 // 3. When the floating point value is then converted to an integral, the 127 // 3. When the floating point value is then converted to an integral, the
125 // resulting value is out of range for the target integral type and 128 // resulting value is out of range for the target integral type and
126 // thus is implementation defined. 129 // thus is implementation defined.
127 // Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0. 130 // Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0.
128 // To fix this bug we manually truncate the maximum value when the destination 131 // To fix this bug we manually truncate the maximum value when the destination
129 // type is an integral of larger precision than the source floating-point type, 132 // type is an integral of larger precision than the source floating-point type,
130 // such that the resulting maximum is represented exactly as a floating point. 133 // such that the resulting maximum is represented exactly as a floating point.
131 template <typename Dst, typename Src> 134 template <typename Dst, typename Src>
132 struct NarrowingRange { 135 struct NarrowingRange {
133 typedef typename std::numeric_limits<Src> SrcLimits; 136 typedef typename std::numeric_limits<Src> SrcLimits;
134 typedef typename std::numeric_limits<Dst> DstLimits; 137 typedef typename std::numeric_limits<Dst> DstLimits;
138 // The following logic avoids warnings where the max function is
139 // instantiated with invalid values for a bit shift (even though
140 // such a function can never be called).
141 static const int shift = (MaxExponent<Src>::value > MaxExponent<Dst>::value &&
142 SrcLimits::digits < DstLimits::digits &&
143 SrcLimits::is_iec559 &&
144 DstLimits::is_integer)
145 ? (DstLimits::digits - SrcLimits::digits)
146 : 0;
135 147
136 static Dst max() { 148 static constexpr Dst max() {
137 // The following logic avoids warnings where the max function is
138 // instantiated with invalid values for a bit shift (even though
139 // such a function can never be called).
140 static const int shift =
141 (MaxExponent<Src>::value > MaxExponent<Dst>::value &&
142 SrcLimits::digits < DstLimits::digits && SrcLimits::is_iec559 &&
143 DstLimits::is_integer)
144 ? (DstLimits::digits - SrcLimits::digits)
145 : 0;
146
147 // We use UINTMAX_C below to avoid compiler warnings about shifting floating 149 // We use UINTMAX_C below to avoid compiler warnings about shifting floating
148 // points. Since it's a compile time calculation, it shouldn't have any 150 // points. Since it's a compile time calculation, it shouldn't have any
149 // performance impact. 151 // performance impact.
150 return DstLimits::max() - static_cast<Dst>((UINTMAX_C(1) << shift) - 1); 152 return DstLimits::max() - static_cast<Dst>((UINTMAX_C(1) << shift) - 1);
151 } 153 }
152 154
153 static Dst min() { 155 static constexpr Dst min() {
154 return std::numeric_limits<Dst>::is_iec559 ? -DstLimits::max() 156 return std::numeric_limits<Dst>::is_iec559 ? -DstLimits::max()
155 : DstLimits::min(); 157 : DstLimits::min();
156 } 158 }
157 }; 159 };
158 160
159 template < 161 template <
160 typename Dst, 162 typename Dst,
161 typename Src, 163 typename Src,
162 IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed 164 IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
163 ? INTEGER_REPRESENTATION_SIGNED 165 ? INTEGER_REPRESENTATION_SIGNED
(...skipping 12 matching lines...) Expand all
176 // Dst range is statically determined to contain Src: Nothing to check. 178 // Dst range is statically determined to contain Src: Nothing to check.
177 template <typename Dst, 179 template <typename Dst,
178 typename Src, 180 typename Src,
179 IntegerRepresentation DstSign, 181 IntegerRepresentation DstSign,
180 IntegerRepresentation SrcSign> 182 IntegerRepresentation SrcSign>
181 struct DstRangeRelationToSrcRangeImpl<Dst, 183 struct DstRangeRelationToSrcRangeImpl<Dst,
182 Src, 184 Src,
183 DstSign, 185 DstSign,
184 SrcSign, 186 SrcSign,
185 NUMERIC_RANGE_CONTAINED> { 187 NUMERIC_RANGE_CONTAINED> {
186 static RangeConstraint Check(Src value) { return RANGE_VALID; } 188 static constexpr RangeConstraint Check(Src value) { return RANGE_VALID; }
187 }; 189 };
188 190
189 // Signed to signed narrowing: Both the upper and lower boundaries may be 191 // Signed to signed narrowing: Both the upper and lower boundaries may be
190 // exceeded. 192 // exceeded.
191 template <typename Dst, typename Src> 193 template <typename Dst, typename Src>
192 struct DstRangeRelationToSrcRangeImpl<Dst, 194 struct DstRangeRelationToSrcRangeImpl<Dst,
193 Src, 195 Src,
194 INTEGER_REPRESENTATION_SIGNED, 196 INTEGER_REPRESENTATION_SIGNED,
195 INTEGER_REPRESENTATION_SIGNED, 197 INTEGER_REPRESENTATION_SIGNED,
196 NUMERIC_RANGE_NOT_CONTAINED> { 198 NUMERIC_RANGE_NOT_CONTAINED> {
197 static RangeConstraint Check(Src value) { 199 static constexpr RangeConstraint Check(Src value) {
198 return GetRangeConstraint((value <= NarrowingRange<Dst, Src>::max()), 200 return GetRangeConstraint((value <= NarrowingRange<Dst, Src>::max()),
199 (value >= NarrowingRange<Dst, Src>::min())); 201 (value >= NarrowingRange<Dst, Src>::min()));
200 } 202 }
201 }; 203 };
202 204
203 // Unsigned to unsigned narrowing: Only the upper boundary can be exceeded. 205 // Unsigned to unsigned narrowing: Only the upper boundary can be exceeded.
204 template <typename Dst, typename Src> 206 template <typename Dst, typename Src>
205 struct DstRangeRelationToSrcRangeImpl<Dst, 207 struct DstRangeRelationToSrcRangeImpl<Dst,
206 Src, 208 Src,
207 INTEGER_REPRESENTATION_UNSIGNED, 209 INTEGER_REPRESENTATION_UNSIGNED,
208 INTEGER_REPRESENTATION_UNSIGNED, 210 INTEGER_REPRESENTATION_UNSIGNED,
209 NUMERIC_RANGE_NOT_CONTAINED> { 211 NUMERIC_RANGE_NOT_CONTAINED> {
210 static RangeConstraint Check(Src value) { 212 static constexpr RangeConstraint Check(Src value) {
211 return GetRangeConstraint(value <= NarrowingRange<Dst, Src>::max(), true); 213 return GetRangeConstraint(value <= NarrowingRange<Dst, Src>::max(), true);
212 } 214 }
213 }; 215 };
214 216
215 // Unsigned to signed: The upper boundary may be exceeded. 217 // Unsigned to signed: The upper boundary may be exceeded.
216 template <typename Dst, typename Src> 218 template <typename Dst, typename Src>
217 struct DstRangeRelationToSrcRangeImpl<Dst, 219 struct DstRangeRelationToSrcRangeImpl<Dst,
218 Src, 220 Src,
219 INTEGER_REPRESENTATION_SIGNED, 221 INTEGER_REPRESENTATION_SIGNED,
220 INTEGER_REPRESENTATION_UNSIGNED, 222 INTEGER_REPRESENTATION_UNSIGNED,
221 NUMERIC_RANGE_NOT_CONTAINED> { 223 NUMERIC_RANGE_NOT_CONTAINED> {
222 static RangeConstraint Check(Src value) { 224 static constexpr RangeConstraint Check(Src value) {
223 return sizeof(Dst) > sizeof(Src) 225 return sizeof(Dst) > sizeof(Src)
224 ? RANGE_VALID 226 ? RANGE_VALID
225 : GetRangeConstraint( 227 : GetRangeConstraint(
226 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()), 228 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
227 true); 229 true);
228 } 230 }
229 }; 231 };
230 232
231 // Signed to unsigned: The upper boundary may be exceeded for a narrower Dst, 233 // Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
232 // and any negative value exceeds the lower boundary. 234 // and any negative value exceeds the lower boundary.
233 template <typename Dst, typename Src> 235 template <typename Dst, typename Src>
234 struct DstRangeRelationToSrcRangeImpl<Dst, 236 struct DstRangeRelationToSrcRangeImpl<Dst,
235 Src, 237 Src,
236 INTEGER_REPRESENTATION_UNSIGNED, 238 INTEGER_REPRESENTATION_UNSIGNED,
237 INTEGER_REPRESENTATION_SIGNED, 239 INTEGER_REPRESENTATION_SIGNED,
238 NUMERIC_RANGE_NOT_CONTAINED> { 240 NUMERIC_RANGE_NOT_CONTAINED> {
239 static RangeConstraint Check(Src value) { 241 static constexpr RangeConstraint Check(Src value) {
240 return (MaxExponent<Dst>::value >= MaxExponent<Src>::value) 242 return (MaxExponent<Dst>::value >= MaxExponent<Src>::value)
241 ? GetRangeConstraint(true, value >= static_cast<Src>(0)) 243 ? GetRangeConstraint(true, value >= static_cast<Src>(0))
242 : GetRangeConstraint( 244 : GetRangeConstraint(
243 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()), 245 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
244 value >= static_cast<Src>(0)); 246 value >= static_cast<Src>(0));
245 } 247 }
246 }; 248 };
247 249
248 template <typename Dst, typename Src> 250 template <typename Dst, typename Src>
249 inline RangeConstraint DstRangeRelationToSrcRange(Src value) { 251 inline constexpr RangeConstraint DstRangeRelationToSrcRange(Src value) {
250 static_assert(std::numeric_limits<Src>::is_specialized, 252 static_assert(std::numeric_limits<Src>::is_specialized,
251 "Argument must be numeric."); 253 "Argument must be numeric.");
252 static_assert(std::numeric_limits<Dst>::is_specialized, 254 static_assert(std::numeric_limits<Dst>::is_specialized,
253 "Result must be numeric."); 255 "Result must be numeric.");
254 return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value); 256 return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value);
255 } 257 }
256 258
257 } // namespace internal 259 } // namespace internal
258 } // namespace base 260 } // namespace base
259 261
260 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_ 262 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
OLDNEW
« no previous file with comments | « base/numerics/safe_conversions.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698