cpp-common: add vectorFastRemove
authorSimon Marchi <simon.marchi@efficios.com>
Tue, 28 Jun 2022 18:26:53 +0000 (14:26 -0400)
committerPhilippe Proulx <eeppeliteloop@gmail.com>
Mon, 11 Sep 2023 15:24:02 +0000 (11:24 -0400)
Add the vectorFastRemove function, in src/cpp-common/vector.hpp, as a
drop-in replacement for g_ptr_array_remove_index_fast, when replacing a
GPtrArray with an std::vector.

Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
Change-Id: Ibee249fd9a8168d02ad99abf36984bf7edd53b5b
Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/8493
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/10837
CI-Build: Philippe Proulx <eeppeliteloop@gmail.com>
Tested-by: jenkins <jenkins@lttng.org>
src/cpp-common/Makefile.am
src/cpp-common/vector.hpp [new file with mode: 0644]

index cfe4efd13a138647de91c2b9e55dbdbc28ff180f..e6d9602abdf0fa356f92a9fa7f1482f718fb4cea 100644 (file)
@@ -16,4 +16,5 @@ EXTRA_DIST = bt2 \
        make-unique.hpp \
        safe-ops.hpp \
        align.hpp \
-       uuid.hpp
+       uuid.hpp \
+       vector.hpp
diff --git a/src/cpp-common/vector.hpp b/src/cpp-common/vector.hpp
new file mode 100644 (file)
index 0000000..0f0f202
--- /dev/null
@@ -0,0 +1,30 @@
+#ifndef SRC_CPP_COMMON_VECTOR_HPP
+#define SRC_CPP_COMMON_VECTOR_HPP
+
+#include <vector>
+#include "common/assert.h"
+
+namespace bt2_common {
+
+/*
+ * Moves the last entry of `vec` to the index `idx`, then removes the last entry.
+ *
+ * Meant to be a direct replacement for g_ptr_array_remove_index_fast(), but for
+ * `std::vector`.
+ */
+template <typename T, typename AllocatorT>
+void vectorFastRemove(std::vector<T, AllocatorT>& vec,
+                      const typename std::vector<T, AllocatorT>::size_type idx)
+{
+    BT_ASSERT_DBG(idx < vec.size());
+
+    if (idx < vec.size() - 1) {
+        vec[idx] = std::move(vec.back());
+    }
+
+    vec.pop_back();
+}
+
+} /* namespace bt2_common */
+
+#endif /* SRC_CPP_COMMON_VECTOR_HPP */
This page took 0.024525 seconds and 4 git commands to generate.