From f413f944d789911c9ded831ac45a7674c129ceba Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Mon, 6 Dec 2021 16:21:19 +0200 Subject: 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(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 Reviewed-by: Kieran Bingham Reviewed-by: Umang Jain --- include/libcamera/base/utils.h | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'include') diff --git a/include/libcamera/base/utils.h b/include/libcamera/base/utils.h index 3a803176..9ab18101 100644 --- a/include/libcamera/base/utils.h +++ b/include/libcamera/base/utils.h @@ -346,6 +346,15 @@ public: } }; +template +decltype(auto) abs_diff(const T &a, const T &b) +{ + if (a < b) + return b - a; + else + return a - b; +} + } /* namespace utils */ #ifndef __DOXYGEN__ -- cgit v1.2.1