Chris_M_Thomasson

Alignment Hack

Mar 7th, 2020
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <new>
  3. #include <cassert>
  4. #include <cstdlib>
  5. #include <cstddef>
  6. #include <cstdint>
  7.  
  8.  
  9. // Doctor Hackinstein!
  10. #define CT_RALLOC_ALIGN_UP(mp_ptr, mp_align) \
  11. ((unsigned char*)( \
  12. (((std::uintptr_t)(mp_ptr)) + ((mp_align) - 1)) \
  13. & ~(((mp_align) - 1)) \
  14. ))
  15.  
  16. #define CT_RALLOC_ALIGN_ASSERT(mp_ptr, mp_align) \
  17. (((unsigned char*)(mp_ptr)) == CT_RALLOC_ALIGN_UP(mp_ptr, mp_align))
  18.  
  19.  
  20. // Hackish indeed!
  21. template<std::size_t T_size>
  22. struct ct_local_mem
  23. {
  24. unsigned char m_bytes[T_size];
  25.  
  26. template<typename T>
  27. unsigned char* align_mem()
  28. {
  29. return align_mem<T>(alignof(T));
  30. }
  31.  
  32. template<typename T>
  33. unsigned char* align_mem(unsigned long align)
  34. {
  35. if (!align) align = alignof(T);
  36.  
  37. unsigned char* base = m_bytes;
  38. unsigned char* aligned = CT_RALLOC_ALIGN_UP(base, align);
  39.  
  40. assert(CT_RALLOC_ALIGN_ASSERT(aligned, align));
  41.  
  42. std::size_t size = aligned - m_bytes;
  43.  
  44. if (size + sizeof(T) + align > T_size)
  45. {
  46. throw;
  47. }
  48.  
  49. return aligned;
  50. }
  51. };
  52.  
  53.  
  54.  
  55. // A test program...
  56. struct foo
  57. {
  58. int m_a;
  59. int m_b;
  60.  
  61. foo(int a, int b) : m_a(a), m_b(b)
  62. {
  63. std::cout << this << "->foo::foo.m_a = " << m_a << "\n";
  64. std::cout << this << "->foo::foo.m_b = " << m_b << "\n";
  65. }
  66.  
  67. ~foo()
  68. {
  69. std::cout << this << "->foo::~foo.m_a = " << m_a << "\n";
  70. std::cout << this << "->foo::~foo.m_b = " << m_b << "\n";
  71. }
  72. };
  73.  
  74.  
  75. int main()
  76. {
  77. {
  78. // create some memory on the stack
  79. ct_local_mem<4096> local = { '\0' };
  80.  
  81.  
  82. // create a foo f
  83. std::cout << "Naturally aligned...\n";
  84. foo* f = new (local.align_mem<foo>(alignof(foo))) foo(1, 2);
  85.  
  86. // destroy f
  87. f->~foo();
  88.  
  89.  
  90.  
  91. // create a foo f aligned on a large byte boundary
  92. std::size_t alignment = 2048;
  93. std::cout << "\n\nForced aligned on a " << alignment << " byte boundary...\n";
  94.  
  95. // ensure the alignment of foo is okay with the boundary
  96. assert((alignment % alignof(foo)) == 0);
  97.  
  98.  
  99. f = new (local.align_mem<foo>(alignment)) foo(3, 4);
  100.  
  101. assert(CT_RALLOC_ALIGN_ASSERT(f, alignment));
  102.  
  103. // destroy f
  104. f->~foo();
  105. }
  106.  
  107. {
  108. std::cout << "\n\nFin\n";
  109. std::cout.flush();
  110. std::cin.get();
  111. }
  112.  
  113. return 0;
  114. }
Add Comment
Please, Sign In to add comment