vcmi_endian.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include <SDL_endian.h>
  3. /*
  4. * vcmi_endian.h, part of VCMI engine
  5. *
  6. * Authors: listed in file AUTHORS in main folder
  7. *
  8. * License: GNU General Public License v2.0 or later
  9. * Full text of license available in license.txt file, in main folder
  10. *
  11. */
  12. /* Reading values from memory.
  13. *
  14. * read_le_u16, read_le_u32 : read a little endian value from
  15. * memory. On big endian machines, the value will be byteswapped.
  16. */
  17. #if defined(linux) && defined(sparc)
  18. /* SPARC does not support unaligned memory access. Let gcc know when
  19. * to emit the right code. */
  20. struct unaligned_Uint16 { ui16 val __attribute__(( packed )); };
  21. struct unaligned_Uint32 { ui32 val __attribute__(( packed )); };
  22. static inline ui16 read_unaligned_u16(const void *p)
  23. {
  24. const struct unaligned_Uint16 *v = reinterpret_cast<const struct unaligned_Uint16 *>(p);
  25. return v->val;
  26. }
  27. static inline ui32 read_unaligned_u32(const void *p)
  28. {
  29. const struct unaligned_Uint32 *v = reinterpret_cast<const struct unaligned_Uint32 *>(p);
  30. return v->val;
  31. }
  32. #define read_le_u16(p) (SDL_SwapLE16(read_unaligned_u16(p)))
  33. #define read_le_u32(p) (SDL_SwapLE32(read_unaligned_u32(p)))
  34. #else
  35. #define read_le_u16(p) (SDL_SwapLE16(* reinterpret_cast<const ui16 *>(p)))
  36. #define read_le_u32(p) (SDL_SwapLE32(* reinterpret_cast<const ui32 *>(p)))
  37. #endif
  38. static inline char readChar(const ui8 * buffer, int & i)
  39. {
  40. return buffer[i++];
  41. }
  42. static inline std::string readString(const ui8 * buffer, int & i)
  43. {
  44. int len = read_le_u32(buffer + i);
  45. i += 4;
  46. assert(len >= 0 && len <= 500000); //not too long
  47. std::string ret;
  48. ret.reserve(len);
  49. for(int gg = 0; gg < len; ++gg)
  50. {
  51. ret += buffer[i++];
  52. }
  53. return ret;
  54. }