mqtt_cpp
four_byte_util.hpp
Go to the documentation of this file.
1 // Copyright Takatoshi Kondo 2018
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(MQTT_FOUR_BYTE_UTIL_HPP)
8 #define MQTT_FOUR_BYTE_UTIL_HPP
9 
10 #include <string>
11 #include <cstdint>
12 #include <algorithm>
13 
14 #include <boost/assert.hpp>
15 #include <boost/container/static_vector.hpp>
16 
17 #include <mqtt/namespace.hpp>
18 
19 namespace MQTT_NS {
20 
21 inline boost::container::static_vector<char, 4> num_to_4bytes(std::uint32_t val) {
22  return {
23  static_cast<char>(val >> 24),
24  static_cast<char>(val >> 16),
25  static_cast<char>(val >> 8),
26  static_cast<char>(val & 0xff)
27  };
28 }
29 
30 template <typename T>
31 inline void add_uint32_t_to_buf(T& buf, std::uint32_t num) {
32  buf.push_back(static_cast<char>(num >> 24));
33  buf.push_back(static_cast<char>(num >> 16));
34  buf.push_back(static_cast<char>(num >> 8));
35  buf.push_back(static_cast<char>(num & 0xff));
36 }
37 
38 template <typename It>
39 constexpr std::uint32_t make_uint32_t(It b, It e) {
40  (void)e; // Avoid warning in release builds about unused variable
41  BOOST_ASSERT(std::distance(b, e) == 4);
42  auto b1 = b++;
43  auto b2 = b++;
44  auto b3 = b++;
45  auto b4 = b++;
46  return
47  static_cast<std::uint32_t>(
48  (static_cast<std::uint16_t>(*b1) & 0xff) << 24 |
49  (static_cast<std::uint16_t>(*b2) & 0xff) << 16 |
50  (static_cast<std::uint16_t>(*b3) & 0xff) << 8 |
51  (static_cast<std::uint16_t>(*b4) & 0xff)
52  );
53 }
54 
55 } // namespace MQTT_NS
56 
57 #endif // MQTT_FOUR_BYTE_UTIL_HPP
Definition: any.hpp:27
void add_uint32_t_to_buf(T &buf, std::uint32_t num)
Definition: four_byte_util.hpp:31
boost::container::static_vector< char, 4 > num_to_4bytes(std::uint32_t val)
Definition: four_byte_util.hpp:21
constexpr std::uint32_t make_uint32_t(It b, It e)
Definition: four_byte_util.hpp:39