2
0

vcmi_endian.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * vcmi_endian.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <boost/endian/conversion.hpp> //FIXME: use std::byteswap in C++23
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. /* Reading values from memory.
  14. *
  15. * read_le_u16, read_le_u32 : read a little endian value from
  16. * memory. On big endian machines, the value will be byteswapped.
  17. */
  18. #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
  19. #if defined(_MSC_VER)
  20. #define PACKED_STRUCT_BEGIN __pragma( pack(push, 1) )
  21. #define PACKED_STRUCT_END __pragma( pack(pop) )
  22. #else
  23. #define PACKED_STRUCT_BEGIN
  24. #define PACKED_STRUCT_END __attribute__(( packed ))
  25. #endif
  26. PACKED_STRUCT_BEGIN struct unaligned_Uint16 { ui16 val; } PACKED_STRUCT_END;
  27. PACKED_STRUCT_BEGIN struct unaligned_Uint32 { ui32 val; } PACKED_STRUCT_END;
  28. static inline ui16 read_unaligned_u16(const void *p)
  29. {
  30. const struct unaligned_Uint16 *v = reinterpret_cast<const struct unaligned_Uint16 *>(p);
  31. return v->val;
  32. }
  33. static inline ui32 read_unaligned_u32(const void *p)
  34. {
  35. const struct unaligned_Uint32 *v = reinterpret_cast<const struct unaligned_Uint32 *>(p);
  36. return v->val;
  37. }
  38. #define read_le_u16(p) (boost::endian::native_to_little(read_unaligned_u16(p)))
  39. #define read_le_u32(p) (boost::endian::native_to_little(read_unaligned_u32(p)))
  40. #else
  41. #warning UB: unaligned memory access
  42. #define read_le_u16(p) (boost::endian::native_to_little(* reinterpret_cast<const ui16 *>(p)))
  43. #define read_le_u32(p) (boost::endian::native_to_little(* reinterpret_cast<const ui32 *>(p)))
  44. #define PACKED_STRUCT_BEGIN
  45. #define PACKED_STRUCT_END
  46. #endif
  47. static inline char readChar(const ui8 * buffer, int & i)
  48. {
  49. return buffer[i++];
  50. }
  51. static inline std::string readString(const ui8 * buffer, int & i)
  52. {
  53. int len = read_le_u32(buffer + i);
  54. i += 4;
  55. assert(len >= 0 && len <= 500000); //not too long
  56. std::string ret;
  57. ret.reserve(len);
  58. for(int gg = 0; gg < len; ++gg)
  59. {
  60. ret += buffer[i++];
  61. }
  62. return ret;
  63. }
  64. VCMI_LIB_NAMESPACE_END