vcmi_endian.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 * bufor, int &i)
  39. {
  40. return bufor[i++];
  41. }
  42. static inline std::string readString(const ui8 * bufor, int &i)
  43. {
  44. int len = read_le_u32(bufor + i); i+=4;
  45. assert(len >= 0 && len <= 500000); //not too long
  46. std::string ret; ret.reserve(len);
  47. for(int gg=0; gg<len; ++gg)
  48. {
  49. ret += bufor[i++];
  50. }
  51. return ret;
  52. }