SkTemplates.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright 2006 The Android Open Source Project
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SkTemplates_DEFINED
  8. #define SkTemplates_DEFINED
  9. #include "include/core/SkTypes.h"
  10. #include "include/private/SkMalloc.h"
  11. #include "include/private/SkTLogic.h"
  12. #include <string.h>
  13. #include <array>
  14. #include <cstddef>
  15. #include <memory>
  16. #include <new>
  17. #include <utility>
  18. /** \file SkTemplates.h
  19. This file contains light-weight template classes for type-safe and exception-safe
  20. resource management.
  21. */
  22. /**
  23. * Marks a local variable as known to be unused (to avoid warnings).
  24. * Note that this does *not* prevent the local variable from being optimized away.
  25. */
  26. template<typename T> inline void sk_ignore_unused_variable(const T&) { }
  27. /**
  28. * Returns a pointer to a D which comes immediately after S[count].
  29. */
  30. template <typename D, typename S> static D* SkTAfter(S* ptr, size_t count = 1) {
  31. return reinterpret_cast<D*>(ptr + count);
  32. }
  33. /**
  34. * Returns a pointer to a D which comes byteOffset bytes after S.
  35. */
  36. template <typename D, typename S> static D* SkTAddOffset(S* ptr, size_t byteOffset) {
  37. // The intermediate char* has the same cv-ness as D as this produces better error messages.
  38. // This relies on the fact that reinterpret_cast can add constness, but cannot remove it.
  39. return reinterpret_cast<D*>(reinterpret_cast<sknonstd::same_cv_t<char, D>*>(ptr) + byteOffset);
  40. }
  41. template <typename R, typename T, R (*P)(T*)> struct SkFunctionWrapper {
  42. R operator()(T* t) { return P(t); }
  43. };
  44. /** \class SkAutoTCallVProc
  45. Call a function when this goes out of scope. The template uses two
  46. parameters, the object, and a function that is to be called in the destructor.
  47. If release() is called, the object reference is set to null. If the object
  48. reference is null when the destructor is called, we do not call the
  49. function.
  50. */
  51. template <typename T, void (*P)(T*)> class SkAutoTCallVProc
  52. : public std::unique_ptr<T, SkFunctionWrapper<void, T, P>> {
  53. public:
  54. SkAutoTCallVProc(T* obj): std::unique_ptr<T, SkFunctionWrapper<void, T, P>>(obj) {}
  55. operator T*() const { return this->get(); }
  56. };
  57. /** Allocate an array of T elements, and free the array in the destructor
  58. */
  59. template <typename T> class SkAutoTArray {
  60. public:
  61. SkAutoTArray() {}
  62. /** Allocate count number of T elements
  63. */
  64. explicit SkAutoTArray(int count) {
  65. SkASSERT(count >= 0);
  66. if (count) {
  67. fArray.reset(new T[count]);
  68. }
  69. SkDEBUGCODE(fCount = count;)
  70. }
  71. SkAutoTArray(SkAutoTArray&& other) : fArray(std::move(other.fArray)) {
  72. SkDEBUGCODE(fCount = other.fCount; other.fCount = 0;)
  73. }
  74. SkAutoTArray& operator=(SkAutoTArray&& other) {
  75. if (this != &other) {
  76. fArray = std::move(other.fArray);
  77. SkDEBUGCODE(fCount = other.fCount; other.fCount = 0;)
  78. }
  79. return *this;
  80. }
  81. /** Reallocates given a new count. Reallocation occurs even if new count equals old count.
  82. */
  83. void reset(int count) { *this = SkAutoTArray(count); }
  84. /** Return the array of T elements. Will be NULL if count == 0
  85. */
  86. T* get() const { return fArray.get(); }
  87. /** Return the nth element in the array
  88. */
  89. T& operator[](int index) const {
  90. SkASSERT((unsigned)index < (unsigned)fCount);
  91. return fArray[index];
  92. }
  93. private:
  94. std::unique_ptr<T[]> fArray;
  95. SkDEBUGCODE(int fCount = 0;)
  96. };
  97. /** Wraps SkAutoTArray, with room for kCountRequested elements preallocated.
  98. */
  99. template <int kCountRequested, typename T> class SkAutoSTArray {
  100. public:
  101. SkAutoSTArray(SkAutoSTArray&&) = delete;
  102. SkAutoSTArray(const SkAutoSTArray&) = delete;
  103. SkAutoSTArray& operator=(SkAutoSTArray&&) = delete;
  104. SkAutoSTArray& operator=(const SkAutoSTArray&) = delete;
  105. /** Initialize with no objects */
  106. SkAutoSTArray() {
  107. fArray = nullptr;
  108. fCount = 0;
  109. }
  110. /** Allocate count number of T elements
  111. */
  112. SkAutoSTArray(int count) {
  113. fArray = nullptr;
  114. fCount = 0;
  115. this->reset(count);
  116. }
  117. ~SkAutoSTArray() {
  118. this->reset(0);
  119. }
  120. /** Destroys previous objects in the array and default constructs count number of objects */
  121. void reset(int count) {
  122. T* start = fArray;
  123. T* iter = start + fCount;
  124. while (iter > start) {
  125. (--iter)->~T();
  126. }
  127. SkASSERT(count >= 0);
  128. if (fCount != count) {
  129. if (fCount > kCount) {
  130. // 'fArray' was allocated last time so free it now
  131. SkASSERT((T*) fStorage != fArray);
  132. sk_free(fArray);
  133. }
  134. if (count > kCount) {
  135. fArray = (T*) sk_malloc_throw(count, sizeof(T));
  136. } else if (count > 0) {
  137. fArray = (T*) fStorage;
  138. } else {
  139. fArray = nullptr;
  140. }
  141. fCount = count;
  142. }
  143. iter = fArray;
  144. T* stop = fArray + count;
  145. while (iter < stop) {
  146. new (iter++) T;
  147. }
  148. }
  149. /** Return the number of T elements in the array
  150. */
  151. int count() const { return fCount; }
  152. /** Return the array of T elements. Will be NULL if count == 0
  153. */
  154. T* get() const { return fArray; }
  155. T* begin() { return fArray; }
  156. const T* begin() const { return fArray; }
  157. T* end() { return fArray + fCount; }
  158. const T* end() const { return fArray + fCount; }
  159. /** Return the nth element in the array
  160. */
  161. T& operator[](int index) const {
  162. SkASSERT(index < fCount);
  163. return fArray[index];
  164. }
  165. private:
  166. #if defined(SK_BUILD_FOR_GOOGLE3)
  167. // Stack frame size is limited for SK_BUILD_FOR_GOOGLE3. 4k is less than the actual max, but some functions
  168. // have multiple large stack allocations.
  169. static const int kMaxBytes = 4 * 1024;
  170. static const int kCount = kCountRequested * sizeof(T) > kMaxBytes
  171. ? kMaxBytes / sizeof(T)
  172. : kCountRequested;
  173. #else
  174. static const int kCount = kCountRequested;
  175. #endif
  176. int fCount;
  177. T* fArray;
  178. // since we come right after fArray, fStorage should be properly aligned
  179. char fStorage[kCount * sizeof(T)];
  180. };
  181. /** Manages an array of T elements, freeing the array in the destructor.
  182. * Does NOT call any constructors/destructors on T (T must be POD).
  183. */
  184. template <typename T> class SkAutoTMalloc {
  185. public:
  186. /** Takes ownership of the ptr. The ptr must be a value which can be passed to sk_free. */
  187. explicit SkAutoTMalloc(T* ptr = nullptr) : fPtr(ptr) {}
  188. /** Allocates space for 'count' Ts. */
  189. explicit SkAutoTMalloc(size_t count)
  190. : fPtr(count ? (T*)sk_malloc_throw(count, sizeof(T)) : nullptr) {}
  191. SkAutoTMalloc(SkAutoTMalloc&&) = default;
  192. SkAutoTMalloc& operator=(SkAutoTMalloc&&) = default;
  193. /** Resize the memory area pointed to by the current ptr preserving contents. */
  194. void realloc(size_t count) {
  195. fPtr.reset(count ? (T*)sk_realloc_throw(fPtr.release(), count * sizeof(T)) : nullptr);
  196. }
  197. /** Resize the memory area pointed to by the current ptr without preserving contents. */
  198. T* reset(size_t count = 0) {
  199. fPtr.reset(count ? (T*)sk_malloc_throw(count, sizeof(T)) : nullptr);
  200. return this->get();
  201. }
  202. T* get() const { return fPtr.get(); }
  203. operator T*() { return fPtr.get(); }
  204. operator const T*() const { return fPtr.get(); }
  205. T& operator[](int index) { return fPtr.get()[index]; }
  206. const T& operator[](int index) const { return fPtr.get()[index]; }
  207. /**
  208. * Transfer ownership of the ptr to the caller, setting the internal
  209. * pointer to NULL. Note that this differs from get(), which also returns
  210. * the pointer, but it does not transfer ownership.
  211. */
  212. T* release() { return fPtr.release(); }
  213. private:
  214. std::unique_ptr<T, SkFunctionWrapper<void, void, sk_free>> fPtr;
  215. };
  216. template <size_t kCountRequested, typename T> class SkAutoSTMalloc {
  217. public:
  218. SkAutoSTMalloc() : fPtr(fTStorage) {}
  219. SkAutoSTMalloc(size_t count) {
  220. if (count > kCount) {
  221. fPtr = (T*)sk_malloc_throw(count, sizeof(T));
  222. } else if (count) {
  223. fPtr = fTStorage;
  224. } else {
  225. fPtr = nullptr;
  226. }
  227. }
  228. SkAutoSTMalloc(SkAutoSTMalloc&&) = delete;
  229. SkAutoSTMalloc(const SkAutoSTMalloc&) = delete;
  230. SkAutoSTMalloc& operator=(SkAutoSTMalloc&&) = delete;
  231. SkAutoSTMalloc& operator=(const SkAutoSTMalloc&) = delete;
  232. ~SkAutoSTMalloc() {
  233. if (fPtr != fTStorage) {
  234. sk_free(fPtr);
  235. }
  236. }
  237. // doesn't preserve contents
  238. T* reset(size_t count) {
  239. if (fPtr != fTStorage) {
  240. sk_free(fPtr);
  241. }
  242. if (count > kCount) {
  243. fPtr = (T*)sk_malloc_throw(count, sizeof(T));
  244. } else if (count) {
  245. fPtr = fTStorage;
  246. } else {
  247. fPtr = nullptr;
  248. }
  249. return fPtr;
  250. }
  251. T* get() const { return fPtr; }
  252. operator T*() {
  253. return fPtr;
  254. }
  255. operator const T*() const {
  256. return fPtr;
  257. }
  258. T& operator[](int index) {
  259. return fPtr[index];
  260. }
  261. const T& operator[](int index) const {
  262. return fPtr[index];
  263. }
  264. // Reallocs the array, can be used to shrink the allocation. Makes no attempt to be intelligent
  265. void realloc(size_t count) {
  266. if (count > kCount) {
  267. if (fPtr == fTStorage) {
  268. fPtr = (T*)sk_malloc_throw(count, sizeof(T));
  269. memcpy(fPtr, fTStorage, kCount * sizeof(T));
  270. } else {
  271. fPtr = (T*)sk_realloc_throw(fPtr, count, sizeof(T));
  272. }
  273. } else if (count) {
  274. if (fPtr != fTStorage) {
  275. fPtr = (T*)sk_realloc_throw(fPtr, count, sizeof(T));
  276. }
  277. } else {
  278. this->reset(0);
  279. }
  280. }
  281. private:
  282. // Since we use uint32_t storage, we might be able to get more elements for free.
  283. static const size_t kCountWithPadding = SkAlign4(kCountRequested*sizeof(T)) / sizeof(T);
  284. #if defined(SK_BUILD_FOR_GOOGLE3)
  285. // Stack frame size is limited for SK_BUILD_FOR_GOOGLE3. 4k is less than the actual max, but some functions
  286. // have multiple large stack allocations.
  287. static const size_t kMaxBytes = 4 * 1024;
  288. static const size_t kCount = kCountRequested * sizeof(T) > kMaxBytes
  289. ? kMaxBytes / sizeof(T)
  290. : kCountWithPadding;
  291. #else
  292. static const size_t kCount = kCountWithPadding;
  293. #endif
  294. T* fPtr;
  295. union {
  296. uint32_t fStorage32[SkAlign4(kCount*sizeof(T)) >> 2];
  297. T fTStorage[1]; // do NOT want to invoke T::T()
  298. };
  299. };
  300. //////////////////////////////////////////////////////////////////////////////////////////////////
  301. /**
  302. * Pass the object and the storage that was offered during SkInPlaceNewCheck, and this will
  303. * safely destroy (and free if it was dynamically allocated) the object.
  304. */
  305. template <typename T> void SkInPlaceDeleteCheck(T* obj, void* storage) {
  306. if (storage == obj) {
  307. obj->~T();
  308. } else {
  309. delete obj;
  310. }
  311. }
  312. /**
  313. * Allocates T, using storage if it is large enough, and allocating on the heap (via new) if
  314. * storage is not large enough.
  315. *
  316. * obj = SkInPlaceNewCheck<Type>(storage, size);
  317. * ...
  318. * SkInPlaceDeleteCheck(obj, storage);
  319. */
  320. template<typename T, typename... Args>
  321. T* SkInPlaceNewCheck(void* storage, size_t size, Args&&... args) {
  322. return (sizeof(T) <= size) ? new (storage) T(std::forward<Args>(args)...)
  323. : new T(std::forward<Args>(args)...);
  324. }
  325. /**
  326. * Reserves memory that is aligned on double and pointer boundaries.
  327. * Hopefully this is sufficient for all practical purposes.
  328. */
  329. template <size_t N> class SkAlignedSStorage {
  330. public:
  331. SkAlignedSStorage() {}
  332. SkAlignedSStorage(SkAlignedSStorage&&) = delete;
  333. SkAlignedSStorage(const SkAlignedSStorage&) = delete;
  334. SkAlignedSStorage& operator=(SkAlignedSStorage&&) = delete;
  335. SkAlignedSStorage& operator=(const SkAlignedSStorage&) = delete;
  336. size_t size() const { return N; }
  337. void* get() { return fData; }
  338. const void* get() const { return fData; }
  339. private:
  340. union {
  341. void* fPtr;
  342. double fDouble;
  343. char fData[N];
  344. };
  345. };
  346. /**
  347. * Reserves memory that is aligned on double and pointer boundaries.
  348. * Hopefully this is sufficient for all practical purposes. Otherwise,
  349. * we have to do some arcane trickery to determine alignment of non-POD
  350. * types. Lifetime of the memory is the lifetime of the object.
  351. */
  352. template <int N, typename T> class SkAlignedSTStorage {
  353. public:
  354. SkAlignedSTStorage() {}
  355. SkAlignedSTStorage(SkAlignedSTStorage&&) = delete;
  356. SkAlignedSTStorage(const SkAlignedSTStorage&) = delete;
  357. SkAlignedSTStorage& operator=(SkAlignedSTStorage&&) = delete;
  358. SkAlignedSTStorage& operator=(const SkAlignedSTStorage&) = delete;
  359. /**
  360. * Returns void* because this object does not initialize the
  361. * memory. Use placement new for types that require a cons.
  362. */
  363. void* get() { return fStorage.get(); }
  364. const void* get() const { return fStorage.get(); }
  365. private:
  366. SkAlignedSStorage<sizeof(T)*N> fStorage;
  367. };
  368. using SkAutoFree = std::unique_ptr<void, SkFunctionWrapper<void, void, sk_free>>;
  369. template<typename C, std::size_t... Is>
  370. constexpr auto SkMakeArrayFromIndexSequence(C c, skstd::index_sequence<Is...>)
  371. -> std::array<skstd::result_of_t<C(std::size_t)>, sizeof...(Is)> {
  372. return {{ c(Is)... }};
  373. }
  374. template<size_t N, typename C> constexpr auto SkMakeArray(C c)
  375. -> std::array<skstd::result_of_t<C(std::size_t)>, N> {
  376. return SkMakeArrayFromIndexSequence(c, skstd::make_index_sequence<N>{});
  377. }
  378. #endif