RecastAlloc.h 12 KB

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