RecastAlloc.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 "RecastAssert.h"
  21. #include <stdlib.h>
  22. #include <stdint.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. ///
  44. /// @see rcAlloc, rcFree
  45. void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
  46. /// Allocates a memory block.
  47. ///
  48. /// @param[in] size The size, in bytes of memory, to allocate.
  49. /// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
  50. /// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
  51. ///
  52. /// @see rcFree, rcAllocSetCustom
  53. void* rcAlloc(size_t size, rcAllocHint hint);
  54. /// Deallocates a memory block. If @p ptr is NULL, this does nothing.
  55. ///
  56. /// @warning This function leaves the value of @p ptr unchanged. So it still
  57. /// points to the same (now invalid) location, and not to null.
  58. ///
  59. /// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
  60. ///
  61. /// @see rcAlloc, rcAllocSetCustom
  62. void rcFree(void* ptr);
  63. /// An implementation of operator new usable for placement new. The default one is part of STL (which we don't use).
  64. /// rcNewTag is a dummy type used to differentiate our operator from the STL one, in case users import both Recast
  65. /// and STL.
  66. struct rcNewTag {};
  67. inline void* operator new(size_t, const rcNewTag&, void* p) { return p; }
  68. inline void operator delete(void*, const rcNewTag&, void*) {}
  69. /// Signed to avoid warnnings when comparing to int loop indexes, and common error with comparing to zero.
  70. /// MSVC2010 has a bug where ssize_t is unsigned (!!!).
  71. typedef intptr_t rcSizeType;
  72. #define RC_SIZE_MAX INTPTR_MAX
  73. /// Macros to hint to the compiler about the likeliest branch. Please add a benchmark that demonstrates a performance
  74. /// improvement before introducing use cases.
  75. #if defined(__GNUC__) || defined(__clang__)
  76. #define rcLikely(x) __builtin_expect((x), true)
  77. #define rcUnlikely(x) __builtin_expect((x), false)
  78. #else
  79. #define rcLikely(x) (x)
  80. #define rcUnlikely(x) (x)
  81. #endif
  82. /// Variable-sized storage type. Mimics the interface of std::vector<T> with some notable differences:
  83. /// * Uses rcAlloc()/rcFree() to handle storage.
  84. /// * No support for a custom allocator.
  85. /// * Uses signed size instead of size_t to avoid warnings in for loops: "for (int i = 0; i < foo.size(); i++)"
  86. /// * Omits methods of limited utility: insert/erase, (bad performance), at (we don't use exceptions), operator=.
  87. /// * assign() and the pre-sizing constructor follow C++11 semantics -- they don't construct a temporary if no value is provided.
  88. /// * push_back() and resize() support adding values from the current vector. Range-based constructors and assign(begin, end) do not.
  89. /// * No specialization for bool.
  90. template <typename T, rcAllocHint H>
  91. class rcVectorBase {
  92. rcSizeType m_size;
  93. rcSizeType m_cap;
  94. T* m_data;
  95. // Constructs a T at the give address with either the copy constructor or the default.
  96. static void construct(T* p, const T& v) { ::new(rcNewTag(), (void*)p) T(v); }
  97. static void construct(T* p) { ::new(rcNewTag(), (void*)p) T; }
  98. static void construct_range(T* begin, T* end);
  99. static void construct_range(T* begin, T* end, const T& value);
  100. static void copy_range(T* dst, const T* begin, const T* end);
  101. void destroy_range(rcSizeType begin, rcSizeType end);
  102. // Creates an array of the given size, copies all of this vector's data into it, and returns it.
  103. T* allocate_and_copy(rcSizeType size);
  104. void resize_impl(rcSizeType size, const T* value);
  105. // Requires: min_capacity > m_cap.
  106. rcSizeType get_new_capacity(rcSizeType min_capacity);
  107. public:
  108. typedef rcSizeType size_type;
  109. typedef T value_type;
  110. rcVectorBase() : m_size(0), m_cap(0), m_data(0) {}
  111. rcVectorBase(const rcVectorBase<T, H>& other) : m_size(0), m_cap(0), m_data(0) { assign(other.begin(), other.end()); }
  112. explicit rcVectorBase(rcSizeType count) : m_size(0), m_cap(0), m_data(0) { resize(count); }
  113. rcVectorBase(rcSizeType count, const T& value) : m_size(0), m_cap(0), m_data(0) { resize(count, value); }
  114. rcVectorBase(const T* begin, const T* end) : m_size(0), m_cap(0), m_data(0) { assign(begin, end); }
  115. ~rcVectorBase() { destroy_range(0, m_size); rcFree(m_data); }
  116. // Unlike in std::vector, we return a bool to indicate whether the alloc was successful.
  117. bool reserve(rcSizeType size);
  118. void assign(rcSizeType count, const T& value) { clear(); resize(count, value); }
  119. void assign(const T* begin, const T* end);
  120. void resize(rcSizeType size) { resize_impl(size, NULL); }
  121. void resize(rcSizeType size, const T& value) { resize_impl(size, &value); }
  122. // Not implemented as resize(0) because resize requires T to be default-constructible.
  123. void clear() { destroy_range(0, m_size); m_size = 0; }
  124. void push_back(const T& value);
  125. void pop_back() { rcAssert(m_size > 0); back().~T(); m_size--; }
  126. rcSizeType size() const { return m_size; }
  127. rcSizeType capacity() const { return m_cap; }
  128. bool empty() const { return size() == 0; }
  129. const T& operator[](rcSizeType i) const { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
  130. T& operator[](rcSizeType i) { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
  131. const T& front() const { rcAssert(m_size); return m_data[0]; }
  132. T& front() { rcAssert(m_size); return m_data[0]; }
  133. const T& back() const { rcAssert(m_size); return m_data[m_size - 1]; }
  134. T& back() { rcAssert(m_size); return m_data[m_size - 1]; }
  135. const T* data() const { return m_data; }
  136. T* data() { return m_data; }
  137. T* begin() { return m_data; }
  138. T* end() { return m_data + m_size; }
  139. const T* begin() const { return m_data; }
  140. const T* end() const { return m_data + m_size; }
  141. void swap(rcVectorBase<T, H>& other);
  142. // Explicitly deleted.
  143. rcVectorBase& operator=(const rcVectorBase<T, H>& other);
  144. };
  145. template<typename T, rcAllocHint H>
  146. bool rcVectorBase<T, H>::reserve(rcSizeType count) {
  147. if (count <= m_cap) {
  148. return true;
  149. }
  150. T* new_data = allocate_and_copy(count);
  151. if (!new_data) {
  152. return false;
  153. }
  154. destroy_range(0, m_size);
  155. rcFree(m_data);
  156. m_data = new_data;
  157. m_cap = count;
  158. return true;
  159. }
  160. template <typename T, rcAllocHint H>
  161. T* rcVectorBase<T, H>::allocate_and_copy(rcSizeType size) {
  162. rcAssert(RC_SIZE_MAX / static_cast<rcSizeType>(sizeof(T)) >= size);
  163. T* new_data = static_cast<T*>(rcAlloc(sizeof(T) * size, H));
  164. if (new_data) {
  165. copy_range(new_data, m_data, m_data + m_size);
  166. }
  167. return new_data;
  168. }
  169. template <typename T, rcAllocHint H>
  170. void rcVectorBase<T, H>::assign(const T* begin, const T* end) {
  171. clear();
  172. reserve(end - begin);
  173. m_size = end - begin;
  174. copy_range(m_data, begin, end);
  175. }
  176. template <typename T, rcAllocHint H>
  177. void rcVectorBase<T, H>::push_back(const T& value) {
  178. // rcLikely increases performance by ~50% on BM_rcVector_PushPreallocated,
  179. // and by ~2-5% on BM_rcVector_Push.
  180. if (rcLikely(m_size < m_cap)) {
  181. construct(m_data + m_size++, value);
  182. return;
  183. }
  184. const rcSizeType new_cap = get_new_capacity(m_cap + 1);
  185. T* data = allocate_and_copy(new_cap);
  186. // construct between allocate and destroy+free in case value is
  187. // in this vector.
  188. construct(data + m_size, value);
  189. destroy_range(0, m_size);
  190. m_size++;
  191. m_cap = new_cap;
  192. rcFree(m_data);
  193. m_data = data;
  194. }
  195. template <typename T, rcAllocHint H>
  196. rcSizeType rcVectorBase<T, H>::get_new_capacity(rcSizeType min_capacity) {
  197. rcAssert(min_capacity <= RC_SIZE_MAX);
  198. if (rcUnlikely(m_cap >= RC_SIZE_MAX / 2))
  199. return RC_SIZE_MAX;
  200. return 2 * m_cap > min_capacity ? 2 * m_cap : min_capacity;
  201. }
  202. template <typename T, rcAllocHint H>
  203. void rcVectorBase<T, H>::resize_impl(rcSizeType size, const T* value) {
  204. if (size < m_size) {
  205. destroy_range(size, m_size);
  206. m_size = size;
  207. } else if (size > m_size) {
  208. if (size <= m_cap) {
  209. if (value) {
  210. construct_range(m_data + m_size, m_data + size, *value);
  211. } else {
  212. construct_range(m_data + m_size, m_data + size);
  213. }
  214. m_size = size;
  215. } else {
  216. const rcSizeType new_cap = get_new_capacity(size);
  217. T* new_data = allocate_and_copy(new_cap);
  218. // We defer deconstructing/freeing old data until after constructing
  219. // new elements in case "value" is there.
  220. if (value) {
  221. construct_range(new_data + m_size, new_data + size, *value);
  222. } else {
  223. construct_range(new_data + m_size, new_data + size);
  224. }
  225. destroy_range(0, m_size);
  226. rcFree(m_data);
  227. m_data = new_data;
  228. m_cap = new_cap;
  229. m_size = size;
  230. }
  231. }
  232. }
  233. template <typename T, rcAllocHint H>
  234. void rcVectorBase<T, H>::swap(rcVectorBase<T, H>& other) {
  235. // TODO: Reorganize headers so we can use rcSwap here.
  236. rcSizeType tmp_cap = other.m_cap;
  237. rcSizeType tmp_size = other.m_size;
  238. T* tmp_data = other.m_data;
  239. other.m_cap = m_cap;
  240. other.m_size = m_size;
  241. other.m_data = m_data;
  242. m_cap = tmp_cap;
  243. m_size = tmp_size;
  244. m_data = tmp_data;
  245. }
  246. // static
  247. template <typename T, rcAllocHint H>
  248. void rcVectorBase<T, H>::construct_range(T* begin, T* end) {
  249. for (T* p = begin; p < end; p++) {
  250. construct(p);
  251. }
  252. }
  253. // static
  254. template <typename T, rcAllocHint H>
  255. void rcVectorBase<T, H>::construct_range(T* begin, T* end, const T& value) {
  256. for (T* p = begin; p < end; p++) {
  257. construct(p, value);
  258. }
  259. }
  260. // static
  261. template <typename T, rcAllocHint H>
  262. void rcVectorBase<T, H>::copy_range(T* dst, const T* begin, const T* end) {
  263. for (rcSizeType i = 0 ; i < end - begin; i++) {
  264. construct(dst + i, begin[i]);
  265. }
  266. }
  267. template <typename T, rcAllocHint H>
  268. void rcVectorBase<T, H>::destroy_range(rcSizeType begin, rcSizeType end) {
  269. for (rcSizeType i = begin; i < end; i++) {
  270. m_data[i].~T();
  271. }
  272. }
  273. template <typename T>
  274. class rcTempVector : public rcVectorBase<T, RC_ALLOC_TEMP> {
  275. typedef rcVectorBase<T, RC_ALLOC_TEMP> Base;
  276. public:
  277. rcTempVector() : Base() {}
  278. explicit rcTempVector(rcSizeType size) : Base(size) {}
  279. rcTempVector(rcSizeType size, const T& value) : Base(size, value) {}
  280. rcTempVector(const rcTempVector<T>& other) : Base(other) {}
  281. rcTempVector(const T* begin, const T* end) : Base(begin, end) {}
  282. };
  283. template <typename T>
  284. class rcPermVector : public rcVectorBase<T, RC_ALLOC_PERM> {
  285. typedef rcVectorBase<T, RC_ALLOC_PERM> Base;
  286. public:
  287. rcPermVector() : Base() {}
  288. explicit rcPermVector(rcSizeType size) : Base(size) {}
  289. rcPermVector(rcSizeType size, const T& value) : Base(size, value) {}
  290. rcPermVector(const rcPermVector<T>& other) : Base(other) {}
  291. rcPermVector(const T* begin, const T* end) : Base(begin, end) {}
  292. };
  293. /// Legacy class. Prefer rcVector<int>.
  294. class rcIntArray
  295. {
  296. rcTempVector<int> m_impl;
  297. public:
  298. rcIntArray() {}
  299. rcIntArray(int n) : m_impl(n, 0) {}
  300. void push(int item) { m_impl.push_back(item); }
  301. void resize(int size) { m_impl.resize(size); }
  302. void clear() { m_impl.clear(); }
  303. int pop()
  304. {
  305. int v = m_impl.back();
  306. m_impl.pop_back();
  307. return v;
  308. }
  309. int size() const { return static_cast<int>(m_impl.size()); }
  310. int& operator[](int index) { return m_impl[index]; }
  311. int operator[](int index) const { return m_impl[index]; }
  312. };
  313. /// A simple helper class used to delete an array when it goes out of scope.
  314. /// @note This class is rarely if ever used by the end user.
  315. template<class T> class rcScopedDelete
  316. {
  317. T* ptr;
  318. public:
  319. /// Constructs an instance with a null pointer.
  320. inline rcScopedDelete() : ptr(0) {}
  321. /// Constructs an instance with the specified pointer.
  322. /// @param[in] p An pointer to an allocated array.
  323. inline rcScopedDelete(T* p) : ptr(p) {}
  324. inline ~rcScopedDelete() { rcFree(ptr); }
  325. /// The root array pointer.
  326. /// @return The root array pointer.
  327. inline operator T*() { return ptr; }
  328. private:
  329. // Explicitly disabled copy constructor and copy assignment operator.
  330. rcScopedDelete(const rcScopedDelete&);
  331. rcScopedDelete& operator=(const rcScopedDelete&);
  332. };
  333. #endif