Safe Namespace Reference

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

## 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 | ( | 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`.

Template Parameters

  T | a signed integer type

Parameters

  [in] | num | The number which absolute value should be computed.

Exceptions

  Never | throws an exception.

Returns
  The absolute value of `num` or `std::numeric_limits<T>::max()` when `num == std::numeric_limits<T>::min()`.

Referenced by Exiv2::floatToRationalCast().

## add()

template<typename T >

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.

Parameters

  [in] | summand_1,summand_2 | summands to be summed up

Returns
  the sum of summand_1 and summand_2

Exceptions

  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:

- 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::Jp2Image::readMetadata(), Exiv2::JpegBase::readMetadata(), Exiv2::RafImage::readMetadata(), and Exiv2::WebPImage::readMetadata().