![]() |
Exiv2
|
Arithmetic operations with overflow checks. More...
Namespaces | |
Internal | |
Helper functions for providing integer overflow checks. | |
Functions | |
template<typename T > | |
T | add (T summand_1, T summand_2) |
Safe addition, throws an exception on overflow. More... | |
template<typename T > | |
Internal::enable_if< Internal::is_signed< T >::VALUE, T >::type | abs (T num) throw () |
Calculates the absolute value of a number without producing negative values. More... | |
Arithmetic operations with overflow checks.
Internal::enable_if<Internal::is_signed<T>::VALUE, T>::type Safe::abs | ( | T | num | ) | |
throw | ( | ||||
) |
Calculates the absolute value of a number without producing negative values.
The "standard" implementation of abs(num)
(num < 0 ? -num : num
) produces negative values when num
is the smallest negative number. This is caused by -1 * INTMAX = INTMIN + 1
, i.e. the real result of abs(INTMIN)
overflows the integer type and results in INTMIN
again (this is not guaranteed as it invokes undefined behavior).
This function does not exhibit this behavior, it returns std::numeric_limits<T>::max()
when the input is std::numeric_limits<T>::min()
. The downside of this is that two negative values produce the same absolute value: std::numeric_limits<T>::min()
and std::numeric_limits<T>::min() + 1
.
T | a signed integer type |
[in] | num | The number which absolute value should be computed. |
Never | throws an exception. |
num
or std::numeric_limits<T>::max()
when num == std::numeric_limits<T>::min()
. Referenced by Exiv2::TimeValue::copy(), Exiv2::floatToRationalCast(), Exiv2::Internal::print0x9204(), Exiv2::Internal::Nikon3MakerNote::printTimeZone(), and Exiv2::TimeValue::write().
T Safe::add | ( | T | summand_1, |
T | summand_2 | ||
) |
Safe addition, throws an exception on overflow.
This function returns the result of summand_1 and summand_2 only when the operation would not overflow, otherwise an exception of type std::overflow_error is thrown.
[in] | summand_1,summand_2 | summands to be summed up |
std::overflow_error | if the addition would overflow |
This function utilizes compiler builtins when available and should have a very small performance hit then. When builtins are unavailable, a more extensive check is required.
Builtins are available for the following configurations:
Referenced by Exiv2::Image::printIFDStructure(), Exiv2::WebPImage::readMetadata(), Exiv2::Jp2Image::readMetadata(), Exiv2::RafImage::readMetadata(), and Exiv2::JpegBase::readMetadata().