enumerate.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #pragma once
  2. #include <util/generic/store_policy.h>
  3. #include <limits>
  4. #include <tuple>
  5. namespace NPrivate {
  6. template <typename TContainer>
  7. struct TEnumerator {
  8. private:
  9. using TStorage = TAutoEmbedOrPtrPolicy<TContainer>;
  10. using TValue = std::tuple<const std::size_t, decltype(*std::begin(std::declval<TContainer&>()))>;
  11. using TIteratorState = decltype(std::begin(std::declval<TContainer&>()));
  12. using TSentinelState = decltype(std::end(std::declval<TContainer&>()));
  13. static constexpr bool TrivialSentinel = std::is_same_v<TIteratorState, TSentinelState>;
  14. struct TIterator;
  15. struct TSentinelCandidate {
  16. TSentinelState Iterator_;
  17. };
  18. using TSentinel = std::conditional_t<TrivialSentinel, TIterator, TSentinelCandidate>;
  19. struct TIterator {
  20. using difference_type = std::ptrdiff_t;
  21. using value_type = TValue;
  22. using pointer = TValue*;
  23. using reference = TValue&;
  24. using iterator_category = std::input_iterator_tag;
  25. TValue operator*() {
  26. return {Index_, *Iterator_};
  27. }
  28. TValue operator*() const {
  29. return {Index_, *Iterator_};
  30. }
  31. void operator++() {
  32. ++Index_;
  33. ++Iterator_;
  34. }
  35. bool operator!=(const TSentinel& other) const {
  36. return Iterator_ != other.Iterator_;
  37. }
  38. bool operator==(const TSentinel& other) const {
  39. return Iterator_ == other.Iterator_;
  40. }
  41. std::size_t Index_;
  42. TIteratorState Iterator_;
  43. };
  44. public:
  45. using iterator = TIterator;
  46. using const_iterator = TIterator;
  47. using value_type = typename TIterator::value_type;
  48. using reference = typename TIterator::reference;
  49. using const_reference = typename TIterator::reference;
  50. TIterator begin() const {
  51. return {0, std::begin(*Storage_.Ptr())};
  52. }
  53. TSentinel end() const {
  54. if constexpr (TrivialSentinel) {
  55. return TIterator{std::numeric_limits<std::size_t>::max(), std::end(*Storage_.Ptr())};
  56. } else {
  57. return TSentinel{std::end(*Storage_.Ptr())};
  58. }
  59. }
  60. mutable TStorage Storage_;
  61. };
  62. }
  63. //! Usage: for (auto [i, x] : Enumerate(container)) {...}
  64. template <typename TContainerOrRef>
  65. auto Enumerate(TContainerOrRef&& container) {
  66. return NPrivate::TEnumerator<TContainerOrRef>{std::forward<TContainerOrRef>(container)};
  67. }