QXmpp Version: 1.10.0
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
12namespace QXmpp::Private {
13
14template<typename T>
15constexpr bool HasShrinkToFit = requires(const T &t) {
16 t.shrink_to_fit();
17};
18
19template<typename T>
20constexpr bool HasSqueeze = requires(const T &t) {
21 t.squeeze();
22};
23
24template<typename OutputVector, typename InputVector, typename Converter>
25auto transform(const InputVector &input, Converter convert)
26{
27 OutputVector output;
28 if constexpr (std::ranges::sized_range<InputVector>) {
29 output.reserve(input.size());
30 }
31 for (const auto &value : input) {
32 output.push_back(std::invoke(convert, value));
33 }
34 return output;
35}
36
37template<typename OutputVector, typename InputVector, typename Converter>
38auto transformFilter(const InputVector &input, Converter convert)
39{
40 OutputVector output;
41 if constexpr (std::ranges::sized_range<InputVector>) {
42 output.reserve(input.size());
43 }
44 for (const auto &value : input) {
45 if (const std::optional<std::decay_t<decltype(value)>> result = std::invoke(convert, value)) {
46 output.push_back(*result);
47 }
48 }
49 if constexpr (HasShrinkToFit<InputVector>) {
50 output.shrink_to_fit();
51 } else if constexpr (HasSqueeze<InputVector>) {
52 output.squeeze();
53 }
54 return output;
55}
56
57template<typename Vec, typename T>
58auto contains(const Vec &vec, const T &value)
59{
60 return std::find(std::begin(vec), std::end(vec), value) != std::end(vec);
61}
62
63template<typename T, typename Function>
64auto map(Function mapValue, std::optional<T> &&optValue) -> std::optional<std::invoke_result_t<Function, T &&>>
65{
66 if (optValue) {
67 return mapValue(std::move(*optValue));
68 }
69 return {};
70}
71
72template<typename To, typename From>
73auto into(std::optional<From> &&value) -> std::optional<To>
74{
75 if (value) {
76 return To { *value };
77 }
78 return {};
79}
80
81} // namespace QXmpp::Private
82
83#endif // ALGORITHMS_H