async_mqtt 5.0.0
Loading...
Searching...
No Matches
copy_to_static_vector.hpp
1// Copyright Takatoshi Kondo 2022
2//
3// Distributed under the Boost Software License, Version 1.0.
4// (See accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7#if !defined(ASYNC_MQTT_PACKET_COPY_TO_STATIC_VECTOR_HPP)
8#define ASYNC_MQTT_PACKET_COPY_TO_STATIC_VECTOR_HPP
9
10#include <algorithm>
11
12#include <async_mqtt/util/static_vector.hpp>
13#include <async_mqtt/util/optional.hpp>
14#include <async_mqtt/buffer.hpp>
15#include <async_mqtt/exception.hpp>
16#include <async_mqtt/variable_bytes.hpp>
17
18namespace async_mqtt {
19
20template <std::size_t N>
21bool copy_advance(buffer& buf, static_vector<char, N>& sv) {
22 if (buf.size() < sv.capacity()) return false;
23 std::copy(
24 buf.begin(),
25 std::next(buf.begin(), typename static_vector<char, N>::difference_type(sv.capacity())),
26 sv.begin()
27 );
28 buf.remove_prefix(sv.capacity());
29 return true;
30}
31
32template <std::size_t N>
33bool insert_advance(buffer& buf, static_vector<char, N>& sv) {
34 if (buf.size() < sv.capacity()) return false;
35 std::copy(
36 buf.begin(),
37 std::next(buf.begin(), typename static_vector<char, N>::difference_type(sv.capacity())),
38 std::back_inserter(sv)
39 );
40 buf.remove_prefix(sv.capacity());
41 return true;
42}
43
44inline
45optional<std::uint32_t> insert_advance_variable_length(buffer& buf, static_vector<char, 4>& sv) {
46 if (buf.empty()) return nullopt;
47 std::uint32_t variable_length = 0;
48 auto it = buf.begin();
49 // it is updated as consmed position
50 if (auto len_opt = variable_bytes_to_val(it, buf.end())) {
51 variable_length = *len_opt;
52 }
53 else {
54 return nullopt;
55 }
56 std::copy(
57 buf.begin(),
58 it,
59 std::back_inserter(sv));
60 buf.remove_prefix(std::size_t(std::distance(buf.begin(), it)));
61 return variable_length;
62}
63
64} // namespace async_mqtt
65
66#endif // ASYNC_MQTT_PACKET_COPY_TO_STATIC_VECTOR_HPP