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

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

Issue 1338553003: Fix float to int conversion in base/numerics (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: more tests Created 5 years, 3 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 | « no previous file | base/numerics/safe_numerics_unittest.cc » ('j') | 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 <limits> 8 #include <limits>
9 9
10 #include "base/template_util.h" 10 #include "base/template_util.h"
(...skipping 90 matching lines...) Expand 10 before | Expand all | Expand 10 after
101 101
102 // This function creates a RangeConstraint from an upper and lower bound 102 // This function creates a RangeConstraint from an upper and lower bound
103 // check by taking advantage of the fact that only NaN can be out of range in 103 // check by taking advantage of the fact that only NaN can be out of range in
104 // both directions at once. 104 // both directions at once.
105 inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound, 105 inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound,
106 bool is_in_lower_bound) { 106 bool is_in_lower_bound) {
107 return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) | 107 return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) |
108 (is_in_lower_bound ? 0 : RANGE_UNDERFLOW)); 108 (is_in_lower_bound ? 0 : RANGE_UNDERFLOW));
109 } 109 }
110 110
111 // The following helper template addresses a corner case in range checks for
112 // conversion from a floating-point type to an integral type of smaller range
113 // but larger precision (e.g. float -> unsigned). The problem is as follows:
114 // 1. Integral maximum is always one less than a power of two, so it must be
115 // truncated to fit the mantissa of the floating point. The direction of
116 // rounding is implementation defined, but by default it's always IEEE
117 // floats, which round to nearest and thus result in a value of larger
118 // magnitude than the integral value.
119 // Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX
120 // // is 4294967295u.
121 // 2. If the floating point value is equal to the promoted integral maximum
122 // value, a range check will erroneously pass.
123 // Example: (4294967296f <= 4294967295u) // This is true due to a precision
124 // // loss in rounding up to float.
125 // 3. When the floating point value is then converted to an integral, the
126 // resulting value is out of range for the target integral type and
127 // thus is implementation defined.
128 // Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0.
129 // To fix this bug we manually truncate the maximum value when the destination
130 // type is an integral of larger precision than the source floating-point type,
131 // such that the resulting maximum is represented exactly as a floating point.
132 template <typename Dst, typename Src>
133 struct NarrowingRange {
134 typedef typename std::numeric_limits<Src> SrcLimits;
135 typedef typename std::numeric_limits<Dst> DstLimits;
136
137 static Dst max() {
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 =
142 (MaxExponent<Src>::value > MaxExponent<Dst>::value &&
143 SrcLimits::digits < DstLimits::digits && SrcLimits::is_iec559 &&
144 DstLimits::is_integer)
145 ? (DstLimits::digits - SrcLimits::digits)
146 : 0;
147
148 // We use UINTMAX_C below to avoid compiler warnings about shifting floating
149 // points. Since it's a compile time calculation, it shouldn't have any
150 // performance impact.
151 return DstLimits::max() - static_cast<Dst>((UINTMAX_C(1) << shift) - 1);
152 }
153
154 static Dst min() {
155 return std::numeric_limits<Dst>::is_iec559 ? -DstLimits::max()
156 : DstLimits::min();
157 }
158 };
159
111 template < 160 template <
112 typename Dst, 161 typename Dst,
113 typename Src, 162 typename Src,
114 IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed 163 IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
115 ? INTEGER_REPRESENTATION_SIGNED 164 ? INTEGER_REPRESENTATION_SIGNED
116 : INTEGER_REPRESENTATION_UNSIGNED, 165 : INTEGER_REPRESENTATION_UNSIGNED,
117 IntegerRepresentation SrcSign = std::numeric_limits<Src>::is_signed 166 IntegerRepresentation SrcSign = std::numeric_limits<Src>::is_signed
118 ? INTEGER_REPRESENTATION_SIGNED 167 ? INTEGER_REPRESENTATION_SIGNED
119 : INTEGER_REPRESENTATION_UNSIGNED, 168 : INTEGER_REPRESENTATION_UNSIGNED,
120 NumericRangeRepresentation DstRange = 169 NumericRangeRepresentation DstRange =
(...skipping 19 matching lines...) Expand all
140 189
141 // Signed to signed narrowing: Both the upper and lower boundaries may be 190 // Signed to signed narrowing: Both the upper and lower boundaries may be
142 // exceeded. 191 // exceeded.
143 template <typename Dst, typename Src> 192 template <typename Dst, typename Src>
144 struct DstRangeRelationToSrcRangeImpl<Dst, 193 struct DstRangeRelationToSrcRangeImpl<Dst,
145 Src, 194 Src,
146 INTEGER_REPRESENTATION_SIGNED, 195 INTEGER_REPRESENTATION_SIGNED,
147 INTEGER_REPRESENTATION_SIGNED, 196 INTEGER_REPRESENTATION_SIGNED,
148 NUMERIC_RANGE_NOT_CONTAINED> { 197 NUMERIC_RANGE_NOT_CONTAINED> {
149 static RangeConstraint Check(Src value) { 198 static RangeConstraint Check(Src value) {
150 return std::numeric_limits<Dst>::is_iec559 199 return GetRangeConstraint((value <= NarrowingRange<Dst, Src>::max()),
151 ? GetRangeConstraint((value < std::numeric_limits<Dst>::max()), 200 (value >= NarrowingRange<Dst, Src>::min()));
152 (value > -std::numeric_limits<Dst>::max()))
153 : GetRangeConstraint((value < std::numeric_limits<Dst>::max()),
154 (value > std::numeric_limits<Dst>::min()));
155 } 201 }
156 }; 202 };
157 203
158 // Unsigned to unsigned narrowing: Only the upper boundary can be exceeded. 204 // Unsigned to unsigned narrowing: Only the upper boundary can be exceeded.
159 template <typename Dst, typename Src> 205 template <typename Dst, typename Src>
160 struct DstRangeRelationToSrcRangeImpl<Dst, 206 struct DstRangeRelationToSrcRangeImpl<Dst,
161 Src, 207 Src,
162 INTEGER_REPRESENTATION_UNSIGNED, 208 INTEGER_REPRESENTATION_UNSIGNED,
163 INTEGER_REPRESENTATION_UNSIGNED, 209 INTEGER_REPRESENTATION_UNSIGNED,
164 NUMERIC_RANGE_NOT_CONTAINED> { 210 NUMERIC_RANGE_NOT_CONTAINED> {
165 static RangeConstraint Check(Src value) { 211 static RangeConstraint Check(Src value) {
166 return GetRangeConstraint(value < std::numeric_limits<Dst>::max(), true); 212 return GetRangeConstraint(value <= NarrowingRange<Dst, Src>::max(), true);
167 } 213 }
168 }; 214 };
169 215
170 // Unsigned to signed: The upper boundary may be exceeded. 216 // Unsigned to signed: The upper boundary may be exceeded.
171 template <typename Dst, typename Src> 217 template <typename Dst, typename Src>
172 struct DstRangeRelationToSrcRangeImpl<Dst, 218 struct DstRangeRelationToSrcRangeImpl<Dst,
173 Src, 219 Src,
174 INTEGER_REPRESENTATION_SIGNED, 220 INTEGER_REPRESENTATION_SIGNED,
175 INTEGER_REPRESENTATION_UNSIGNED, 221 INTEGER_REPRESENTATION_UNSIGNED,
176 NUMERIC_RANGE_NOT_CONTAINED> { 222 NUMERIC_RANGE_NOT_CONTAINED> {
177 static RangeConstraint Check(Src value) { 223 static RangeConstraint Check(Src value) {
178 return sizeof(Dst) > sizeof(Src) 224 return sizeof(Dst) > sizeof(Src)
179 ? RANGE_VALID 225 ? RANGE_VALID
180 : GetRangeConstraint( 226 : GetRangeConstraint(
181 value < static_cast<Src>(std::numeric_limits<Dst>::max()), 227 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
182 true); 228 true);
183 } 229 }
184 }; 230 };
185 231
186 // Signed to unsigned: The upper boundary may be exceeded for a narrower Dst, 232 // Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
187 // and any negative value exceeds the lower boundary. 233 // and any negative value exceeds the lower boundary.
188 template <typename Dst, typename Src> 234 template <typename Dst, typename Src>
189 struct DstRangeRelationToSrcRangeImpl<Dst, 235 struct DstRangeRelationToSrcRangeImpl<Dst,
190 Src, 236 Src,
191 INTEGER_REPRESENTATION_UNSIGNED, 237 INTEGER_REPRESENTATION_UNSIGNED,
192 INTEGER_REPRESENTATION_SIGNED, 238 INTEGER_REPRESENTATION_SIGNED,
193 NUMERIC_RANGE_NOT_CONTAINED> { 239 NUMERIC_RANGE_NOT_CONTAINED> {
194 static RangeConstraint Check(Src value) { 240 static RangeConstraint Check(Src value) {
195 return (MaxExponent<Dst>::value >= MaxExponent<Src>::value) 241 return (MaxExponent<Dst>::value >= MaxExponent<Src>::value)
196 ? GetRangeConstraint(true, value >= static_cast<Src>(0)) 242 ? GetRangeConstraint(true, value >= static_cast<Src>(0))
197 : GetRangeConstraint( 243 : GetRangeConstraint(
198 value < static_cast<Src>(std::numeric_limits<Dst>::max()), 244 value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
199 value >= static_cast<Src>(0)); 245 value >= static_cast<Src>(0));
200 } 246 }
201 }; 247 };
202 248
203 template <typename Dst, typename Src> 249 template <typename Dst, typename Src>
204 inline RangeConstraint DstRangeRelationToSrcRange(Src value) { 250 inline RangeConstraint DstRangeRelationToSrcRange(Src value) {
205 static_assert(std::numeric_limits<Src>::is_specialized, 251 static_assert(std::numeric_limits<Src>::is_specialized,
206 "Argument must be numeric."); 252 "Argument must be numeric.");
207 static_assert(std::numeric_limits<Dst>::is_specialized, 253 static_assert(std::numeric_limits<Dst>::is_specialized,
208 "Result must be numeric."); 254 "Result must be numeric.");
209 return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value); 255 return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value);
210 } 256 }
211 257
212 } // namespace internal 258 } // namespace internal
213 } // namespace base 259 } // namespace base
214 260
215 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_ 261 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
OLDNEW
« no previous file with comments | « no previous file | base/numerics/safe_numerics_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698