util/idalloc: add exists and foreach helpers
authorMarek Olšák <marek.olsak@amd.com>
Mon, 17 May 2021 19:44:50 +0000 (15:44 -0400)
committerMarge Bot <eric+marge@anholt.net>
Fri, 9 Jul 2021 10:05:46 +0000 (10:05 +0000)
Reviewed-by: Pierre-Eric Pelloux-Prayer <pierre-eric.pelloux-prayer@amd.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/11493>

src/util/u_idalloc.h

index c6ba9f8..83f1378 100644 (file)
  *
  **************************************************************************/
 
+/* Allocator of IDs (e.g. OpenGL object IDs), or simply an allocator of
+ * numbers.
+ *
+ * The allocator uses a bit array to track allocated IDs.
+ */
+
 #ifndef U_IDALLOC_H
 #define U_IDALLOC_H
 
@@ -58,6 +64,20 @@ util_idalloc_free(struct util_idalloc *buf, unsigned id);
 void
 util_idalloc_reserve(struct util_idalloc *buf, unsigned id);
 
+static inline bool
+util_idalloc_exists(struct util_idalloc *buf, unsigned id)
+{
+   return id / 32 < buf->num_elements &&
+          buf->data[id / 32] & BITFIELD_BIT(id % 32);
+}
+
+#define util_idalloc_foreach(buf, id) \
+   for (uint32_t i = 0, mask = (buf)->num_elements ? (buf)->data[0] : 0, id, \
+                 count = (buf)->num_elements; \
+        i < count; mask = ++i < count ? (buf)->data[i] : 0) \
+      while (mask) \
+         if ((id = i * 32 + u_bit_scan(&mask)), true)
+
 
 /* Thread-safe variant. */
 struct util_idalloc_mt {