summaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
authorLaurent Pinchart <laurent.pinchart@ideasonboard.com>2021-12-06 16:21:19 +0200
committerLaurent Pinchart <laurent.pinchart@ideasonboard.com>2021-12-07 19:09:31 +0200
commitf413f944d789911c9ded831ac45a7674c129ceba (patch)
treec09d9d0e96e9e504d3a35c7d02e5c31d33908b1b /include
parent72679c682eb0b9f03948f258a26f78c037d33c48 (diff)
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>
Diffstat (limited to 'include')
-rw-r--r--include/libcamera/base/utils.h9
1 files changed, 9 insertions, 0 deletions
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<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__