vcmi_endian.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. //FIXME:library file depends on SDL - may cause troubles
  12. #include <SDL_endian.h>
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. /* Reading values from memory.
  15. *
  16. * read_le_u16, read_le_u32 : read a little endian value from
  17. * memory. On big endian machines, the value will be byteswapped.
  18. */
  19. #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
  20. #if defined(_MSC_VER)
  21. #define PACKED_STRUCT_BEGIN __pragma( pack(push, 1) )
  22. #define PACKED_STRUCT_END __pragma( pack(pop) )
  23. #else
  24. #define PACKED_STRUCT_BEGIN
  25. #define PACKED_STRUCT_END __attribute__(( packed ))
  26. #endif
  27. PACKED_STRUCT_BEGIN struct unaligned_Uint16 { ui16 val; } PACKED_STRUCT_END;
  28. PACKED_STRUCT_BEGIN struct unaligned_Uint32 { ui32 val; } PACKED_STRUCT_END;
  29. static inline ui16 read_unaligned_u16(const void *p)
  30. {
  31. const struct unaligned_Uint16 *v = reinterpret_cast<const struct unaligned_Uint16 *>(p);
  32. return v->val;
  33. }
  34. static inline ui32 read_unaligned_u32(const void *p)
  35. {
  36. const struct unaligned_Uint32 *v = reinterpret_cast<const struct unaligned_Uint32 *>(p);
  37. return v->val;
  38. }
  39. #define read_le_u16(p) (SDL_SwapLE16(read_unaligned_u16(p)))
  40. #define read_le_u32(p) (SDL_SwapLE32(read_unaligned_u32(p)))
  41. #else
  42. #warning UB: unaligned memory access
  43. #define read_le_u16(p) (SDL_SwapLE16(* reinterpret_cast<const ui16 *>(p)))
  44. #define read_le_u32(p) (SDL_SwapLE32(* reinterpret_cast<const ui32 *>(p)))
  45. #define PACKED_STRUCT_BEGIN
  46. #define PACKED_STRUCT_END
  47. #endif
  48. static inline char readChar(const ui8 * buffer, int & i)
  49. {
  50. return buffer[i++];
  51. }
  52. static inline std::string readString(const ui8 * buffer, int & i)
  53. {
  54. int len = read_le_u32(buffer + i);
  55. i += 4;
  56. assert(len >= 0 && len <= 500000); //not too long
  57. std::string ret;
  58. ret.reserve(len);
  59. for(int gg = 0; gg < len; ++gg)
  60. {
  61. ret += buffer[i++];
  62. }
  63. return ret;
  64. }
  65. VCMI_LIB_NAMESPACE_END