1*635a8641SAndroid Build Coastguard Worker# `base/numerics` 2*635a8641SAndroid Build Coastguard Worker 3*635a8641SAndroid Build Coastguard WorkerThis directory contains a dependency-free, header-only library of templates 4*635a8641SAndroid Build Coastguard Workerproviding well-defined semantics for safely and performantly handling a variety 5*635a8641SAndroid Build Coastguard Workerof numeric operations, including most common arithmetic operations and 6*635a8641SAndroid Build Coastguard Workerconversions. 7*635a8641SAndroid Build Coastguard Worker 8*635a8641SAndroid Build Coastguard WorkerThe public API is broken out into the following header files: 9*635a8641SAndroid Build Coastguard Worker 10*635a8641SAndroid Build Coastguard Worker* `checked_math.h` contains the `CheckedNumeric` template class and helper 11*635a8641SAndroid Build Coastguard Worker functions for performing arithmetic and conversion operations that detect 12*635a8641SAndroid Build Coastguard Worker errors and boundary conditions (e.g. overflow, truncation, etc.). 13*635a8641SAndroid Build Coastguard Worker* `clamped_math.h` contains the `ClampedNumeric` template class and 14*635a8641SAndroid Build Coastguard Worker helper functions for performing fast, clamped (i.e. non-sticky saturating) 15*635a8641SAndroid Build Coastguard Worker arithmetic operations and conversions. 16*635a8641SAndroid Build Coastguard Worker* `safe_conversions.h` contains the `StrictNumeric` template class and 17*635a8641SAndroid Build Coastguard Worker a collection of custom casting templates and helper functions for safely 18*635a8641SAndroid Build Coastguard Worker converting between a range of numeric types. 19*635a8641SAndroid Build Coastguard Worker* `safe_math.h` includes all of the previously mentioned headers. 20*635a8641SAndroid Build Coastguard Worker 21*635a8641SAndroid Build Coastguard Worker*** aside 22*635a8641SAndroid Build Coastguard Worker**Note:** The `Numeric` template types implicitly convert from C numeric types 23*635a8641SAndroid Build Coastguard Workerand `Numeric` templates that are convertable to an underlying C numeric type. 24*635a8641SAndroid Build Coastguard WorkerThe conversion priority for `Numeric` type coercions is: 25*635a8641SAndroid Build Coastguard Worker 26*635a8641SAndroid Build Coastguard Worker* `StrictNumeric` coerces to `ClampedNumeric` and `CheckedNumeric` 27*635a8641SAndroid Build Coastguard Worker* `ClampedNumeric` coerces to `CheckedNumeric` 28*635a8641SAndroid Build Coastguard Worker*** 29*635a8641SAndroid Build Coastguard Worker 30*635a8641SAndroid Build Coastguard Worker[TOC] 31*635a8641SAndroid Build Coastguard Worker 32*635a8641SAndroid Build Coastguard Worker## Common patterns and use-cases 33*635a8641SAndroid Build Coastguard Worker 34*635a8641SAndroid Build Coastguard WorkerThe following covers the preferred style for the most common uses of this 35*635a8641SAndroid Build Coastguard Workerlibrary. Please don't cargo-cult from anywhere else. 36*635a8641SAndroid Build Coastguard Worker 37*635a8641SAndroid Build Coastguard Worker### Performing checked arithmetic conversions 38*635a8641SAndroid Build Coastguard Worker 39*635a8641SAndroid Build Coastguard WorkerThe `checked_cast` template converts between arbitrary arithmetic types, and is 40*635a8641SAndroid Build Coastguard Workerused for cases where a conversion failure should result in program termination: 41*635a8641SAndroid Build Coastguard Worker 42*635a8641SAndroid Build Coastguard Worker```cpp 43*635a8641SAndroid Build Coastguard Worker// Crash if signed_value is out of range for buff_size. 44*635a8641SAndroid Build Coastguard Workersize_t buff_size = checked_cast<size_t>(signed_value); 45*635a8641SAndroid Build Coastguard Worker``` 46*635a8641SAndroid Build Coastguard Worker 47*635a8641SAndroid Build Coastguard Worker### Performing saturated (clamped) arithmetic conversions 48*635a8641SAndroid Build Coastguard Worker 49*635a8641SAndroid Build Coastguard WorkerThe `saturated_cast` template converts between arbitrary arithmetic types, and 50*635a8641SAndroid Build Coastguard Workeris used in cases where an out-of-bounds source value should be saturated to the 51*635a8641SAndroid Build Coastguard Workercorresponding maximum or minimum of the destination type: 52*635a8641SAndroid Build Coastguard Worker 53*635a8641SAndroid Build Coastguard Worker```cpp 54*635a8641SAndroid Build Coastguard Worker// Convert from float with saturation to INT_MAX, INT_MIN, or 0 for NaN. 55*635a8641SAndroid Build Coastguard Workerint int_value = saturated_cast<int>(floating_point_value); 56*635a8641SAndroid Build Coastguard Worker``` 57*635a8641SAndroid Build Coastguard Worker 58*635a8641SAndroid Build Coastguard Worker### Enforcing arithmetic conversions at compile-time 59*635a8641SAndroid Build Coastguard Worker 60*635a8641SAndroid Build Coastguard WorkerThe `strict_cast` enforces type restrictions at compile-time and results in 61*635a8641SAndroid Build Coastguard Workeremitted code that is identical to a normal `static_cast`. However, a 62*635a8641SAndroid Build Coastguard Worker`strict_cast` assignment will fail to compile if the destination type cannot 63*635a8641SAndroid Build Coastguard Workerrepresent the full range of the source type: 64*635a8641SAndroid Build Coastguard Worker 65*635a8641SAndroid Build Coastguard Worker```cpp 66*635a8641SAndroid Build Coastguard Worker// Throw a compiler error if byte_value is changed to an out-of-range-type. 67*635a8641SAndroid Build Coastguard Workerint int_value = strict_cast<int>(byte_value); 68*635a8641SAndroid Build Coastguard Worker``` 69*635a8641SAndroid Build Coastguard Worker 70*635a8641SAndroid Build Coastguard WorkerYou can also enforce these compile-time restrictions on function parameters by 71*635a8641SAndroid Build Coastguard Workerusing the `StrictNumeric` template: 72*635a8641SAndroid Build Coastguard Worker 73*635a8641SAndroid Build Coastguard Worker```cpp 74*635a8641SAndroid Build Coastguard Worker// Throw a compiler error if the size argument cannot be represented by a 75*635a8641SAndroid Build Coastguard Worker// size_t (e.g. passing an int will fail to compile). 76*635a8641SAndroid Build Coastguard Workerbool AllocateBuffer(void** buffer, StrictCast<size_t> size); 77*635a8641SAndroid Build Coastguard Worker``` 78*635a8641SAndroid Build Coastguard Worker 79*635a8641SAndroid Build Coastguard Worker### Comparing values between arbitrary arithmetic types 80*635a8641SAndroid Build Coastguard Worker 81*635a8641SAndroid Build Coastguard WorkerBoth the `StrictNumeric` and `ClampedNumeric` types provide well defined 82*635a8641SAndroid Build Coastguard Workercomparisons between arbitrary arithmetic types. This allows you to perform 83*635a8641SAndroid Build Coastguard Workercomparisons that are not legal or would trigger compiler warnings or errors 84*635a8641SAndroid Build Coastguard Workerunder the normal arithmetic promotion rules: 85*635a8641SAndroid Build Coastguard Worker 86*635a8641SAndroid Build Coastguard Worker```cpp 87*635a8641SAndroid Build Coastguard Workerbool foo(unsigned value, int upper_bound) { 88*635a8641SAndroid Build Coastguard Worker // Converting to StrictNumeric allows this comparison to work correctly. 89*635a8641SAndroid Build Coastguard Worker if (MakeStrictNum(value) >= upper_bound) 90*635a8641SAndroid Build Coastguard Worker return false; 91*635a8641SAndroid Build Coastguard Worker``` 92*635a8641SAndroid Build Coastguard Worker 93*635a8641SAndroid Build Coastguard Worker*** note 94*635a8641SAndroid Build Coastguard Worker**Warning:** Do not perform manual conversions using the comparison operators. 95*635a8641SAndroid Build Coastguard WorkerInstead, use the cast templates described in the previous sections, or the 96*635a8641SAndroid Build Coastguard Workerconstexpr template functions `IsValueInRangeForNumericType` and 97*635a8641SAndroid Build Coastguard Worker`IsTypeInRangeForNumericType`, as these templates properly handle the full range 98*635a8641SAndroid Build Coastguard Workerof corner cases and employ various optimizations. 99*635a8641SAndroid Build Coastguard Worker*** 100*635a8641SAndroid Build Coastguard Worker 101*635a8641SAndroid Build Coastguard Worker### Calculating a buffer size (checked arithmetic) 102*635a8641SAndroid Build Coastguard Worker 103*635a8641SAndroid Build Coastguard WorkerWhen making exact calculations—such as for buffer lengths—it's often necessary 104*635a8641SAndroid Build Coastguard Workerto know when those calculations trigger an overflow, undefined behavior, or 105*635a8641SAndroid Build Coastguard Workerother boundary conditions. The `CheckedNumeric` template does this by storing 106*635a8641SAndroid Build Coastguard Workera bit determining whether or not some arithmetic operation has occured that 107*635a8641SAndroid Build Coastguard Workerwould put the variable in an "invalid" state. Attempting to extract the value 108*635a8641SAndroid Build Coastguard Workerfrom a variable in an invalid state will trigger a check/trap condition, that 109*635a8641SAndroid Build Coastguard Workerby default will result in process termination. 110*635a8641SAndroid Build Coastguard Worker 111*635a8641SAndroid Build Coastguard WorkerHere's an example of a buffer calculation using a `CheckedNumeric` type (note: 112*635a8641SAndroid Build Coastguard Workerthe AssignIfValid method will trigger a compile error if the result is ignored). 113*635a8641SAndroid Build Coastguard Worker 114*635a8641SAndroid Build Coastguard Worker```cpp 115*635a8641SAndroid Build Coastguard Worker// Calculate the buffer size and detect if an overflow occurs. 116*635a8641SAndroid Build Coastguard Workersize_t size; 117*635a8641SAndroid Build Coastguard Workerif (!CheckAdd(kHeaderSize, CheckMul(count, kItemSize)).AssignIfValid(&size)) { 118*635a8641SAndroid Build Coastguard Worker // Handle an overflow error... 119*635a8641SAndroid Build Coastguard Worker} 120*635a8641SAndroid Build Coastguard Worker``` 121*635a8641SAndroid Build Coastguard Worker 122*635a8641SAndroid Build Coastguard Worker### Calculating clamped coordinates (non-sticky saturating arithmetic) 123*635a8641SAndroid Build Coastguard Worker 124*635a8641SAndroid Build Coastguard WorkerCertain classes of calculations—such as coordinate calculations—require 125*635a8641SAndroid Build Coastguard Workerwell-defined semantics that always produce a valid result on boundary 126*635a8641SAndroid Build Coastguard Workerconditions. The `ClampedNumeric` template addresses this by providing 127*635a8641SAndroid Build Coastguard Workerperformant, non-sticky saturating arithmetic operations. 128*635a8641SAndroid Build Coastguard Worker 129*635a8641SAndroid Build Coastguard WorkerHere's an example of using a `ClampedNumeric` to calculate an operation 130*635a8641SAndroid Build Coastguard Workerinsetting a rectangle. 131*635a8641SAndroid Build Coastguard Worker 132*635a8641SAndroid Build Coastguard Worker```cpp 133*635a8641SAndroid Build Coastguard Worker// Use clamped arithmetic since inset calculations might overflow. 134*635a8641SAndroid Build Coastguard Workervoid Rect::Inset(int left, int top, int right, int bottom) { 135*635a8641SAndroid Build Coastguard Worker origin_ += Vector2d(left, top); 136*635a8641SAndroid Build Coastguard Worker set_width(ClampSub(width(), ClampAdd(left, right))); 137*635a8641SAndroid Build Coastguard Worker set_height(ClampSub(height(), ClampAdd(top, bottom))); 138*635a8641SAndroid Build Coastguard Worker} 139*635a8641SAndroid Build Coastguard Worker``` 140*635a8641SAndroid Build Coastguard Worker 141*635a8641SAndroid Build Coastguard Worker*** note 142*635a8641SAndroid Build Coastguard WorkerThe `ClampedNumeric` type is not "sticky", which means the saturation is not 143*635a8641SAndroid Build Coastguard Workerretained across individual operations. As such, one arithmetic operation may 144*635a8641SAndroid Build Coastguard Workerresult in a saturated value, while the next operation may then "desaturate" 145*635a8641SAndroid Build Coastguard Workerthe value. Here's an example: 146*635a8641SAndroid Build Coastguard Worker 147*635a8641SAndroid Build Coastguard Worker```cpp 148*635a8641SAndroid Build Coastguard WorkerClampedNumeric<int> value = INT_MAX; 149*635a8641SAndroid Build Coastguard Worker++value; // value is still INT_MAX, due to saturation. 150*635a8641SAndroid Build Coastguard Worker--value; // value is now (INT_MAX - 1), because saturation is not sticky. 151*635a8641SAndroid Build Coastguard Worker``` 152*635a8641SAndroid Build Coastguard Worker 153*635a8641SAndroid Build Coastguard Worker*** 154*635a8641SAndroid Build Coastguard Worker 155*635a8641SAndroid Build Coastguard Worker## Conversion functions and StrictNumeric<> in safe_conversions.h 156*635a8641SAndroid Build Coastguard Worker 157*635a8641SAndroid Build Coastguard WorkerThis header includes a collection of helper `constexpr` templates for safely 158*635a8641SAndroid Build Coastguard Workerperforming a range of conversions, assignments, and tests. 159*635a8641SAndroid Build Coastguard Worker 160*635a8641SAndroid Build Coastguard Worker### Safe casting templates 161*635a8641SAndroid Build Coastguard Worker 162*635a8641SAndroid Build Coastguard Worker* `as_signed()` - Returns the supplied integral value as a signed type of 163*635a8641SAndroid Build Coastguard Worker the same width. 164*635a8641SAndroid Build Coastguard Worker* `as_unsigned()` - Returns the supplied integral value as an unsigned type 165*635a8641SAndroid Build Coastguard Worker of the same width. 166*635a8641SAndroid Build Coastguard Worker* `checked_cast<>()` - Analogous to `static_cast<>` for numeric types, except 167*635a8641SAndroid Build Coastguard Worker that by default it will trigger a crash on an out-of-bounds conversion (e.g. 168*635a8641SAndroid Build Coastguard Worker overflow, underflow, NaN to integral) or a compile error if the conversion 169*635a8641SAndroid Build Coastguard Worker error can be detected at compile time. The crash handler can be overridden 170*635a8641SAndroid Build Coastguard Worker to perform a behavior other than crashing. 171*635a8641SAndroid Build Coastguard Worker* `saturated_cast<>()` - Analogous to `static_cast` for numeric types, except 172*635a8641SAndroid Build Coastguard Worker that it returns a saturated result when the specified numeric conversion 173*635a8641SAndroid Build Coastguard Worker would otherwise overflow or underflow. An NaN source returns 0 by 174*635a8641SAndroid Build Coastguard Worker default, but can be overridden to return a different result. 175*635a8641SAndroid Build Coastguard Worker* `strict_cast<>()` - Analogous to `static_cast` for numeric types, except 176*635a8641SAndroid Build Coastguard Worker this causes a compile failure if the destination type is not large 177*635a8641SAndroid Build Coastguard Worker enough to contain any value in the source type. It performs no runtime 178*635a8641SAndroid Build Coastguard Worker checking and thus introduces no runtime overhead. 179*635a8641SAndroid Build Coastguard Worker 180*635a8641SAndroid Build Coastguard Worker### Other helper and conversion functions 181*635a8641SAndroid Build Coastguard Worker 182*635a8641SAndroid Build Coastguard Worker* `IsValueInRangeForNumericType<>()` - A convenience function that returns 183*635a8641SAndroid Build Coastguard Worker true if the type supplied as the template parameter can represent the value 184*635a8641SAndroid Build Coastguard Worker passed as an argument to the function. 185*635a8641SAndroid Build Coastguard Worker* `IsTypeInRangeForNumericType<>()` - A convenience function that evaluates 186*635a8641SAndroid Build Coastguard Worker entirely at compile-time and returns true if the destination type (first 187*635a8641SAndroid Build Coastguard Worker template parameter) can represent the full range of the source type 188*635a8641SAndroid Build Coastguard Worker (second template parameter). 189*635a8641SAndroid Build Coastguard Worker* `IsValueNegative()` - A convenience function that will accept any 190*635a8641SAndroid Build Coastguard Worker arithmetic type as an argument and will return whether the value is less 191*635a8641SAndroid Build Coastguard Worker than zero. Unsigned types always return false. 192*635a8641SAndroid Build Coastguard Worker* `SafeUnsignedAbs()` - Returns the absolute value of the supplied integer 193*635a8641SAndroid Build Coastguard Worker parameter as an unsigned result (thus avoiding an overflow if the value 194*635a8641SAndroid Build Coastguard Worker is the signed, two's complement minimum). 195*635a8641SAndroid Build Coastguard Worker 196*635a8641SAndroid Build Coastguard Worker### StrictNumeric<> 197*635a8641SAndroid Build Coastguard Worker 198*635a8641SAndroid Build Coastguard Worker`StrictNumeric<>` is a wrapper type that performs assignments and copies via 199*635a8641SAndroid Build Coastguard Workerthe `strict_cast` template, and can perform valid arithmetic comparisons 200*635a8641SAndroid Build Coastguard Workeracross any range of arithmetic types. `StrictNumeric` is the return type for 201*635a8641SAndroid Build Coastguard Workervalues extracted from a `CheckedNumeric` class instance. The raw numeric value 202*635a8641SAndroid Build Coastguard Workeris extracted via `static_cast` to the underlying type or any type with 203*635a8641SAndroid Build Coastguard Workersufficient range to represent the underlying type. 204*635a8641SAndroid Build Coastguard Worker 205*635a8641SAndroid Build Coastguard Worker* `MakeStrictNum()` - Creates a new `StrictNumeric` from the underlying type 206*635a8641SAndroid Build Coastguard Worker of the supplied arithmetic or StrictNumeric type. 207*635a8641SAndroid Build Coastguard Worker* `SizeT` - Alias for `StrictNumeric<size_t>`. 208*635a8641SAndroid Build Coastguard Worker 209*635a8641SAndroid Build Coastguard Worker## CheckedNumeric<> in checked_math.h 210*635a8641SAndroid Build Coastguard Worker 211*635a8641SAndroid Build Coastguard Worker`CheckedNumeric<>` implements all the logic and operators for detecting integer 212*635a8641SAndroid Build Coastguard Workerboundary conditions such as overflow, underflow, and invalid conversions. 213*635a8641SAndroid Build Coastguard WorkerThe `CheckedNumeric` type implicitly converts from floating point and integer 214*635a8641SAndroid Build Coastguard Workerdata types, and contains overloads for basic arithmetic operations (i.e.: `+`, 215*635a8641SAndroid Build Coastguard Worker`-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers). 216*635a8641SAndroid Build Coastguard WorkerHowever, *the [variadic template functions 217*635a8641SAndroid Build Coastguard Worker](#CheckedNumeric_in-checked_math_h-Non_member-helper-functions) 218*635a8641SAndroid Build Coastguard Workerare the prefered API,* as they remove type ambiguities and help prevent a number 219*635a8641SAndroid Build Coastguard Workerof common errors. The variadic functions can also be more performant, as they 220*635a8641SAndroid Build Coastguard Workereliminate redundant expressions that are unavoidable with the with the operator 221*635a8641SAndroid Build Coastguard Workeroverloads. (Ideally the compiler should optimize those away, but better to avoid 222*635a8641SAndroid Build Coastguard Workerthem in the first place.) 223*635a8641SAndroid Build Coastguard Worker 224*635a8641SAndroid Build Coastguard WorkerType promotions are a slightly modified version of the [standard C/C++ numeric 225*635a8641SAndroid Build Coastguard Workerpromotions 226*635a8641SAndroid Build Coastguard Worker](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) 227*635a8641SAndroid Build Coastguard Workerwith the two differences being that *there is no default promotion to int* 228*635a8641SAndroid Build Coastguard Workerand *bitwise logical operations always return an unsigned of the wider type.* 229*635a8641SAndroid Build Coastguard Worker 230*635a8641SAndroid Build Coastguard Worker### Members 231*635a8641SAndroid Build Coastguard Worker 232*635a8641SAndroid Build Coastguard WorkerThe unary negation, increment, and decrement operators are supported, along 233*635a8641SAndroid Build Coastguard Workerwith the following unary arithmetic methods, which return a new 234*635a8641SAndroid Build Coastguard Worker`CheckedNumeric` as a result of the operation: 235*635a8641SAndroid Build Coastguard Worker 236*635a8641SAndroid Build Coastguard Worker* `Abs()` - Absolute value. 237*635a8641SAndroid Build Coastguard Worker* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type 238*635a8641SAndroid Build Coastguard Worker (valid for only integral types). 239*635a8641SAndroid Build Coastguard Worker* `Max()` - Returns whichever is greater of the current instance or argument. 240*635a8641SAndroid Build Coastguard Worker The underlying return type is whichever has the greatest magnitude. 241*635a8641SAndroid Build Coastguard Worker* `Min()` - Returns whichever is lowest of the current instance or argument. 242*635a8641SAndroid Build Coastguard Worker The underlying return type is whichever has can represent the lowest 243*635a8641SAndroid Build Coastguard Worker number in the smallest width (e.g. int8_t over unsigned, int over 244*635a8641SAndroid Build Coastguard Worker int8_t, and float over int). 245*635a8641SAndroid Build Coastguard Worker 246*635a8641SAndroid Build Coastguard WorkerThe following are for converting `CheckedNumeric` instances: 247*635a8641SAndroid Build Coastguard Worker 248*635a8641SAndroid Build Coastguard Worker* `type` - The underlying numeric type. 249*635a8641SAndroid Build Coastguard Worker* `AssignIfValid()` - Assigns the underlying value to the supplied 250*635a8641SAndroid Build Coastguard Worker destination pointer if the value is currently valid and within the 251*635a8641SAndroid Build Coastguard Worker range supported by the destination type. Returns true on success. 252*635a8641SAndroid Build Coastguard Worker* `Cast<>()` - Instance method returning a `CheckedNumeric` derived from 253*635a8641SAndroid Build Coastguard Worker casting the current instance to a `CheckedNumeric` of the supplied 254*635a8641SAndroid Build Coastguard Worker destination type. 255*635a8641SAndroid Build Coastguard Worker 256*635a8641SAndroid Build Coastguard Worker*** aside 257*635a8641SAndroid Build Coastguard WorkerThe following member functions return a `StrictNumeric`, which is valid for 258*635a8641SAndroid Build Coastguard Workercomparison and assignment operations, but will trigger a compile failure on 259*635a8641SAndroid Build Coastguard Workerattempts to assign to a type of insufficient range. The underlying value can 260*635a8641SAndroid Build Coastguard Workerbe extracted by an explicit `static_cast` to the underlying type or any type 261*635a8641SAndroid Build Coastguard Workerwith sufficient range to represent the underlying type. 262*635a8641SAndroid Build Coastguard Worker*** 263*635a8641SAndroid Build Coastguard Worker 264*635a8641SAndroid Build Coastguard Worker* `IsValid()` - Returns true if the underlying numeric value is valid (i.e. 265*635a8641SAndroid Build Coastguard Worker has not wrapped or saturated and is not the result of an invalid 266*635a8641SAndroid Build Coastguard Worker conversion). 267*635a8641SAndroid Build Coastguard Worker* `ValueOrDie()` - Returns the underlying value. If the state is not valid 268*635a8641SAndroid Build Coastguard Worker this call will trigger a crash by default (but may be overridden by 269*635a8641SAndroid Build Coastguard Worker supplying an alternate handler to the template). 270*635a8641SAndroid Build Coastguard Worker* `ValueOrDefault()` - Returns the current value, or the supplied default if 271*635a8641SAndroid Build Coastguard Worker the state is not valid (but will not crash). 272*635a8641SAndroid Build Coastguard Worker 273*635a8641SAndroid Build Coastguard Worker**Comparison operators are explicitly not provided** for `CheckedNumeric` 274*635a8641SAndroid Build Coastguard Workertypes because they could result in a crash if the type is not in a valid state. 275*635a8641SAndroid Build Coastguard WorkerPatterns like the following should be used instead: 276*635a8641SAndroid Build Coastguard Worker 277*635a8641SAndroid Build Coastguard Worker```cpp 278*635a8641SAndroid Build Coastguard Worker// Either input or padding (or both) may be arbitrary sizes. 279*635a8641SAndroid Build Coastguard Workersize_t buff_size; 280*635a8641SAndroid Build Coastguard Workerif (!CheckAdd(input, padding, kHeaderLength).AssignIfValid(&buff_size) || 281*635a8641SAndroid Build Coastguard Worker buff_size >= kMaxBuffer) { 282*635a8641SAndroid Build Coastguard Worker // Handle an error... 283*635a8641SAndroid Build Coastguard Worker} else { 284*635a8641SAndroid Build Coastguard Worker // Do stuff on success... 285*635a8641SAndroid Build Coastguard Worker} 286*635a8641SAndroid Build Coastguard Worker``` 287*635a8641SAndroid Build Coastguard Worker 288*635a8641SAndroid Build Coastguard Worker### Non-member helper functions 289*635a8641SAndroid Build Coastguard Worker 290*635a8641SAndroid Build Coastguard WorkerThe following variadic convenience functions, which accept standard arithmetic 291*635a8641SAndroid Build Coastguard Workeror `CheckedNumeric` types, perform arithmetic operations, and return a 292*635a8641SAndroid Build Coastguard Worker`CheckedNumeric` result. The supported functions are: 293*635a8641SAndroid Build Coastguard Worker 294*635a8641SAndroid Build Coastguard Worker* `CheckAdd()` - Addition. 295*635a8641SAndroid Build Coastguard Worker* `CheckSub()` - Subtraction. 296*635a8641SAndroid Build Coastguard Worker* `CheckMul()` - Multiplication. 297*635a8641SAndroid Build Coastguard Worker* `CheckDiv()` - Division. 298*635a8641SAndroid Build Coastguard Worker* `CheckMod()` - Modulus (integer only). 299*635a8641SAndroid Build Coastguard Worker* `CheckLsh()` - Left integer shift (integer only). 300*635a8641SAndroid Build Coastguard Worker* `CheckRsh()` - Right integer shift (integer only). 301*635a8641SAndroid Build Coastguard Worker* `CheckAnd()` - Bitwise AND (integer only with unsigned result). 302*635a8641SAndroid Build Coastguard Worker* `CheckOr()` - Bitwise OR (integer only with unsigned result). 303*635a8641SAndroid Build Coastguard Worker* `CheckXor()` - Bitwise XOR (integer only with unsigned result). 304*635a8641SAndroid Build Coastguard Worker* `CheckMax()` - Maximum of supplied arguments. 305*635a8641SAndroid Build Coastguard Worker* `CheckMin()` - Minimum of supplied arguments. 306*635a8641SAndroid Build Coastguard Worker 307*635a8641SAndroid Build Coastguard WorkerThe following wrapper functions can be used to avoid the template 308*635a8641SAndroid Build Coastguard Workerdisambiguator syntax when converting a destination type. 309*635a8641SAndroid Build Coastguard Worker 310*635a8641SAndroid Build Coastguard Worker* `IsValidForType<>()` in place of: `a.template IsValid<>()` 311*635a8641SAndroid Build Coastguard Worker* `ValueOrDieForType<>()` in place of: `a.template ValueOrDie<>()` 312*635a8641SAndroid Build Coastguard Worker* `ValueOrDefaultForType<>()` in place of: `a.template ValueOrDefault<>()` 313*635a8641SAndroid Build Coastguard Worker 314*635a8641SAndroid Build Coastguard WorkerThe following general utility methods is are useful for converting from 315*635a8641SAndroid Build Coastguard Workerarithmetic types to `CheckedNumeric` types: 316*635a8641SAndroid Build Coastguard Worker 317*635a8641SAndroid Build Coastguard Worker* `MakeCheckedNum()` - Creates a new `CheckedNumeric` from the underlying type 318*635a8641SAndroid Build Coastguard Worker of the supplied arithmetic or directly convertible type. 319*635a8641SAndroid Build Coastguard Worker 320*635a8641SAndroid Build Coastguard Worker## ClampedNumeric<> in clamped_math.h 321*635a8641SAndroid Build Coastguard Worker 322*635a8641SAndroid Build Coastguard Worker`ClampedNumeric<>` implements all the logic and operators for clamped 323*635a8641SAndroid Build Coastguard Worker(non-sticky saturating) arithmetic operations and conversions. The 324*635a8641SAndroid Build Coastguard Worker`ClampedNumeric` type implicitly converts back and forth between floating point 325*635a8641SAndroid Build Coastguard Workerand integer data types, saturating on assignment as appropriate. It contains 326*635a8641SAndroid Build Coastguard Workeroverloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for 327*635a8641SAndroid Build Coastguard Workerall types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers) along with comparison 328*635a8641SAndroid Build Coastguard Workeroperators for arithmetic types of any size. However, *the [variadic template 329*635a8641SAndroid Build Coastguard Workerfunctions 330*635a8641SAndroid Build Coastguard Worker](#ClampedNumeric_in-clamped_math_h-Non_member-helper-functions) 331*635a8641SAndroid Build Coastguard Workerare the prefered API,* as they remove type ambiguities and help prevent 332*635a8641SAndroid Build Coastguard Workera number of common errors. The variadic functions can also be more performant, 333*635a8641SAndroid Build Coastguard Workeras they eliminate redundant expressions that are unavoidable with the operator 334*635a8641SAndroid Build Coastguard Workeroverloads. (Ideally the compiler should optimize those away, but better to avoid 335*635a8641SAndroid Build Coastguard Workerthem in the first place.) 336*635a8641SAndroid Build Coastguard Worker 337*635a8641SAndroid Build Coastguard WorkerType promotions are a slightly modified version of the [standard C/C++ numeric 338*635a8641SAndroid Build Coastguard Workerpromotions 339*635a8641SAndroid Build Coastguard Worker](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) 340*635a8641SAndroid Build Coastguard Workerwith the two differences being that *there is no default promotion to int* 341*635a8641SAndroid Build Coastguard Workerand *bitwise logical operations always return an unsigned of the wider type.* 342*635a8641SAndroid Build Coastguard Worker 343*635a8641SAndroid Build Coastguard Worker*** aside 344*635a8641SAndroid Build Coastguard WorkerMost arithmetic operations saturate normally, to the numeric limit in the 345*635a8641SAndroid Build Coastguard Workerdirection of the sign. The potentially unusual cases are: 346*635a8641SAndroid Build Coastguard Worker 347*635a8641SAndroid Build Coastguard Worker* **Division:** Division by zero returns the saturated limit in the direction 348*635a8641SAndroid Build Coastguard Worker of sign of the dividend (first argument). The one exception is 0/0, which 349*635a8641SAndroid Build Coastguard Worker returns zero (although logically is NaN). 350*635a8641SAndroid Build Coastguard Worker* **Modulus:** Division by zero returns the dividend (first argument). 351*635a8641SAndroid Build Coastguard Worker* **Left shift:** Non-zero values saturate in the direction of the signed 352*635a8641SAndroid Build Coastguard Worker limit (max/min), even for shifts larger than the bit width. 0 shifted any 353*635a8641SAndroid Build Coastguard Worker amount results in 0. 354*635a8641SAndroid Build Coastguard Worker* **Right shift:** Negative values saturate to -1. Positive or 0 saturates 355*635a8641SAndroid Build Coastguard Worker to 0. (Effectively just an unbounded arithmetic-right-shift.) 356*635a8641SAndroid Build Coastguard Worker* **Bitwise operations:** No saturation; bit pattern is identical to 357*635a8641SAndroid Build Coastguard Worker non-saturated bitwise operations. 358*635a8641SAndroid Build Coastguard Worker*** 359*635a8641SAndroid Build Coastguard Worker 360*635a8641SAndroid Build Coastguard Worker### Members 361*635a8641SAndroid Build Coastguard Worker 362*635a8641SAndroid Build Coastguard WorkerThe unary negation, increment, and decrement operators are supported, along 363*635a8641SAndroid Build Coastguard Workerwith the following unary arithmetic methods, which return a new 364*635a8641SAndroid Build Coastguard Worker`ClampedNumeric` as a result of the operation: 365*635a8641SAndroid Build Coastguard Worker 366*635a8641SAndroid Build Coastguard Worker* `Abs()` - Absolute value. 367*635a8641SAndroid Build Coastguard Worker* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type 368*635a8641SAndroid Build Coastguard Worker (valid for only integral types). 369*635a8641SAndroid Build Coastguard Worker* `Max()` - Returns whichever is greater of the current instance or argument. 370*635a8641SAndroid Build Coastguard Worker The underlying return type is whichever has the greatest magnitude. 371*635a8641SAndroid Build Coastguard Worker* `Min()` - Returns whichever is lowest of the current instance or argument. 372*635a8641SAndroid Build Coastguard Worker The underlying return type is whichever has can represent the lowest 373*635a8641SAndroid Build Coastguard Worker number in the smallest width (e.g. int8_t over unsigned, int over 374*635a8641SAndroid Build Coastguard Worker int8_t, and float over int). 375*635a8641SAndroid Build Coastguard Worker 376*635a8641SAndroid Build Coastguard WorkerThe following are for converting `ClampedNumeric` instances: 377*635a8641SAndroid Build Coastguard Worker 378*635a8641SAndroid Build Coastguard Worker* `type` - The underlying numeric type. 379*635a8641SAndroid Build Coastguard Worker* `RawValue()` - Returns the raw value as the underlying arithmetic type. This 380*635a8641SAndroid Build Coastguard Worker is useful when e.g. assigning to an auto type or passing as a deduced 381*635a8641SAndroid Build Coastguard Worker template parameter. 382*635a8641SAndroid Build Coastguard Worker* `Cast<>()` - Instance method returning a `ClampedNumeric` derived from 383*635a8641SAndroid Build Coastguard Worker casting the current instance to a `ClampedNumeric` of the supplied 384*635a8641SAndroid Build Coastguard Worker destination type. 385*635a8641SAndroid Build Coastguard Worker 386*635a8641SAndroid Build Coastguard Worker### Non-member helper functions 387*635a8641SAndroid Build Coastguard Worker 388*635a8641SAndroid Build Coastguard WorkerThe following variadic convenience functions, which accept standard arithmetic 389*635a8641SAndroid Build Coastguard Workeror `ClampedNumeric` types, perform arithmetic operations, and return a 390*635a8641SAndroid Build Coastguard Worker`ClampedNumeric` result. The supported functions are: 391*635a8641SAndroid Build Coastguard Worker 392*635a8641SAndroid Build Coastguard Worker* `ClampAdd()` - Addition. 393*635a8641SAndroid Build Coastguard Worker* `ClampSub()` - Subtraction. 394*635a8641SAndroid Build Coastguard Worker* `ClampMul()` - Multiplication. 395*635a8641SAndroid Build Coastguard Worker* `ClampDiv()` - Division. 396*635a8641SAndroid Build Coastguard Worker* `ClampMod()` - Modulus (integer only). 397*635a8641SAndroid Build Coastguard Worker* `ClampLsh()` - Left integer shift (integer only). 398*635a8641SAndroid Build Coastguard Worker* `ClampRsh()` - Right integer shift (integer only). 399*635a8641SAndroid Build Coastguard Worker* `ClampAnd()` - Bitwise AND (integer only with unsigned result). 400*635a8641SAndroid Build Coastguard Worker* `ClampOr()` - Bitwise OR (integer only with unsigned result). 401*635a8641SAndroid Build Coastguard Worker* `ClampXor()` - Bitwise XOR (integer only with unsigned result). 402*635a8641SAndroid Build Coastguard Worker* `ClampMax()` - Maximum of supplied arguments. 403*635a8641SAndroid Build Coastguard Worker* `ClampMin()` - Minimum of supplied arguments. 404*635a8641SAndroid Build Coastguard Worker 405*635a8641SAndroid Build Coastguard WorkerThe following is a general utility method that is useful for converting 406*635a8641SAndroid Build Coastguard Workerto a `ClampedNumeric` type: 407*635a8641SAndroid Build Coastguard Worker 408*635a8641SAndroid Build Coastguard Worker* `MakeClampedNum()` - Creates a new `ClampedNumeric` from the underlying type 409*635a8641SAndroid Build Coastguard Worker of the supplied arithmetic or directly convertible type. 410