Stroika Library 3.0d16
 
Loading...
Searching...
No Matches
Generator.inl
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2025. All rights reserved
3 */
8
9namespace Stroika::Foundation::Traversal {
10
11 /**
12 */
13 template <typename T>
14 Iterator<T> CreateGeneratorIterator (const function<optional<T> ()>& getNext)
15 {
16 struct GenItWrapper_ : Iterator<T>::IRep, public Memory::UseBlockAllocationIfAppropriate<GenItWrapper_> {
17 function<optional<T> ()> fFun_;
18 optional<T> fCur_;
19 GenItWrapper_ () = delete;
20 GenItWrapper_ (const function<optional<T> ()>& f)
21 : fFun_{f}
22 , fCur_{fFun_ ()}
23 {
24 }
25 virtual void More (optional<T>* result, bool advance) override
26 {
27 RequireNotNull (result);
28 if (advance) {
29 // Iterator<T, ITERATOR_TRAITS>::IRep::More() docs say legal to call More(advance) even if at end
30 if (fCur_.has_value ()) {
31 fCur_ = fFun_ ();
32 }
33 }
34 *result = fCur_;
35 }
36 virtual bool Equals (const typename Iterator<T>::IRep* rhs) const override
37 {
38 RequireNotNull (rhs);
39 const GenItWrapper_& rrhs = *Debug::UncheckedDynamicCast<const GenItWrapper_*> (rhs);
40 // No way to tell equality (so must rethink definition in Iterator<T>::Equals()!!! @todo
41 WeakAssert (not fCur_.has_value () or not rrhs.fCur_.has_value ());
42 return fCur_.has_value () == rrhs.fCur_.has_value ();
43 }
44 virtual unique_ptr<typename Iterator<T>::IRep> Clone () const override
45 {
46 return make_unique<GenItWrapper_> (*this);
47 }
48 };
49 return Iterator<T>{make_unique<GenItWrapper_> (getNext)};
50 }
51
52 /**
53 */
54 template <typename T>
55 inline Iterable<T> CreateGenerator (const function<optional<T> ()>& getNext)
56 {
58 }
59
60}
#define RequireNotNull(p)
Definition Assertions.h:347
#define WeakAssert(c)
A WeakAssert() is for things that aren't guaranteed to be true, but are overwhelmingly likely to be t...
Definition Assertions.h:438
conditional_t< qStroika_Foundation_Memory_PreferBlockAllocation and andTrueCheck, BlockAllocationUseHelper< T >, Common::Empty > UseBlockAllocationIfAppropriate
Use this to enable block allocation for a particular class. Beware of subclassing.
Iterator< T > CreateGeneratorIterator(const function< optional< T >()> &getNext)
Definition Generator.inl:14
Iterable< T > CreateGenerator(const function< optional< T >()> &getNext)
Create an Iterable<T> from a function that returns optional<T> - treating nullopt as meaning the END ...
Definition Generator.inl:55
Iterable< T > MakeIterableFromIterator(const Iterator< T > &iterator)
Iterable<T> is a base class for containers which easily produce an Iterator<T> to traverse them.
Definition Iterable.h:237
Implementation detail for iterator implementors.
Definition Iterator.h:599
An Iterator<T> is a copyable object which allows traversing the contents of some container....
Definition Iterator.h:225