diff --git a/lib/base/CMakeLists.txt b/lib/base/CMakeLists.txt index d44254a35..1bb700c3d 100644 --- a/lib/base/CMakeLists.txt +++ b/lib/base/CMakeLists.txt @@ -37,6 +37,7 @@ set(base_SOURCES fifo.cpp fifo.hpp filelogger.cpp filelogger.hpp filelogger-ti.hpp function.cpp function.hpp function-ti.hpp function-script.cpp functionwrapper.hpp + generator.hpp initialize.cpp initialize.hpp intrusive-ptr.hpp io-engine.cpp io-engine.hpp diff --git a/lib/base/generator.hpp b/lib/base/generator.hpp new file mode 100644 index 000000000..fa41e67fc --- /dev/null +++ b/lib/base/generator.hpp @@ -0,0 +1,48 @@ +/* Icinga 2 | (c) 2025 Icinga GmbH | GPLv2+ */ + +#pragma once + +#include "base/i2-base.hpp" +#include "base/value.hpp" +#include + +namespace icinga +{ + +/** + * ValueGenerator is a class that defines a generator function type for producing Values on demand. + * + * This class is used to create generator functions that can yield any values that can be represented by the + * Icinga Value type. The generator function is exhausted when it returns `std::nullopt`, indicating that there + * are no more values to produce. Subsequent calls to `Next()` will always return `std::nullopt` after exhaustion. + * + * @ingroup base + */ +class ValueGenerator final : public Object +{ +public: + DECLARE_PTR_TYPEDEFS(ValueGenerator); + + /** + * Generates a Value using the provided generator function. + * + * The generator function should return an `std::optional` which contains the produced Value or + * `std::nullopt` when there are no more values to produce. After the generator function returns `std::nullopt`, + * the generator is considered exhausted, and further calls to `Next()` will always return `std::nullopt`. + */ + using GenFunc = std::function()>; + + explicit ValueGenerator(GenFunc generator): m_Generator(std::move(generator)) + { + } + + std::optional Next() const + { + return m_Generator(); + } + +private: + GenFunc m_Generator; // The generator function that produces Values. +}; + +}