four_byte_util.hpp 1.6 KB

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