|
| 1 | +/* |
| 2 | + Copyright 2025 The Silkworm Authors |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +#pragma once |
| 18 | + |
| 19 | +#include <functional> |
| 20 | +#include <optional> |
| 21 | +#include <ranges> |
| 22 | + |
| 23 | +namespace silkworm::ranges { |
| 24 | + |
| 25 | +template <std::invocable TRangeFactory, std::ranges::range TRange = decltype(std::invoke(std::declval<TRangeFactory>()))> |
| 26 | +class LazyView : public std::ranges::view_interface<LazyView<TRangeFactory, TRange>> { |
| 27 | + public: |
| 28 | + LazyView() = default; |
| 29 | + |
| 30 | + explicit LazyView(TRangeFactory&& range_factory) : range_factory_{std::move(range_factory)} {} |
| 31 | + |
| 32 | + LazyView(LazyView&&) = default; |
| 33 | + |
| 34 | + LazyView& operator=(LazyView&& other) noexcept { |
| 35 | + range_factory_ = std::exchange(std::move(other.range_factory_), std::nullopt); |
| 36 | + range_ = std::exchange(std::move(other.range_), std::nullopt); |
| 37 | + return this; |
| 38 | + }; |
| 39 | + |
| 40 | + std::ranges::iterator_t<TRange> begin() { return std::ranges::begin(range()); } |
| 41 | + std::ranges::sentinel_t<TRange> end() { return std::ranges::end(range()); } |
| 42 | + |
| 43 | + private: |
| 44 | + TRange& range() { |
| 45 | + if (!range_) { |
| 46 | + range_.emplace(std::invoke(*range_factory_)); |
| 47 | + } |
| 48 | + return *range_; |
| 49 | + } |
| 50 | + |
| 51 | + std::optional<TRangeFactory> range_factory_; |
| 52 | + std::optional<TRange> range_; |
| 53 | +}; |
| 54 | + |
| 55 | +template <class TRangeFactory> |
| 56 | +LazyView<TRangeFactory> lazy(TRangeFactory&& range_factory) { |
| 57 | + return LazyView<TRangeFactory>{std::forward<TRangeFactory>(range_factory)}; |
| 58 | +} |
| 59 | + |
| 60 | +} // namespace silkworm::ranges |
0 commit comments