Exiv2
Namespaces | Functions
Safe Namespace Reference

Arithmetic operations with overflow checks. More...

Namespaces

 Internal
 Helper functions for providing integer overflow checks.
 

Functions

template<typename 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...
 

Detailed Description

Arithmetic operations with overflow checks.

Function Documentation

◆ abs()

template<typename T >
Internal::enable_if<Internal::is_signed<T>::VALUE, T>::type Safe::abs ( 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.

Template Parameters
Ta signed integer type
Parameters
[in]numThe number which absolute value should be computed.
Exceptions
Neverthrows an exception.
Returns
The absolute value of num or std::numeric_limits<T>::max() when num == std::numeric_limits<T>::min().
Examples:
geotag.cpp.

Referenced by Exiv2::TimeValue::copy(), Exiv2::floatToRationalCast(), Exiv2::Internal::print0x9204(), Exiv2::Internal::Nikon3MakerNote::printTimeZone(), and Exiv2::TimeValue::write().

◆ add()

template<typename T >
T Safe::add ( summand_1,
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.

Parameters
[in]summand_1,summand_2summands to be summed up
Returns
the sum of summand_1 and summand_2
Exceptions
std::overflow_errorif 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:

  • GCC/Clang for signed and unsigned int, long and long long (not char & short)
  • MSVC for unsigned int, long and long long

Referenced by Exiv2::Image::printIFDStructure(), Exiv2::WebPImage::readMetadata(), Exiv2::Jp2Image::readMetadata(), Exiv2::RafImage::readMetadata(), and Exiv2::JpegBase::readMetadata().