You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 regels
1.7 KiB

  1. #pragma once
  2. namespace utl
  3. {
  4. namespace __impl
  5. {
  6. template<class T, size_t N = sizeof(T)>
  7. struct network_convert_helper;
  8. }
  9. template<class T>
  10. inline T hton(const T& value)
  11. { return __impl::network_convert_helper<T>::hton(value); }
  12. template<class T>
  13. inline T ntoh(const T& value)
  14. { return __impl::network_convert_helper<T>::ntoh(value); }
  15. namespace __impl
  16. {
  17. template<class T>
  18. struct network_convert_helper<T, 1>
  19. {
  20. static inline T hton(const T& t)
  21. { return t; }
  22. static inline T ntoh(const T& t)
  23. { return t; }
  24. };
  25. template<class T>
  26. struct network_convert_helper<T, 2>
  27. {
  28. static inline T hton(const T& t)
  29. { return reinterpret_cast<T>(htobe16(reinterpret_cast<uint16_t>(t))); }
  30. static inline T ntoh(const T& t)
  31. { return reinterpret_cast<T>(be16toh(reinterpret_cast<uint16_t>(t))); }
  32. };
  33. template<class T>
  34. struct network_convert_helper<T, 4>
  35. {
  36. static inline T hton(const T& t)
  37. { return reinterpret_cast<T>(htobe32(reinterpret_cast<uint32_t>(t))); }
  38. static inline T ntoh(const T& t)
  39. { return reinterpret_cast<T>(be32toh(reinterpret_cast<uint32_t>(t))); }
  40. };
  41. template<class T>
  42. struct network_convert_helper<T, 8>
  43. {
  44. static inline T hton(const T& t)
  45. { return reinterpret_cast<T>(htobe64(reinterpret_cast<uint64_t>(t))); }
  46. static inline T ntoh(const T& t)
  47. { return reinterpret_cast<T>(be64toh(reinterpret_cast<uint64_t>(t))); }
  48. };
  49. }
  50. }