vcmi_endian.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma once
  2. //FIXME:library file depends on SDL - make cause troubles
  3. #include <SDL_endian.h>
  4. /*
  5. * vcmi_endian.h, part of VCMI engine
  6. *
  7. * Authors: listed in file AUTHORS in main folder
  8. *
  9. * License: GNU General Public License v2.0 or later
  10. * Full text of license available in license.txt file, in main folder
  11. *
  12. */
  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(linux) || defined(__linux) || defined(__linux__)) && (defined(sparc) || defined(__arm__))
  19. /* SPARC does not support unaligned memory access. Let gcc know when
  20. * to emit the right code. */
  21. struct unaligned_Uint16 { ui16 val __attribute__(( packed )); };
  22. struct unaligned_Uint32 { ui32 val __attribute__(( packed )); };
  23. static inline ui16 read_unaligned_u16(const void *p)
  24. {
  25. const struct unaligned_Uint16 *v = reinterpret_cast<const struct unaligned_Uint16 *>(p);
  26. return v->val;
  27. }
  28. static inline ui32 read_unaligned_u32(const void *p)
  29. {
  30. const struct unaligned_Uint32 *v = reinterpret_cast<const struct unaligned_Uint32 *>(p);
  31. return v->val;
  32. }
  33. #define read_le_u16(p) (SDL_SwapLE16(read_unaligned_u16(p)))
  34. #define read_le_u32(p) (SDL_SwapLE32(read_unaligned_u32(p)))
  35. #define PACKED_STRUCT __attribute__(( packed ))
  36. #else
  37. #define read_le_u16(p) (SDL_SwapLE16(* reinterpret_cast<const ui16 *>(p)))
  38. #define read_le_u32(p) (SDL_SwapLE32(* reinterpret_cast<const ui32 *>(p)))
  39. #define PACKED_STRUCT
  40. #endif
  41. static inline char readChar(const ui8 * buffer, int & i)
  42. {
  43. return buffer[i++];
  44. }
  45. static inline std::string readString(const ui8 * buffer, int & i)
  46. {
  47. int len = read_le_u32(buffer + i);
  48. i += 4;
  49. assert(len >= 0 && len <= 500000); //not too long
  50. std::string ret;
  51. ret.reserve(len);
  52. for(int gg = 0; gg < len; ++gg)
  53. {
  54. ret += buffer[i++];
  55. }
  56. return ret;
  57. }