From: Vsevolod Stakhov Date: Wed, 4 May 2022 20:24:06 +0000 (+0100) Subject: [Minor] Add enumerate helper X-Git-Tag: 3.3~279 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=e153d90011395d349b91cd60758c2887615ab6fc;p=thirdparty%2Frspamd.git [Minor] Add enumerate helper --- diff --git a/src/libutil/cxx/util.hxx b/src/libutil/cxx/util.hxx index 8011f67a12..0df3349a3d 100644 --- a/src/libutil/cxx/util.hxx +++ b/src/libutil/cxx/util.hxx @@ -22,6 +22,7 @@ #include #include #include +#include /* * 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 = decltype(std::end(std::declval()))> +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(iterable) }; +} + } #endif //RSPAMD_UTIL_HXX