RecastAlloc.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen [email protected]
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #ifndef RECASTALLOC_H
  19. #define RECASTALLOC_H
  20. #include <stddef.h>
  21. #include <stdint.h>
  22. #include <RecastAssert.h>
  23. /// Provides hint values to the memory allocator on how long the
  24. /// memory is expected to be used.
  25. enum rcAllocHint
  26. {
  27. RC_ALLOC_PERM, ///< Memory will persist after a function call.
  28. RC_ALLOC_TEMP ///< Memory used temporarily within a function.
  29. };
  30. /// A memory allocation function.
  31. // @param[in] size The size, in bytes of memory, to allocate.
  32. // @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
  33. // @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
  34. /// @see rcAllocSetCustom
  35. typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint);
  36. /// A memory deallocation function.
  37. /// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc.
  38. /// @see rcAllocSetCustom
  39. typedef void (rcFreeFunc)(void* ptr);
  40. /// Sets the base custom allocation functions to be used by Recast.
  41. /// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
  42. /// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
  43. void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
  44. /// Allocates a memory block.
  45. /// @param[in] size The size, in bytes of memory, to allocate.
  46. /// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
  47. /// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
  48. /// @see rcFree
  49. void* rcAlloc(size_t size, rcAllocHint hint);
  50. /// Deallocates a memory block.
  51. /// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
  52. /// @see rcAlloc
  53. void rcFree(void* ptr);
  54. /// An implementation of operator new usable for placement new. The default one is part of STL (which we don't use).
  55. /// rcNewTag is a dummy type used to differentiate our operator from the STL one, in case users import both Recast
  56. /// and STL.
  57. struct rcNewTag {};
  58. inline void* operator new(size_t, const rcNewTag&, void* p) { return p; }
  59. /// Signed to avoid warnnings when comparing to int loop indexes, and common error with comparing to zero.
  60. /// MSVC2010 has a bug where ssize_t is unsigned (!!!).
  61. typedef intptr_t rcSizeType;
  62. #define RC_SIZE_MAX INTPTR_MAX
  63. /// Macros to hint to the compiler about the likeliest branch. Please add a benchmark that demonstrates a performance
  64. /// improvement before introducing use cases.
  65. #if defined(__GNUC__) || defined(__clang__)
  66. #define rcLikely(x) __builtin_expect((x), true)
  67. #define rcUnlikely(x) __builtin_expect((x), false)
  68. #else
  69. #define rcLikely(x) (x)
  70. #define rcUnlikely(x) (x)
  71. #endif
  72. /// Variable-sized storage type. Mimics the interface of std::vector<T> with some notable differences:
  73. /// * Uses rcAlloc()/rcFree() to handle storage.
  74. /// * No support for a custom allocator.
  75. /// * Uses signed size instead of size_t to avoid warnings in for loops: "for (int i = 0; i < foo.size(); i++)"
  76. /// * Omits methods of limited utility: insert/erase, (bad performance), at (we don't use exceptions), operator=.
  77. /// * assign() and the pre-sizing constructor follow C++11 semantics -- they don't construct a temporary if no value is provided.
  78. /// * push_back() and resize() support adding values from the current vector. Range-based constructors and assign(begin, end) do not.
  79. /// * No specialization for bool.
  80. template <typename T, rcAllocHint H>
  81. class rcVectorBase {
  82. rcSizeType m_size;
  83. rcSizeType m_cap;
  84. T* m_data;
  85. // Constructs a T at the give address with either the copy constructor or the default.
  86. static void construct(T* p, const T& v) { ::new(rcNewTag(), (void*)p) T(v); }
  87. static void construct(T* p) { ::new(rcNewTag(), (void*)p) T; }
  88. static void construct_range(T* begin, T* end);
  89. static void construct_range(T* begin, T* end, const T& value);
  90. static void copy_range(T* dst, const T* begin, const T* end);
  91. void destroy_range(rcSizeType begin, rcSizeType end);
  92. // Creates an array of the given size, copies all of this vector's data into it, and returns it.
  93. T* allocate_and_copy(rcSizeType size);
  94. void resize_impl(rcSizeType size, const T* value);
  95. public:
  96. typedef rcSizeType size_type;
  97. typedef T value_type;
  98. rcVectorBase() : m_size(0), m_cap(0), m_data(0) {};
  99. rcVectorBase(const rcVectorBase<T, H>& other) : m_size(0), m_cap(0), m_data(0) { assign(other.begin(), other.end()); }
  100. explicit rcVectorBase(rcSizeType count) : m_size(0), m_cap(0), m_data(0) { resize(count); }
  101. rcVectorBase(rcSizeType count, const T& value) : m_size(0), m_cap(0), m_data(0) { resize(count, value); }
  102. rcVectorBase(const T* begin, const T* end) : m_size(0), m_cap(0), m_data(0) { assign(begin, end); }
  103. ~rcVectorBase() { destroy_range(0, m_size); rcFree(m_data); }
  104. // Unlike in std::vector, we return a bool to indicate whether the alloc was successful.
  105. bool reserve(rcSizeType size);
  106. void assign(rcSizeType count, const T& value) { clear(); resize(count, value); }
  107. void assign(const T* begin, const T* end);
  108. void resize(rcSizeType size) { resize_impl(size, NULL); }
  109. void resize(rcSizeType size, const T& value) { resize_impl(size, &value); }
  110. // Not implemented as resize(0) because resize requires T to be default-constructible.
  111. void clear() { destroy_range(0, m_size); m_size = 0; }
  112. void push_back(const T& value);
  113. void pop_back() { rcAssert(m_size > 0); back().~T(); m_size--; }
  114. rcSizeType size() const { return m_size; }
  115. rcSizeType capacity() const { return m_cap; }
  116. bool empty() const { return size() == 0; }
  117. const T& operator[](rcSizeType i) const { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
  118. T& operator[](rcSizeType i) { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
  119. const T& front() const { rcAssert(m_size); return m_data[0]; }
  120. T& front() { rcAssert(m_size); return m_data[0]; }
  121. const T& back() const { rcAssert(m_size); return m_data[m_size - 1]; };
  122. T& back() { rcAssert(m_size); return m_data[m_size - 1]; };
  123. const T* data() const { return m_data; }
  124. T* data() { return m_data; }
  125. T* begin() { return m_data; }
  126. T* end() { return m_data + m_size; }
  127. const T* begin() const { return m_data; }
  128. const T* end() const { return m_data + m_size; }
  129. void swap(rcVectorBase<T, H>& other);
  130. // Explicitly deleted.
  131. rcVectorBase& operator=(const rcVectorBase<T, H>& other);
  132. };
  133. template<typename T, rcAllocHint H>
  134. bool rcVectorBase<T, H>::reserve(rcSizeType count) {
  135. if (count <= m_cap) {
  136. return true;
  137. }
  138. T* new_data = allocate_and_copy(count);
  139. if (!new_data) {
  140. return false;
  141. }
  142. destroy_range(0, m_size);
  143. rcFree(m_data);
  144. m_data = new_data;
  145. m_cap = count;
  146. return true;
  147. }
  148. template <typename T, rcAllocHint H>
  149. T* rcVectorBase<T, H>::allocate_and_copy(rcSizeType size) {
  150. rcAssert(RC_SIZE_MAX / static_cast<rcSizeType>(sizeof(T)) >= size);
  151. T* new_data = static_cast<T*>(rcAlloc(sizeof(T) * size, H));
  152. if (new_data) {
  153. copy_range(new_data, m_data, m_data + m_size);
  154. }
  155. return new_data;
  156. }
  157. template <typename T, rcAllocHint H>
  158. void rcVectorBase<T, H>::assign(const T* begin, const T* end) {
  159. clear();
  160. reserve(end - begin);
  161. m_size = end - begin;
  162. copy_range(m_data, begin, end);
  163. }
  164. template <typename T, rcAllocHint H>
  165. void rcVectorBase<T, H>::push_back(const T& value) {
  166. // rcLikely increases performance by ~50% on BM_rcVector_PushPreallocated,
  167. // and by ~2-5% on BM_rcVector_Push.
  168. if (rcLikely(m_size < m_cap)) {
  169. construct(m_data + m_size++, value);
  170. return;
  171. }
  172. rcAssert(RC_SIZE_MAX / 2 >= m_size);
  173. rcSizeType new_cap = m_size ? 2*m_size : 1;
  174. T* data = allocate_and_copy(new_cap);
  175. // construct between allocate and destroy+free in case value is
  176. // in this vector.
  177. construct(data + m_size, value);
  178. destroy_range(0, m_size);
  179. m_size++;
  180. m_cap = new_cap;
  181. rcFree(m_data);
  182. m_data = data;
  183. }
  184. template <typename T, rcAllocHint H>
  185. void rcVectorBase<T, H>::resize_impl(rcSizeType size, const T* value) {
  186. if (size < m_size) {
  187. destroy_range(size, m_size);
  188. m_size = size;
  189. } else if (size > m_size) {
  190. T* new_data = allocate_and_copy(size);
  191. // We defer deconstructing/freeing old data until after constructing
  192. // new elements in case "value" is there.
  193. if (value) {
  194. construct_range(new_data + m_size, new_data + size, *value);
  195. } else {
  196. construct_range(new_data + m_size, new_data + size);
  197. }
  198. destroy_range(0, m_size);
  199. rcFree(m_data);
  200. m_data = new_data;
  201. m_cap = size;
  202. m_size = size;
  203. }
  204. }
  205. template <typename T, rcAllocHint H>
  206. void rcVectorBase<T, H>::swap(rcVectorBase<T, H>& other) {
  207. // TODO: Reorganize headers so we can use rcSwap here.
  208. rcSizeType tmp_cap = other.m_cap;
  209. rcSizeType tmp_size = other.m_size;
  210. T* tmp_data = other.m_data;
  211. other.m_cap = m_cap;
  212. other.m_size = m_size;
  213. other.m_data = m_data;
  214. m_cap = tmp_cap;
  215. m_size = tmp_size;
  216. m_data = tmp_data;
  217. }
  218. // static
  219. template <typename T, rcAllocHint H>
  220. void rcVectorBase<T, H>::construct_range(T* begin, T* end) {
  221. for (T* p = begin; p < end; p++) {
  222. construct(p);
  223. }
  224. }
  225. // static
  226. template <typename T, rcAllocHint H>
  227. void rcVectorBase<T, H>::construct_range(T* begin, T* end, const T& value) {
  228. for (T* p = begin; p < end; p++) {
  229. construct(p, value);
  230. }
  231. }
  232. // static
  233. template <typename T, rcAllocHint H>
  234. void rcVectorBase<T, H>::copy_range(T* dst, const T* begin, const T* end) {
  235. for (rcSizeType i = 0 ; i < end - begin; i++) {
  236. construct(dst + i, begin[i]);
  237. }
  238. }
  239. template <typename T, rcAllocHint H>
  240. void rcVectorBase<T, H>::destroy_range(rcSizeType begin, rcSizeType end) {
  241. for (rcSizeType i = begin; i < end; i++) {
  242. m_data[i].~T();
  243. }
  244. }
  245. template <typename T>
  246. class rcTempVector : public rcVectorBase<T, RC_ALLOC_TEMP> {
  247. typedef rcVectorBase<T, RC_ALLOC_TEMP> Base;
  248. public:
  249. rcTempVector() : Base() {}
  250. explicit rcTempVector(rcSizeType size) : Base(size) {}
  251. rcTempVector(rcSizeType size, const T& value) : Base(size, value) {}
  252. rcTempVector(const rcTempVector<T>& other) : Base(other) {}
  253. rcTempVector(const T* begin, const T* end) : Base(begin, end) {}
  254. };
  255. template <typename T>
  256. class rcPermVector : public rcVectorBase<T, RC_ALLOC_PERM> {
  257. typedef rcVectorBase<T, RC_ALLOC_PERM> Base;
  258. public:
  259. rcPermVector() : Base() {}
  260. explicit rcPermVector(rcSizeType size) : Base(size) {}
  261. rcPermVector(rcSizeType size, const T& value) : Base(size, value) {}
  262. rcPermVector(const rcPermVector<T>& other) : Base(other) {}
  263. rcPermVector(const T* begin, const T* end) : Base(begin, end) {}
  264. };
  265. /// Legacy class. Prefer rcVector<int>.
  266. class rcIntArray
  267. {
  268. rcTempVector<int> m_impl;
  269. public:
  270. rcIntArray() {}
  271. rcIntArray(int n) : m_impl(n, 0) {}
  272. void push(int item) { m_impl.push_back(item); }
  273. void resize(int size) { m_impl.resize(size); }
  274. int pop()
  275. {
  276. int v = m_impl.back();
  277. m_impl.pop_back();
  278. return v;
  279. }
  280. int size() const { return m_impl.size(); }
  281. int& operator[](int index) { return m_impl[index]; }
  282. int operator[](int index) const { return m_impl[index]; }
  283. };
  284. /// A simple helper class used to delete an array when it goes out of scope.
  285. /// @note This class is rarely if ever used by the end user.
  286. template<class T> class rcScopedDelete
  287. {
  288. T* ptr;
  289. public:
  290. /// Constructs an instance with a null pointer.
  291. inline rcScopedDelete() : ptr(0) {}
  292. /// Constructs an instance with the specified pointer.
  293. /// @param[in] p An pointer to an allocated array.
  294. inline rcScopedDelete(T* p) : ptr(p) {}
  295. inline ~rcScopedDelete() { rcFree(ptr); }
  296. /// The root array pointer.
  297. /// @return The root array pointer.
  298. inline operator T*() { return ptr; }
  299. private:
  300. // Explicitly disabled copy constructor and copy assignment operator.
  301. rcScopedDelete(const rcScopedDelete&);
  302. rcScopedDelete& operator=(const rcScopedDelete&);
  303. };
  304. #endif