sparrow 0.3.0
Loading...
Searching...
No Matches
ranges.hpp
Go to the documentation of this file.
1// Copyright 2024 Man Group Operations Limited
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#pragma once
15
16#include <algorithm>
17#include <ranges>
18#include <type_traits>
19
20#if defined(__cpp_lib_format)
21# include <format>
22# include <ostream>
23#endif
24
26
27namespace sparrow
28{
29 template <std::ranges::input_range R>
30 requires(std::ranges::sized_range<R>)
31 [[nodiscard]] std::size_t range_size(R&& r)
32 {
33 return static_cast<std::size_t>(std::ranges::size(r));
34 }
35
36 template <std::ranges::input_range R>
37 requires(!std::ranges::sized_range<R>)
38 [[nodiscard]] std::size_t range_size(R&& r)
39 {
40 return static_cast<std::size_t>(std::ranges::distance(r));
41 }
42
43 template <std::ranges::range Range>
44 requires std::ranges::sized_range<std::ranges::range_value_t<Range>>
45 [[nodiscard]] constexpr bool all_same_size(const Range& range)
46 {
47 // Optimization for std::array and fixed-size std::span
50 {
51 return true;
52 }
53 else
54 {
55 if (std::ranges::empty(range))
56 {
57 return true;
58 }
59
60 const std::size_t first_size = range.front().size();
61 return std::ranges::all_of(
62 range,
63 [first_size](const auto& element)
64 {
65 return element.size() == first_size;
66 }
67 );
68 }
69 }
70};
71
72#if defined(__cpp_lib_format) && !defined(__cpp_lib_format_ranges)
73
74template <typename T, std::size_t N>
75struct std::formatter<std::array<T, N>>
76{
77 // Parsing format specifiers
78 constexpr auto parse(std::format_parse_context& ctx)
79 {
80 return ctx.begin(); // Simple implementation
81 }
82
83 auto format(const std::array<T, N>& array, std::format_context& ctx) const
84 {
85 auto out = ctx.out();
86 *out++ = '<';
87
88 bool first = true;
89 for (const auto& elem : array)
90 {
91 if (!first)
92 {
93 *out++ = ',';
94 *out++ = ' ';
95 }
96 out = std::format_to(out, "{}", elem);
97 first = false;
98 }
99
100 *out++ = '>';
101 return out;
102 }
103};
104#endif
constexpr bool all_same_size(const Range &range)
Definition ranges.hpp:45
std::size_t range_size(R &&r)
Definition ranges.hpp:31