Program Listing for File assign.hpp
↰ Return to documentation for file (include/beluga/actions/assign.hpp
)
// Copyright 2024 Ekumen, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BELUGA_ACTIONS_ASSIGN_HPP
#define BELUGA_ACTIONS_ASSIGN_HPP
#include <range/v3/action/action.hpp>
#include <range/v3/functional/bind_back.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/view.hpp>
namespace beluga::actions {
template <class T, class = void>
struct is_range_closure : std::false_type {};
template <class T>
struct is_range_closure<ranges::actions::action_closure<T>> : std::true_type {};
template <class T>
struct is_range_closure<ranges::views::view_closure<T>> : std::true_type {};
template <class T>
inline constexpr bool is_range_closure_v = is_range_closure<T>::value;
namespace detail {
struct assign_fn {
template <
class Range,
class Fn,
std::enable_if_t<ranges::range<Range>, int> = 0,
std::enable_if_t<is_range_closure_v<Fn>, int> = 0>
constexpr auto operator()(Range& range, Fn fn) const -> Range& {
auto&& view = fn(range);
if constexpr (!std::is_same_v<Range, std::decay_t<decltype(view)>>) {
// If the result of invoking the closure is not the range itself,
// then we need to convert the view and assign it to the input range.
range = std::move(view) | ranges::to<Range>;
}
return range;
}
template <class Fn, std::enable_if_t<is_range_closure_v<Fn>, int> = 0>
friend constexpr auto operator|(Fn fn, assign_fn) {
return ranges::make_action_closure(ranges::bind_back(assign_fn{}, std::move(fn)));
}
};
} // namespace detail
inline constexpr detail::assign_fn assign;
} // namespace beluga::actions
#endif