two_byte_util.hpp 1.2 KB

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