OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2013 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef BASE_SAFE_NUMERICS_H_ | |
6 #define BASE_SAFE_NUMERICS_H_ | |
7 | |
8 #include <limits> | |
9 | |
10 #include "base/logging.h" | |
11 | |
12 namespace base { | |
13 namespace internal { | |
14 | |
15 // The main test for whether the conversion will under or overflow. | |
16 template <class Dest, class Source> | |
17 inline bool IsValidNumericCast(Source source) { | |
18 typedef std::numeric_limits<Source> SourceLimits; | |
19 typedef std::numeric_limits<Dest> DestLimits; | |
20 COMPILE_ASSERT(SourceLimits::is_specialized, argument_must_be_numeric); | |
21 COMPILE_ASSERT(SourceLimits::is_integer, argument_must_be_integral); | |
22 COMPILE_ASSERT(DestLimits::is_specialized, result_must_be_numeric); | |
23 COMPILE_ASSERT(DestLimits::is_integer, result_must_be_integral); | |
24 | |
25 // Source and Dest are the same. | |
26 if (DestLimits::digits == SourceLimits::digits && | |
27 DestLimits::is_signed == SourceLimits::is_signed) | |
28 return true; | |
29 | |
30 // Dest is wider, check for loss of sign if Dest is not signed. | |
31 if (DestLimits::digits > SourceLimits::digits) | |
32 return DestLimits::is_signed || source >= 0; | |
33 | |
34 // Otherwise, Dest is narrower than Source. | |
35 | |
36 // Check for underflow. | |
37 if (SourceLimits::is_signed && // Don't need to check if source is unsigned. | |
38 source < static_cast<Source>(DestLimits::min())) | |
39 return false; | |
40 | |
41 // Or overflow. | |
42 return source <= static_cast<Source>(DestLimits::max()); | |
43 } | |
44 | |
45 } // namespace internal | |
46 | |
47 // numeric_cast<> is analogous to static_cast<> for numeric types, except that | |
48 // it CHECKs that the specified numeric conversion will not overflow or | |
49 // underflow. Floating point arguments are not currently allowed (this is | |
50 // COMPILE_ASSERTd), though this could be supported if necessary. | |
51 template <class Dest, class Source> | |
52 inline Dest numeric_cast(Source source) { | |
53 CHECK(internal::IsValidNumericCast<Dest>(source)); | |
54 return static_cast<Dest>(source); | |
55 } | |
56 | |
57 } // namespace base | |
brettw
2013/01/15 21:09:50
We've done some extern templates in some cases whi
jschuh
2013/01/15 21:13:27
fwiw, I was planning on just adding a saturating_c
| |
58 | |
59 #endif // BASE_SAFE_NUMERICS_H_ | |
OLD | NEW |