libcamera: base: utils: Add abs_diff() utility function

The abs_diff() function computes the absolute difference of two
elements. This may seem trivial at first, but can lead to unexpected
results when operating on unsigned operands. A common implementation
of the absolute difference of two unsigned int (used through the
libcamera code base) is

	std::abs(static_cast<int>(a - b))

but doesn't return the expected result when either a or b is larger than
UINT_MAX / 2 due to overflows. The abs_diff() function offers a safe
alternative.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Reviewed-by: Umang Jain <umang.jain@ideasonboard.com>
This commit is contained in:
Laurent Pinchart
2021-12-06 16:21:19 +02:00
parent 72679c682e
commit f413f944d7
2 changed files with 26 additions and 0 deletions
+17
View File
@@ -437,6 +437,23 @@ std::string toAscii(const std::string &str)
* \return True if \a Duration is a non-zero time value, False otherwise
*/
/**
* \fn abs_diff(const T& a, const T& b)
* \brief Calculates the absolute value of the difference between two elements
* \param[in] a The first element
* \param[in] b The second element
*
* This function calculates the absolute value of the difference between two
* elements of the same type, in such a way that a negative value will never
* occur during the calculation.
*
* This is inspired by the std::abs_diff() candidate proposed in N4318
* (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4318.pdf).
*
* \return The absolute value of the difference of the two parameters \a a and
* \a b
*/
} /* namespace utils */
#ifndef __DOXYGEN__