summaryrefslogtreecommitdiff
path: root/gi/utils-inl.h
diff options
context:
space:
mode:
authorMarco Trevisan (TreviƱo) <mail@3v1n0.net>2021-05-16 17:27:05 +0200
committerPhilip Chimento <philip.chimento@gmail.com>2021-05-19 22:05:02 -0700
commit5ca326a66cc6cfb7b1fdcfbf0f4a1da66f63e8fa (patch)
tree72f184b1bcfffe7f514077bac498954acc4f9e3a /gi/utils-inl.h
parented1cdae2edaeb0c880d643c60693029bd13b0ed4 (diff)
downloadgjs-5ca326a66cc6cfb7b1fdcfbf0f4a1da66f63e8fa.tar.gz
utils: Add inline function to remove from unsorted vectors
Erasing a value from a vector can be very verbose in C++, mostly if we want to use some optimized path. So add a generic function to handle it for the case of unsorted vectors (the ones we care mostly in gjs).
Diffstat (limited to 'gi/utils-inl.h')
-rw-r--r--gi/utils-inl.h22
1 files changed, 22 insertions, 0 deletions
diff --git a/gi/utils-inl.h b/gi/utils-inl.h
index bcd85876..a8155bcd 100644
--- a/gi/utils-inl.h
+++ b/gi/utils-inl.h
@@ -7,6 +7,8 @@
#include <stdint.h>
#include <type_traits> // IWYU pragma: keep
+#include <utility>
+#include <vector>
template <typename T>
constexpr void* gjs_int_to_pointer(T v) {
@@ -37,3 +39,23 @@ template <>
inline bool gjs_pointer_to_int<bool>(void* p) {
return !!gjs_pointer_to_int<int8_t>(p);
}
+
+namespace Gjs {
+
+template <typename T>
+inline bool remove_one_from_unsorted_vector(std::vector<T>* v, const T& value) {
+ // This assumes that there's only a copy of the same value in the vector
+ // so this needs to be ensured when populating it.
+ // We use the swap and pop idiom to avoid moving all the values.
+ auto it = std::find(v->begin(), v->end(), value);
+ if (it != v->end()) {
+ std::swap(*it, v->back());
+ v->pop_back();
+ g_assert(std::find(v->begin(), v->end(), value) == v->end());
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace Gjs