QXmpp  Version: 1.8.1
Algorithms.h
1 // SPDX-FileCopyrightText: 2024 Linus Jahn <lnj@kaidan.im>
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 
5 #ifndef ALGORITHMS_H
6 #define ALGORITHMS_H
7 
8 #include <algorithm>
9 #include <functional>
10 #include <optional>
11 
12 namespace QXmpp::Private {
13 
14 template<typename OutputVector, typename InputVector, typename Converter>
15 auto transform(const InputVector &input, Converter convert)
16 {
17  OutputVector output;
18  if constexpr (std::ranges::sized_range<InputVector>) {
19  output.reserve(input.size());
20  }
21  for (const auto &value : input) {
22  output.push_back(std::invoke(convert, value));
23  }
24  return output;
25 }
26 
27 template<typename Vec, typename T>
28 auto contains(const Vec &vec, const T &value)
29 {
30  return std::find(std::begin(vec), std::end(vec), value) != std::end(vec);
31 }
32 
33 template<typename T, typename Function>
34 auto map(Function mapValue, std::optional<T> &&optValue) -> std::optional<std::invoke_result_t<Function, T &&>>
35 {
36  if (optValue) {
37  return mapValue(std::move(*optValue));
38  }
39  return {};
40 }
41 
42 template<typename To, typename From>
43 auto into(std::optional<From> &&value) -> std::optional<To>
44 {
45  if (value) {
46  return To { *value };
47  }
48  return {};
49 }
50 
51 } // namespace QXmpp::Private
52 
53 #endif // ALGORITHMS_H
Definition: Algorithms.h:12