memory.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Memory-related utilities
  2. //
  3. // Platform: ISO C++ 98/11
  4. // $Id$
  5. //
  6. // (c) __vic 2019
  7. #ifndef __VIC_MEMORY_H
  8. #define __VIC_MEMORY_H
  9. #include<__vic/defs.h>
  10. #if defined(__VIC_STRICT_RAM_ALIGNMENT__) && !defined(__GNUC__)
  11. #include<cstring>
  12. #endif
  13. namespace __vic {
  14. //----------------------------------------------------------------------------
  15. template<class T>
  16. inline T load_unaligned(const void *p)
  17. {
  18. #ifdef __VIC_STRICT_RAM_ALIGNMENT__
  19. #ifdef __GNUC__
  20. struct wrapper { T v; } __attribute__((packed));
  21. return static_cast<const wrapper *>(p)->v;
  22. #else
  23. T v;
  24. std::memcpy(&v, p, sizeof v);
  25. return v;
  26. #endif
  27. #else // unaligned access is OK
  28. return *static_cast<const T *>(p);
  29. #endif
  30. }
  31. //----------------------------------------------------------------------------
  32. template<class T>
  33. inline void store_unaligned(void *p, T v)
  34. {
  35. #ifdef __VIC_STRICT_RAM_ALIGNMENT__
  36. #ifdef __GNUC__
  37. struct wrapper { T v; } __attribute__((packed));
  38. static_cast<wrapper *>(p)->v = v;
  39. #else
  40. std::memcpy(p, &v, sizeof v);
  41. #endif
  42. #else // unaligned access is OK
  43. *static_cast<T *>(p) = v;
  44. #endif
  45. }
  46. //----------------------------------------------------------------------------
  47. } // namespace
  48. #endif // header guard