mqtt_cpp
two_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_TWO_BYTE_UTIL_HPP)
8 #define MQTT_TWO_BYTE_UTIL_HPP
9 
10 #include <string>
11 #include <cstdint>
12 
13 #include <boost/assert.hpp>
14 #include <boost/container/static_vector.hpp>
15 
16 #include <mqtt/namespace.hpp>
17 
18 namespace MQTT_NS {
19 
20 inline boost::container::static_vector<char, 2> num_to_2bytes(std::uint16_t val) {
21  return {
22  static_cast<char>(val >> 8),
23  static_cast<char>(val & 0xff)
24  };
25 }
26 
27 template <typename T>
28 inline void add_uint16_t_to_buf(T& buf, std::uint16_t num) {
29  buf.push_back(static_cast<char>(num >> 8));
30  buf.push_back(static_cast<char>(num & 0xff));
31 }
32 
33 template <typename It>
34 constexpr std::uint16_t make_uint16_t(It b, It e) {
35  (void)e; // Avoid warning in release builds about unused variable
36  BOOST_ASSERT(std::distance(b, e) == 2);
37  auto b1 = b++;
38  auto b2 = b++;
39  return
40  static_cast<std::uint16_t>(
41  (static_cast<std::uint16_t>(*b1) & 0xff) << 8 |
42  (static_cast<std::uint16_t>(*b2) & 0xff)
43  );
44 }
45 
46 } // namespace MQTT_NS
47 
48 #endif // MQTT_TWO_BYTE_UTIL_HPP
Definition: any.hpp:27
boost::container::static_vector< char, 2 > num_to_2bytes(std::uint16_t val)
Definition: two_byte_util.hpp:20
void add_uint16_t_to_buf(T &buf, std::uint16_t num)
Definition: two_byte_util.hpp:28
constexpr std::uint16_t make_uint16_t(It b, It e)
Definition: two_byte_util.hpp:34