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:
@@ -346,6 +346,15 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
decltype(auto) abs_diff(const T &a, const T &b)
|
||||
{
|
||||
if (a < b)
|
||||
return b - a;
|
||||
else
|
||||
return a - b;
|
||||
}
|
||||
|
||||
} /* namespace utils */
|
||||
|
||||
#ifndef __DOXYGEN__
|
||||
|
||||
Reference in New Issue
Block a user