vcmi_endian.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 - make 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(linux) || defined(__linux) || defined(__linux__)) && (defined(sparc) || defined(__arm__))
  20. /* SPARC does not support unaligned memory access. Let gcc know when
  21. * to emit the right code. */
  22. struct unaligned_Uint16 { ui16 val __attribute__(( packed )); };
  23. struct unaligned_Uint32 { ui32 val __attribute__(( packed )); };
  24. static inline ui16 read_unaligned_u16(const void *p)
  25. {
  26. const struct unaligned_Uint16 *v = reinterpret_cast<const struct unaligned_Uint16 *>(p);
  27. return v->val;
  28. }
  29. static inline ui32 read_unaligned_u32(const void *p)
  30. {
  31. const struct unaligned_Uint32 *v = reinterpret_cast<const struct unaligned_Uint32 *>(p);
  32. return v->val;
  33. }
  34. #define read_le_u16(p) (SDL_SwapLE16(read_unaligned_u16(p)))
  35. #define read_le_u32(p) (SDL_SwapLE32(read_unaligned_u32(p)))
  36. #define PACKED_STRUCT __attribute__(( packed ))
  37. #else
  38. #define read_le_u16(p) (SDL_SwapLE16(* reinterpret_cast<const ui16 *>(p)))
  39. #define read_le_u32(p) (SDL_SwapLE32(* reinterpret_cast<const ui32 *>(p)))
  40. #define PACKED_STRUCT
  41. #endif
  42. static inline char readChar(const ui8 * buffer, int & i)
  43. {
  44. return buffer[i++];
  45. }
  46. static inline std::string readString(const ui8 * buffer, int & i)
  47. {
  48. int len = read_le_u32(buffer + i);
  49. i += 4;
  50. assert(len >= 0 && len <= 500000); //not too long
  51. std::string ret;
  52. ret.reserve(len);
  53. for(int gg = 0; gg < len; ++gg)
  54. {
  55. ret += buffer[i++];
  56. }
  57. return ret;
  58. }
  59. VCMI_LIB_NAMESPACE_END