Botan 3.11.0
Crypto and TLS for C&
buffer_slicer.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_SLICER_H_
8#define BOTAN_BUFFER_SLICER_H_
9
10#include <botan/assert.h>
11#include <botan/concepts.h>
12#include <botan/secmem.h>
13#include <botan/strong_type.h>
14#include <botan/types.h>
15#include <span>
16#include <vector>
17
18namespace Botan {
19
20/**
21 * Helper class to ease unmarshalling of concatenated fixed-length values
22 */
23class BufferSlicer final {
24 public:
25 explicit BufferSlicer(std::span<const uint8_t> buffer) : m_remaining(buffer) {}
26
27 template <concepts::contiguous_container ContainerT>
28 auto copy(const size_t count) {
29 const auto result = take(count);
30 return ContainerT(result.begin(), result.end());
31 }
32
33 auto copy_as_vector(const size_t count) { return copy<std::vector<uint8_t>>(count); }
34
35 auto copy_as_secure_vector(const size_t count) { return copy<secure_vector<uint8_t>>(count); }
36
37 std::span<const uint8_t> take(const size_t count) {
38 BOTAN_STATE_CHECK(remaining() >= count);
39 auto result = m_remaining.first(count);
40 m_remaining = m_remaining.subspan(count);
41 return result;
42 }
43
44 template <size_t count>
45 std::span<const uint8_t, count> take() {
46 BOTAN_STATE_CHECK(remaining() >= count);
47 auto result = m_remaining.first<count>();
48 m_remaining = m_remaining.subspan(count);
49 return result;
50 }
51
52 template <concepts::contiguous_strong_type T>
53 StrongSpan<const T> take(const size_t count) {
54 return StrongSpan<const T>(take(count));
55 }
56
57 uint8_t take_byte() { return take(1)[0]; }
58
59 void copy_into(std::span<uint8_t> sink) {
60 const auto data = take(sink.size());
61 std::copy(data.begin(), data.end(), sink.begin());
62 }
63
64 void skip(const size_t count) { take(count); }
65
66 size_t remaining() const { return m_remaining.size(); }
67
68 bool empty() const { return m_remaining.empty(); }
69
70 private:
71 std::span<const uint8_t> m_remaining;
72};
73
74} // namespace Botan
75
76#endif
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
size_t remaining() const
void skip(const size_t count)
auto copy_as_secure_vector(const size_t count)
void copy_into(std::span< uint8_t > sink)
BufferSlicer(std::span< const uint8_t > buffer)
std::span< const uint8_t, count > take()
auto copy(const size_t count)
std::span< const uint8_t > take(const size_t count)
StrongSpan< const T > take(const size_t count)
auto copy_as_vector(const size_t count)