Botan 3.11.0
Crypto and TLS for C&
buffer_stuffer.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_BUFFER_STUFFER_H_
8#define BOTAN_BUFFER_STUFFER_H_
9
10#include <botan/assert.h>
11#include <botan/strong_type.h>
12#include <botan/types.h>
13#include <span>
14
15namespace Botan {
16
17/**
18 * @brief Helper class to ease in-place marshalling of concatenated fixed-length
19 * values.
20 *
21 * The size of the final buffer must be known from the start, reallocations are
22 * not performed.
23 */
24class BufferStuffer final {
25 public:
26 constexpr explicit BufferStuffer(std::span<uint8_t> buffer) : m_buffer(buffer) {}
27
28 /**
29 * @returns a span for the next @p bytes bytes in the concatenated buffer.
30 * Checks that the buffer is not exceeded.
31 */
32 constexpr std::span<uint8_t> next(size_t bytes) {
33 BOTAN_STATE_CHECK(m_buffer.size() >= bytes);
34
35 auto result = m_buffer.first(bytes);
36 m_buffer = m_buffer.subspan(bytes);
37 return result;
38 }
39
40 template <size_t bytes>
41 constexpr std::span<uint8_t, bytes> next() {
42 BOTAN_STATE_CHECK(m_buffer.size() >= bytes);
43
44 auto result = m_buffer.first<bytes>();
45 m_buffer = m_buffer.subspan(bytes);
46 return result;
47 }
48
49 template <concepts::contiguous_strong_type StrongT>
50 StrongSpan<StrongT> next(size_t bytes) {
51 return StrongSpan<StrongT>(next(bytes));
52 }
53
54 /**
55 * @returns a reference to the next single byte in the buffer
56 */
57 constexpr uint8_t& next_byte() { return next(1)[0]; }
58
59 constexpr void append(std::span<const uint8_t> buffer) {
60 auto sink = next(buffer.size());
61 std::copy(buffer.begin(), buffer.end(), sink.begin());
62 }
63
64 constexpr void append(uint8_t b, size_t repeat = 1) {
65 auto sink = next(repeat);
66 std::fill(sink.begin(), sink.end(), b);
67 }
68
69 constexpr bool full() const { return m_buffer.empty(); }
70
71 constexpr size_t remaining_capacity() const { return m_buffer.size(); }
72
73 private:
74 std::span<uint8_t> m_buffer;
75};
76
77} // namespace Botan
78
79#endif
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
constexpr void append(std::span< const uint8_t > buffer)
constexpr void append(uint8_t b, size_t repeat=1)
constexpr size_t remaining_capacity() const
StrongSpan< StrongT > next(size_t bytes)
constexpr std::span< uint8_t > next(size_t bytes)
constexpr std::span< uint8_t, bytes > next()
constexpr uint8_t & next_byte()
constexpr BufferStuffer(std::span< uint8_t > buffer)
constexpr bool full() const