Stroika Library 3.0d24
 
Loading...
Searching...
No Matches
Generator.inl
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. 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 bool AtEnd () const override
26 {
27 return not fCur_.has_value ();
28 }
29 virtual optional<T> Current () const override
30 {
31 return fCur_;
32 }
33 virtual optional<T> More () override
34 {
35 Require (fCur_.has_value ()); // not at end
36 fCur_ = fFun_ ();
37 return fCur_;
38 }
39 virtual bool Equals (const typename Iterator<T>::IRep* rhs) const override
40 {
41 RequireNotNull (rhs);
42 const GenItWrapper_& rrhs = *Debug::UncheckedDynamicCast<const GenItWrapper_*> (rhs);
43 // No way to tell equality (so must rethink definition in Iterator<T>::Equals()!!! @todo
44 WeakAssert (not fCur_.has_value () or not rrhs.fCur_.has_value ());
45 return fCur_.has_value () == rrhs.fCur_.has_value ();
46 }
47 virtual unique_ptr<typename Iterator<T>::IRep> Clone () const override
48 {
49 return make_unique<GenItWrapper_> (*this);
50 }
51 };
52 return Iterator<T>{make_unique<GenItWrapper_> (getNext)};
53 }
54
55 /**
56 */
57 template <typename T>
58 inline Iterable<T> CreateGenerator (const function<optional<T> ()>& getNext)
59 {
61 }
62
63}
#define RequireNotNull(p)
Definition Assertions.h:348
#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:439
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:58
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:238
Implementation detail for iterator implementors.
Definition Iterator.h:616
An Iterator<T> is a copyable object which allows traversing the contents of some container.
Definition Iterator.h:253