diff mbox

[rdma-core,1/2] ccan: Add array_size.h file

Message ID 1528190318-18563-2-git-send-email-yishaih@mellanox.com (mailing list archive)
State Not Applicable
Headers show

Commit Message

Yishai Hadas June 5, 2018, 9:18 a.m. UTC
From: Parav Pandit <parav@mellanox.com>

Add array_size.h file for ARRAY_SIZE macro.

Signed-off-by: Parav Pandit <parav@mellanox.com>
Signed-off-by: Yishai Hadas <yishaih@mellanox.com>
---
 ccan/CMakeLists.txt |  1 +
 ccan/array_size.h   | 26 ++++++++++++++++++++++++++
 2 files changed, 27 insertions(+)
 create mode 100644 ccan/array_size.h
diff mbox

Patch

diff --git a/ccan/CMakeLists.txt b/ccan/CMakeLists.txt
index 1793af7..573aa5a 100644
--- a/ccan/CMakeLists.txt
+++ b/ccan/CMakeLists.txt
@@ -1,4 +1,5 @@ 
 publish_internal_headers(ccan
+  array_size.h
   bitmap.h
   build_assert.h
   check_type.h
diff --git a/ccan/array_size.h b/ccan/array_size.h
new file mode 100644
index 0000000..37b200f
--- /dev/null
+++ b/ccan/array_size.h
@@ -0,0 +1,26 @@ 
+/* CC0 (Public domain) - see LICENSE file for details */
+#ifndef CCAN_ARRAY_SIZE_H
+#define CCAN_ARRAY_SIZE_H
+#include "config.h"
+#include <ccan/build_assert.h>
+
+/**
+ * ARRAY_SIZE - get the number of elements in a visible array
+ * @arr: the array whose size you want.
+ *
+ * This does not work on pointers, or arrays declared as [], or
+ * function parameters.  With correct compiler support, such usage
+ * will cause a build error (see build_assert).
+ */
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + _array_size_chk(arr))
+
+#if HAVE_BUILTIN_TYPES_COMPATIBLE_P && HAVE_TYPEOF
+/* Two gcc extensions.
+ * &a[0] degrades to a pointer: a different type from an array */
+#define _array_size_chk(arr)						\
+	BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(typeof(arr),	\
+							typeof(&(arr)[0])))
+#else
+#define _array_size_chk(arr) 0
+#endif
+#endif /* CCAN_ALIGNOF_H */