HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
ranges.hpp
1// Copyright Take Vos 2021-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "../utility/utility.hpp"
8#include "../macros.hpp"
9#include <ranges>
10#include <algorithm>
11#include <concepts>
12#include <type_traits>
13#include <vector>
14#include <exception>
15#include <stdexcept>
16
17hi_export_module(hikogui.algorithm.ranges);
18
19hi_export namespace hi::inline v1 {
20
21template<typename Value, typename Range>
22[[nodiscard]] constexpr Value get_first(Range &&range)
23{
24 auto it = std::ranges::begin(range);
25 auto last = std::ranges::end(range);
26
27 if (it == last) {
28 throw std::out_of_range{"Range is empty"};
29 }
30
31 auto value = *it++;
32 return Value{value};
33}
34
37template<typename Range>
38[[nodiscard]] constexpr Range::value_type get_first(Range&& range)
39{
40 return get_first<typename Range::value_type>(std::forward<Range>(range));
41}
42
46template<typename Value, typename Range>
47[[nodiscard]] constexpr std::vector<Value> make_vector(Range&& range)
48{
49 auto const first = std::ranges::begin(range);
50 auto const last = std::ranges::end(range);
51
52 if constexpr (requires(std::vector<Value> & x) { std::ranges::copy(first, last, std::back_inserter(x)); }) {
53 // This should handle almost everything.
54 auto r = std::vector<Value>{};
55 if constexpr (requires { std::distance(first, last); }) {
56 r.reserve(std::distance(first, last));
57 }
58 std::ranges::copy(first, last, std::back_inserter(r));
59 return r;
60
61 } else if constexpr (requires { Value{std::string_view{(*first).begin(), (*first).end()}}; }) {
62 // std::views::split returns a range of ranges, handle the string_view cases.
63 auto r = std::vector<Value>{};
64 if constexpr (requires { std::distance(first, last); }) {
65 r.reserve(std::distance(first, last));
66 }
67 for (auto it = first; it != last; ++it) {
68 r.emplace_back(std::string_view{(*it).begin(), (*it).end()});
69 }
70 return r;
71
72 } else {
73 hi_static_not_implemented();
74 }
75}
76
79template<typename Range>
80[[nodiscard]] constexpr std::vector<typename Range::value_type> make_vector(Range&& range)
81{
82 return make_vector<typename Range::value_type>(std::forward<Range>(range));
83}
84
85} // namespace hi::inline v1
DOXYGEN BUG.
Definition algorithm_misc.hpp:20
constexpr std::vector< Value > make_vector(Range &&range)
Make a vector from a view.
Definition ranges.hpp:47
T back_inserter(T... args)
T distance(T... args)
T reserve(T... args)