You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nuttx.apache.org by xi...@apache.org on 2025/11/24 06:11:48 UTC
(nuttx) 01/03: include: add BSD rounding macros to sys/param.h
This is an automated email from the ASF dual-hosted git repository.
xiaoxiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git
commit b9066e42bbabc6a1cc72d64b80d511a91e08cd51
Author: Karel Kočí <kk...@elektroline.cz>
AuthorDate: Thu Nov 20 17:19:54 2025 +0100
include: add BSD rounding macros to sys/param.h
These macros are commonly provided on BSD systems. They are not part of
C nor POSIX but these types of operations can be required in drivers
implementation as well as in user space. The operations themself are
simple but kind of cryptic when placed in the code as is. Thus having
macro with an appropriate name is beneficial.
The use of BSD naming here is only to cling to at least some other
implementation instead of creating completelly NuttX specific one.
Kudos to @hartmannathan for the source code documentation.
Signed-off-by: Karel Kočí <kk...@elektroline.cz>
---
include/sys/param.h | 45 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/include/sys/param.h b/include/sys/param.h
index 1e0ad74a8b3..ff7ebb38ae3 100644
--- a/include/sys/param.h
+++ b/include/sys/param.h
@@ -53,6 +53,51 @@
# define nitems(_a) (sizeof(_a) / sizeof(0[(_a)]))
#endif /* nitems */
+/* Macros for counting and rounding.
+ *
+ * These macros accept value to be rounded or checked as 'a' and base as 'b'.
+ * They are consistent with those provided by some BSDs.
+ *
+ * howmany() calculates how many b fit into a.
+ *
+ * rounddown() and roundup() round a to the next b.
+ *
+ * rounddown2() and roundup2() are for powers of 2 only.
+ *
+ * powerof2() returns 1 if a is a power of 2, 0 otherwise.
+ *
+ * Warning: rounddown2() and roundup2() can be used only if b is power of 2,
+ * otherwise they will produce wrong result.
+ *
+ * In all of these macros, outcome is undefined if b is 0.
+ *
+ * All parameters are assumed to be unsigned integers.
+ */
+
+#ifndef howmany
+# define howmany(a, b) (((a) + ((b) - 1)) / (b))
+#endif /* howmany */
+
+#ifndef rounddown
+# define rounddown(a, b) (((a) / (b)) * (b))
+#endif /* rounddown */
+
+#ifndef rounddown2
+# define rounddown2(a, b) ((a) & ~((b) - 1))
+#endif /* rounddown2 */
+
+#ifndef roundup
+# define roundup(a, b) ((((a) + ((b) - 1)) / (b)) * (b))
+#endif /* roundup */
+
+#ifndef roundup2
+# define roundup2(a, b) (((a) + ((b) - 1)) & ~((b) - 1))
+#endif /* roundup2 */
+
+#ifndef powerof2
+# define powerof2(a) (!(((a) - 1) & (a)))
+#endif /* powerof2 */
+
/****************************************************************************
* Public Type Definitions
****************************************************************************/