commit e153d90: [Minor] Add enumerate helper
Vsevolod Stakhov
vsevolod at rspamd.com
Wed May 4 22:56:03 UTC 2022
Author: Vsevolod Stakhov
Date: 2022-05-04 21:24:06 +0100
URL: https://github.com/rspamd/rspamd/commit/e153d90011395d349b91cd60758c2887615ab6fc
[Minor] Add enumerate helper
---
src/libutil/cxx/util.hxx | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/src/libutil/cxx/util.hxx b/src/libutil/cxx/util.hxx
index 8011f67a1..0df3349a3 100644
--- a/src/libutil/cxx/util.hxx
+++ b/src/libutil/cxx/util.hxx
@@ -22,6 +22,7 @@
#include <array>
#include <string_view>
#include <optional>
+#include <tuple>
/*
* Common C++ utilities
@@ -103,6 +104,31 @@ inline constexpr auto make_string_view_from_it(_It begin, _It end)
};
}
+/**
+ * Enumerate for range loop
+ */
+template <typename T,
+ typename TIter = decltype(std::begin(std::declval<T>())),
+ typename = decltype(std::end(std::declval<T>()))>
+constexpr auto enumerate(T && iterable)
+{
+ struct iterator
+ {
+ size_t i;
+ TIter iter;
+ bool operator != (const iterator & other) const { return iter != other.iter; }
+ void operator ++ () { ++i; ++iter; }
+ auto operator * () const { return std::tie(i, *iter); }
+ };
+ struct iterable_wrapper
+ {
+ T iterable;
+ auto begin() { return iterator{ 0, std::begin(iterable) }; }
+ auto end() { return iterator{ 0, std::end(iterable) }; }
+ };
+ return iterable_wrapper{ std::forward<T>(iterable) };
+}
+
}
#endif //RSPAMD_UTIL_HXX
More information about the Commits
mailing list