11#ifndef LIB_ENUMERATOR_H_
12#define LIB_ENUMERATOR_H_
16#include <initializer_list>
24#include "iterator_range.h"
27enum class EnumeratorState { NotStarted, Valid, PastEnd };
33using EnumeratorPtr = std::shared_ptr<Enumerator<T>>;
43class EnumeratorHandle {
46 explicit EnumeratorHandle(
Enumerator<T> *enumerator) : enumerator(enumerator) {}
48 friend EnumeratorHandle<U> begin(
const EnumeratorPtr<U> &enumerator);
50 friend EnumeratorHandle<U> end(
const EnumeratorPtr<U> &enumerator);
53 using iterator_category = std::input_iterator_tag;
54 using difference_type = std::ptrdiff_t;
59 reference operator*()
const;
60 const EnumeratorHandle<T> &operator++();
61 bool operator==(
const EnumeratorHandle<T> &other)
const;
62 bool operator!=(
const EnumeratorHandle<T> &other)
const;
67class Enumerator :
public std::enable_shared_from_this<Enumerator<T>> {
69 EnumeratorState state = EnumeratorState::NotStarted;
73 friend class Enumerator;
75 static std::vector<T> emptyVector;
77 friend class EnumeratorHandle;
82 Enumerator() { this->
reset(); }
84 virtual ~Enumerator() =
default;
92 virtual void reset() { this->state = EnumeratorState::NotStarted; }
94 const char *stateName()
const {
95 switch (this->state) {
96 case EnumeratorState::NotStarted:
98 case EnumeratorState::Valid:
100 case EnumeratorState::PastEnd:
103 throw std::logic_error(
"Unexpected state " + std::to_string(
static_cast<int>(this->state)));
107 template <
typename Container>
109 "Use Util::enumerate() instead")]]
static EnumeratorPtr<typename Container::value_type>
110 createEnumerator(
const Container &data);
111 static EnumeratorPtr<T> emptyEnumerator();
112 template <
typename Iter>
113 [[deprecated(
"Use Util::enumerate() instead")]]
static EnumeratorPtr<typename Iter::value_type>
114 createEnumerator(Iter begin, Iter end);
115 template <
typename Iter>
116 [[deprecated(
"Use Util::enumerate() instead")]]
static EnumeratorPtr<typename Iter::value_type>
117 createEnumerator(iterator_range<Iter> range);
120 template <
typename Filter>
121 EnumeratorPtr<T>
where(Filter filter);
123 template <
typename Mapper>
124 EnumeratorPtr<std::invoke_result_t<Mapper, T>>
map(Mapper
map);
126 template <
typename S>
127 EnumeratorPtr<S>
as();
129 virtual EnumeratorPtr<T>
concat(EnumeratorPtr<T> other);
131 static EnumeratorPtr<T>
concatAll(EnumeratorPtr<EnumeratorPtr<T>> inputs);
133 std::vector<T> toVector() {
134 std::vector<T> result;
152 if (!
next)
throw std::logic_error(
"There is no element for `single()'");
155 if (
next)
throw std::logic_error(
"There are multiple elements when calling `single()'");
163 if (!
next)
return T{};
166 if (
next)
throw std::logic_error(
"There are multiple elements when calling `single()'");
173 if (!
next)
return T{};
180 if (!
next)
throw std::logic_error(
"There is no element for `next()'");
192template <
typename Iter>
193class IteratorEnumerator :
public Enumerator<typename std::iterator_traits<Iter>::value_type> {
199 friend class Enumerator<typename
std::iterator_traits<Iter>::value_type>;
202 IteratorEnumerator(Iter begin, Iter end, const char *name)
203 : Enumerator<typename std::iterator_traits<Iter>::value_type>(),
209 [[nodiscard]] std::string toString()
const {
210 return std::string(this->name) +
":" + this->stateName();
214 switch (this->state) {
215 case EnumeratorState::NotStarted:
216 this->current = this->begin;
217 if (this->current == this->end) {
218 this->state = EnumeratorState::PastEnd;
221 this->state = EnumeratorState::Valid;
224 case EnumeratorState::PastEnd:
226 case EnumeratorState::Valid:
228 if (this->current == this->end) {
229 this->state = EnumeratorState::PastEnd;
235 throw std::runtime_error(
"Unexpected enumerator state");
238 typename std::iterator_traits<Iter>::value_type
getCurrent()
const override {
239 switch (this->state) {
240 case EnumeratorState::NotStarted:
241 throw std::logic_error(
"You cannot call 'getCurrent' before 'moveNext'");
242 case EnumeratorState::PastEnd:
243 throw std::logic_error(
"You cannot call 'getCurrent' past the collection end");
244 case EnumeratorState::Valid:
245 return *this->current;
247 throw std::runtime_error(
"Unexpected enumerator state");
251template <
typename Iter>
252IteratorEnumerator(Iter begin, Iter end,
const char *name) -> IteratorEnumerator<Iter>;
257class SingleEnumerator :
public Enumerator<T> {
261 explicit SingleEnumerator(T v) : Enumerator<T>(), value(v) {}
263 switch (this->state) {
264 case EnumeratorState::NotStarted:
265 this->state = EnumeratorState::Valid;
267 case EnumeratorState::PastEnd:
269 case EnumeratorState::Valid:
270 this->state = EnumeratorState::PastEnd;
273 throw std::runtime_error(
"Unexpected enumerator state");
276 switch (this->state) {
277 case EnumeratorState::NotStarted:
278 throw std::logic_error(
"You cannot call 'getCurrent' before 'moveNext'");
279 case EnumeratorState::PastEnd:
280 throw std::logic_error(
"You cannot call 'getCurrent' past the collection end");
281 case EnumeratorState::Valid:
284 throw std::runtime_error(
"Unexpected enumerator state");
294 [[nodiscard]] std::string toString()
const {
return "EmptyEnumerator"; }
298 throw std::logic_error(
"You cannot call 'getCurrent' on an EmptyEnumerator");
309template <
typename T,
typename Filter>
310class FilterEnumerator final :
public Enumerator<T> {
311 EnumeratorPtr<T> input;
316 FilterEnumerator(EnumeratorPtr<T> input, Filter filter)
317 : input(input), filter(std::move(filter)) {}
321 this->state = EnumeratorState::Valid;
322 while (this->input->moveNext()) {
323 this->current = this->input->getCurrent();
324 bool match = this->filter(this->current);
325 if (match)
return true;
327 this->state = EnumeratorState::PastEnd;
332 [[nodiscard]] std::string toString()
const {
333 return "FilterEnumerator(" + this->input->toString() +
"):" + this->stateName();
337 this->input->reset();
342 switch (this->state) {
343 case EnumeratorState::NotStarted:
344 case EnumeratorState::Valid:
345 return this->advance();
346 case EnumeratorState::PastEnd:
349 throw std::runtime_error(
"Unexpected enumerator state");
353 switch (this->state) {
354 case EnumeratorState::NotStarted:
355 throw std::logic_error(
"You cannot call 'getCurrent' before 'moveNext'");
356 case EnumeratorState::PastEnd:
357 throw std::logic_error(
"You cannot call 'getCurrent' past the collection end");
358 case EnumeratorState::Valid:
359 return this->current;
361 throw std::runtime_error(
"Unexpected enumerator state");
368template <
typename T,
typename S>
369class AsEnumerator final :
public Enumerator<S> {
370 S getCurrentImpl()
const {
371 T current = input->getCurrent();
372 using Target =
typename std::pointer_traits<S>::element_type;
373 if constexpr (
requires { current->template to<Target>(); }) {
374 return current ? current->template to<Target>() :
nullptr;
376 return dynamic_cast<S
>(current);
381 EnumeratorPtr<T> input;
384 explicit AsEnumerator(EnumeratorPtr<T> input) : input(input) {}
386 std::string toString()
const {
387 return "AsEnumerator(" + this->input->toString() +
"):" + this->stateName();
392 this->input->reset();
396 bool result = this->input->moveNext();
398 this->state = EnumeratorState::Valid;
400 this->state = EnumeratorState::PastEnd;
410template <
typename T,
typename S,
typename Mapper>
411class MapEnumerator final :
public Enumerator<S> {
413 EnumeratorPtr<T> input;
418 MapEnumerator(EnumeratorPtr<T> input, Mapper map) : input(input), map(std::move(map)) {}
421 this->input->reset();
425 [[nodiscard]] std::string toString()
const {
426 return "MapEnumerator(" + this->input->toString() +
"):" + this->stateName();
430 switch (this->state) {
431 case EnumeratorState::NotStarted:
432 case EnumeratorState::Valid: {
433 bool success = input->moveNext();
435 T currentInput = this->input->getCurrent();
436 this->current = this->map(currentInput);
437 this->state = EnumeratorState::Valid;
440 this->state = EnumeratorState::PastEnd;
444 case EnumeratorState::PastEnd:
447 throw std::runtime_error(
"Unexpected enumerator state");
451 switch (this->state) {
452 case EnumeratorState::NotStarted:
453 throw std::logic_error(
"You cannot call 'getCurrent' before 'moveNext'");
454 case EnumeratorState::PastEnd:
455 throw std::logic_error(
"You cannot call 'getCurrent' past the collection end");
456 case EnumeratorState::Valid:
457 return this->current;
459 throw std::runtime_error(
"Unexpected enumerator state");
463template <
typename T,
typename Mapper>
464MapEnumerator(EnumeratorPtr<T>,
465 Mapper) -> MapEnumerator<T, typename std::invoke_result_t<Mapper, T>, Mapper>;
471class ConcatEnumerator final :
public Enumerator<T> {
472 std::vector<EnumeratorPtr<T>> inputs;
476 ConcatEnumerator() =
default;
478 explicit ConcatEnumerator(std::vector<EnumeratorPtr<T>> &&inputs) : inputs(std::move(inputs)) {
479 for (
const auto ¤tInput : inputs)
480 if (currentInput ==
nullptr)
throw std::logic_error(
"Null iterator in concatenation");
483 ConcatEnumerator(std::initializer_list<EnumeratorPtr<T>> inputs) : inputs(inputs) {
484 for (
const auto ¤tInput : inputs)
485 if (currentInput ==
nullptr)
throw std::logic_error(
"Null iterator in concatenation");
487 explicit ConcatEnumerator(EnumeratorPtr<EnumeratorPtr<T>> inputs)
488 : ConcatEnumerator(inputs->toVector()) {}
490 [[nodiscard]] std::string toString()
const {
return "ConcatEnumerator:" + this->stateName(); }
494 this->state = EnumeratorState::Valid;
495 for (
const auto ¤tInput : inputs) {
496 if (currentInput->moveNext()) {
497 this->currentResult = currentInput->getCurrent();
502 this->state = EnumeratorState::PastEnd;
507 EnumeratorPtr<T>
concat(EnumeratorPtr<T> other)
override {
509 if (this->state == EnumeratorState::PastEnd)
510 throw std::runtime_error(
"Invalid enumerator state to concatenate");
512 inputs.push_back(other);
514 return this->shared_from_this();
518 for (
const auto ¤tInput : inputs) currentInput->reset();
523 switch (this->state) {
524 case EnumeratorState::NotStarted:
525 case EnumeratorState::Valid:
526 return this->advance();
527 case EnumeratorState::PastEnd:
530 throw std::runtime_error(
"Unexpected enumerator state");
534 switch (this->state) {
535 case EnumeratorState::NotStarted:
536 throw std::logic_error(
"You cannot call 'getCurrent' before 'moveNext'");
537 case EnumeratorState::PastEnd:
538 throw std::logic_error(
"You cannot call 'getCurrent' past the collection end");
539 case EnumeratorState::Valid:
540 return this->currentResult;
542 throw std::runtime_error(
"Unexpected enumerator state");
549template <
typename Mapper>
551 return std::make_shared<MapEnumerator<T, std::invoke_result_t<Mapper, T>, Mapper>>(
552 this->shared_from_this(), std::move(
map));
558 return std::make_shared<AsEnumerator<T, S>>(this->shared_from_this());
562template <
typename Filter>
564 return std::make_shared<FilterEnumerator<T, Filter>>(this->shared_from_this(),
569template <
typename Container>
570EnumeratorPtr<typename Container::value_type> Enumerator<T>::createEnumerator(
571 const Container &data) {
572 return std::make_shared<
IteratorEnumerator<
decltype(data.begin())>>(data.begin(), data.end(),
573 typeid(Container).name());
577EnumeratorPtr<T> Enumerator<T>::emptyEnumerator() {
578 return std::make_shared<EmptyEnumerator<T>>();
582template <
typename Iter>
583EnumeratorPtr<typename Iter::value_type> Enumerator<T>::createEnumerator(Iter begin, Iter end) {
584 return std::make_shared<IteratorEnumerator<Iter>>(begin, end,
"iterator");
588template <
typename Iter>
589EnumeratorPtr<typename Iter::value_type> Enumerator<T>::createEnumerator(
591 return std::make_shared<IteratorEnumerator<Iter>>(range.begin(), range.end(),
"range");
596 return std::make_shared<ConcatEnumerator<T>>(inputs);
601 return std::make_shared<ConcatEnumerator<T>>(
602 std::initializer_list<EnumeratorPtr<T>>{this->shared_from_this(), other});
608T EnumeratorHandle<T>::operator*()
const {
609 if (enumerator ==
nullptr)
throw std::logic_error(
"Dereferencing end() iterator");
610 return enumerator->getCurrent();
614const EnumeratorHandle<T> &EnumeratorHandle<T>::operator++() {
615 enumerator->moveNext();
620bool EnumeratorHandle<T>::operator==(
const EnumeratorHandle<T> &other)
const {
621 return !(*
this != other);
626 if (this->enumerator == other.enumerator)
return true;
627 if (other.enumerator !=
nullptr)
throw std::logic_error(
"Comparison with different iterator");
628 return this->enumerator->state == EnumeratorState::Valid;
631template <
typename Iter>
632EnumeratorPtr<typename std::iterator_traits<Iter>::value_type> enumerate(Iter begin, Iter end) {
633 return std::make_shared<IteratorEnumerator<Iter>>(begin, end,
"iterator");
636template <
typename Iter>
637EnumeratorPtr<typename std::iterator_traits<Iter>::value_type> enumerate(
639 return std::make_shared<IteratorEnumerator<Iter>>(range.begin(), range.end(),
"range");
642template <
typename Container>
643EnumeratorPtr<typename Container::value_type> enumerate(
const Container &data) {
646 return std::make_shared<
IteratorEnumerator<
decltype(begin(data))>>(begin(data), end(data),
647 typeid(data).name());
652EnumeratorPtr<T> concat(std::initializer_list<EnumeratorPtr<T>> inputs) {
653 return std::make_shared<ConcatEnumerator<T>>(inputs);
656template <
typename... Args>
657auto concat(Args &&...inputs) {
658 using FirstEnumeratorTy =
659 typename std::decay_t<std::tuple_element_t<0, std::tuple<Args...>>>::element_type;
660 std::initializer_list<EnumeratorPtr<typename FirstEnumeratorTy::value_type>> init{
661 std::forward<Args>(inputs)...};
669 enumerator->moveNext();
S getCurrent() const override
Get current element in the collection.
Definition enumerator.h:404
void reset() override
Move back to the beginning of the collection.
Definition enumerator.h:390
bool moveNext() override
Definition enumerator.h:395
void reset() override
Move back to the beginning of the collection.
Definition enumerator.h:517
EnumeratorPtr< T > concat(EnumeratorPtr< T > other) override
Append all elements of other after all elements of this.
Definition enumerator.h:507
bool moveNext() override
Definition enumerator.h:522
T getCurrent() const override
Get current element in the collection.
Definition enumerator.h:533
Always empty iterator (equivalent to end())
Definition enumerator.h:292
bool moveNext() override
Always returns false.
Definition enumerator.h:296
T getCurrent() const override
Get current element in the collection.
Definition enumerator.h:297
Definition enumerator.h:43
Type-erased Enumerator interface.
Definition enumerator.h:67
virtual bool moveNext()=0
T nextOrDefault()
Next element, or the default value if none exists.
Definition enumerator.h:171
virtual EnumeratorPtr< T > concat(EnumeratorPtr< T > other)
Append all elements of other after all elements of this.
Definition enumerator.h:600
T single()
The only next element; throws if the enumerator does not have exactly 1 element.
Definition enumerator.h:150
EnumeratorPtr< S > as()
Cast to an enumerator of S objects.
Definition enumerator.h:557
EnumeratorPtr< std::invoke_result_t< Mapper, T > > map(Mapper map)
Apply specified function to all elements of this enumerator.
Definition enumerator.h:550
EnumeratorPtr< T > where(Filter filter)
Return an enumerator returning all elements that pass the filter.
Definition enumerator.h:563
virtual void reset()
Move back to the beginning of the collection.
Definition enumerator.h:92
bool any()
True if the enumerator has at least one element.
Definition enumerator.h:147
static EnumeratorPtr< T > concatAll(EnumeratorPtr< EnumeratorPtr< T > > inputs)
Concatenate all these collections into a single one.
Definition enumerator.h:595
virtual T getCurrent() const =0
Get current element in the collection.
T next()
Next element; throws if there are no elements.
Definition enumerator.h:178
uint64_t count()
Enumerate all elements and return the count.
Definition enumerator.h:140
T singleOrDefault()
Definition enumerator.h:161
T getCurrent() const
Get current element in the collection.
Definition enumerator.h:352
void reset()
Move back to the beginning of the collection.
Definition enumerator.h:336
bool moveNext()
Definition enumerator.h:341
A generic iterator returning elements of type T.
Definition enumerator.h:193
bool moveNext() override
Definition enumerator.h:213
std::iterator_traits< Iter >::value_type getCurrent() const override
Get current element in the collection.
Definition enumerator.h:238
void reset()
Move back to the beginning of the collection.
Definition enumerator.h:420
bool moveNext()
Definition enumerator.h:429
S getCurrent() const
Get current element in the collection.
Definition enumerator.h:450
bool moveNext()
Definition enumerator.h:262
T getCurrent() const
Get current element in the collection.
Definition enumerator.h:275
Definition iterator_range.h:44
Definition tofino/bf-asm/target.h:196