Botan 3.14.1
Crypto and TLS for C&
concat_util.h
Go to the documentation of this file.
1/*
2* (C) 2023-2024 René Meusel - Rohde & Schwarz Cybersecurity
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_CONCAT_UTIL_H_
8#define BOTAN_CONCAT_UTIL_H_
9
10#include <botan/assert.h>
11#include <botan/concepts.h>
12#include <botan/mem_ops.h>
13#include <botan/range_concepts.h>
14#include <botan/strong_type_helpers.h>
15#include <array>
16#include <iterator>
17#include <ranges>
18#include <span>
19#include <tuple>
20#include <type_traits>
21#include <vector>
22
23namespace Botan {
24
25namespace detail {
26
27/**
28 * Helper function that performs range size-checks as required given the
29 * selected output and input range types. If all lengths are known at compile
30 * time, this check will be performed at compile time as well. It will then
31 * instantiate an output range and concatenate the input ranges' contents.
32 */
33template <ranges::spanable_range OutR, ranges::spanable_range... Rs>
34constexpr OutR concatenate(Rs&&... ranges)
36{
37 OutR result{};
38
39 // Prepare and validate the output range and construct a lambda that does the
40 // actual filling of the result buffer.
41 // (if no input ranges are given, GCC claims that fill_fn is unused)
42 // NOLINTNEXTLINE(*-const-correctness) the fixed-size branch returns a mutable lambda
43 [[maybe_unused]] auto fill_fn = [&] {
45 // dynamically allocate the correct result byte length
46 const size_t total_size = (ranges.size() + ... + 0);
47 result.reserve(total_size);
48
49 // append each input as a whole range, so contiguous byte
50 // buffers are copied with memcpy rather than element by element
51 return [&result](auto&& range) {
52 auto& out = unwrap_strong_type(result);
53 out.insert(out.end(), std::ranges::begin(range), std::ranges::end(range));
54 };
55 } else {
56 if constexpr((ranges::statically_spanable_range<Rs> && ... && true)) {
57 // all input ranges have a static extent, so check the total size at compile time
58 // (work around an issue in MSVC that warns `total_size` is unused)
59 [[maybe_unused]] constexpr size_t total_size = (decltype(std::span{ranges})::extent + ... + 0);
60 static_assert(result.size() == total_size, "size of result buffer does not match the sum of input buffers");
61 } else {
62 // at least one input range has a dynamic extent, so check the total size at runtime
63 const size_t total_size = (ranges.size() + ... + 0);
64 BOTAN_ARG_CHECK(result.size() == total_size,
65 "result buffer has static extent that does not match the sum of input buffers");
66 }
67
68 // fill the result buffer and hold the current output-iterator position
69 return [itr = std::ranges::begin(result)](auto&& range) mutable {
70 std::copy(std::ranges::begin(range), std::ranges::end(range), itr);
71 std::advance(itr, std::ranges::size(range));
72 };
73 }
74 }();
75
76 // perform the actual concatenation
77 (fill_fn(std::forward<Rs>(ranges)), ...);
78
79 return result;
80}
81
82} // namespace detail
83
84/**
85 * Concatenate an arbitrary number of buffers. Performs range-checks as needed.
86 *
87 * The output type can be auto-detected based on the input ranges, or explicitly
88 * specified by the caller. If all input ranges have a static extent, the total
89 * size is calculated at compile time and a statically sized std::array<> is used.
90 * Otherwise this tries to use the type of the first input range as output type.
91 *
92 * Alternatively, the output container type can be specified explicitly.
93 */
94template <typename OutR = detail::AutoDetect, ranges::spanable_range... Rs>
95constexpr auto concat(Rs&&... ranges)
96 requires(all_same_v<std::ranges::range_value_t<Rs>...>)
97{
98 if constexpr(std::same_as<detail::AutoDetect, OutR>) {
99 // Try to auto-detect a reasonable output type given the input ranges
100 static_assert(sizeof...(Rs) > 0, "Cannot auto-detect the output type if not a single input range is provided.");
101 using candidate_result_t = std::remove_cvref_t<std::tuple_element_t<0, std::tuple<Rs...>>>;
102 using result_range_value_t = std::remove_cvref_t<std::ranges::range_value_t<candidate_result_t>>;
103
104 if constexpr((ranges::statically_spanable_range<Rs> && ...)) {
105 // If all input ranges have a static extent, we can calculate the total size at compile time
106 // and therefore can use a statically sized output container. This is constexpr.
107 constexpr size_t total_size = (decltype(std::span{ranges})::extent + ... + 0);
108 using out_array_t = std::array<result_range_value_t, total_size>;
109 return detail::concatenate<out_array_t>(std::forward<Rs>(ranges)...);
110 } else {
111 // If at least one input range has a dynamic extent, we must use a dynamically allocated output container.
112 // We assume that the user wants to use the first input range's container type as output type.
113 static_assert(
115 "First input range has static extent, but a dynamically allocated output range is required. Please explicitly specify a dynamically allocatable output type.");
116 return detail::concatenate<candidate_result_t>(std::forward<Rs>(ranges)...);
117 }
118 } else {
119 // The caller has explicitly specified the output type
120 return detail::concatenate<OutR>(std::forward<Rs>(ranges)...);
121 }
122}
123
124/**
125 * Append @p in to the end of @p out
126 *
127 * For a vector with a non-standard allocator (eg secure_vector), insert()
128 * falls back to an element-wise copy loop in libstdc++; this uses memcpy.
129 */
130template <typename T, typename Alloc>
131 requires std::is_trivially_copyable_v<T>
132void append(std::vector<T, Alloc>& out, std::type_identity_t<std::span<const T>> in) {
133 const size_t offset = out.size();
134 out.resize(offset + in.size());
135 copy_mem(std::span{out}.subspan(offset), in);
136}
137
138} // namespace Botan
139
140#endif
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
constexpr OutR concatenate(Rs &&... ranges)
Definition concat_util.h:34
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
constexpr decltype(auto) unwrap_strong_type(T &&t)
Generically unwraps a strong type to its underlying type.
void append(std::vector< T, Alloc > &out, std::type_identity_t< std::span< const T > > in)
constexpr auto concat(Rs &&... ranges)
Definition concat_util.h:95