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
8 #ifndef SkTemplates_DEFINED
9 #define SkTemplates_DEFINED
10
11 #include "include/private/base/SkAlign.h"
12 #include "include/private/base/SkAssert.h"
13 #include "include/private/base/SkDebug.h"
14 #include "include/private/base/SkMalloc.h"
15 #include "include/private/base/SkTLogic.h"
16
17 #include <array>
18 #include <cstddef>
19 #include <cstdint>
20 #include <cstring>
21 #include <memory>
22 #include <type_traits>
23 #include <utility>
24
25
26 /** \file SkTemplates.h
27
28 This file contains light-weight template classes for type-safe and exception-safe
29 resource management.
30 */
31
32 /**
33 * Marks a local variable as known to be unused (to avoid warnings).
34 * Note that this does *not* prevent the local variable from being optimized away.
35 */
sk_ignore_unused_variable(const T &)36 template<typename T> inline void sk_ignore_unused_variable(const T&) { }
37
38 /**
39 * This is a general purpose absolute-value function.
40 * See SkAbs32 in (SkSafe32.h) for a 32-bit int specific version that asserts.
41 */
SkTAbs(T value)42 template <typename T> static inline T SkTAbs(T value) {
43 if (value < 0) {
44 value = -value;
45 }
46 return value;
47 }
48
49 /**
50 * Returns a pointer to a D which comes immediately after S[count].
51 */
52 template <typename D, typename S> inline D* SkTAfter(S* ptr, size_t count = 1) {
53 return reinterpret_cast<D*>(ptr + count);
54 }
55
56 /**
57 * Returns a pointer to a D which comes byteOffset bytes after S.
58 */
SkTAddOffset(S * ptr,ptrdiff_t byteOffset)59 template <typename D, typename S> inline D* SkTAddOffset(S* ptr, ptrdiff_t byteOffset) {
60 // The intermediate char* has the same cv-ness as D as this produces better error messages.
61 // This relies on the fact that reinterpret_cast can add constness, but cannot remove it.
62 return reinterpret_cast<D*>(reinterpret_cast<sknonstd::same_cv_t<char, D>*>(ptr) + byteOffset);
63 }
64
65 template <typename T, T* P> struct SkOverloadedFunctionObject {
66 template <typename... Args>
67 auto operator()(Args&&... args) const -> decltype(P(std::forward<Args>(args)...)) {
68 return P(std::forward<Args>(args)...);
69 }
70 };
71
72 template <auto F> using SkFunctionObject =
73 SkOverloadedFunctionObject<std::remove_pointer_t<decltype(F)>, F>;
74
75 /** \class SkAutoTCallVProc
76
77 Call a function when this goes out of scope. The template uses two
78 parameters, the object, and a function that is to be called in the destructor.
79 If release() is called, the object reference is set to null. If the object
80 reference is null when the destructor is called, we do not call the
81 function.
82 */
83 template <typename T, void (*P)(T*)> class SkAutoTCallVProc
84 : public std::unique_ptr<T, SkFunctionObject<P>> {
85 using inherited = std::unique_ptr<T, SkFunctionObject<P>>;
86 public:
87 using inherited::inherited;
88 SkAutoTCallVProc(const SkAutoTCallVProc&) = delete;
SkAutoTCallVProc(SkAutoTCallVProc && that)89 SkAutoTCallVProc(SkAutoTCallVProc&& that) : inherited(std::move(that)) {}
90
91 operator T*() const { return this->get(); }
92 };
93
94
95 namespace skia_private {
96 /** Allocate an array of T elements, and free the array in the destructor
97 */
98 template <typename T> class AutoTArray {
99 public:
AutoTArray()100 AutoTArray() {}
101 /** Allocate count number of T elements
102 */
AutoTArray(int count)103 explicit AutoTArray(int count) {
104 SkASSERT(count >= 0);
105 if (count) {
106 fArray.reset(new T[count]);
107 }
108 SkDEBUGCODE(fCount = count;)
109 }
110
AutoTArray(AutoTArray && other)111 AutoTArray(AutoTArray&& other) : fArray(std::move(other.fArray)) {
112 SkDEBUGCODE(fCount = other.fCount; other.fCount = 0;)
113 }
114 AutoTArray& operator=(AutoTArray&& other) {
115 if (this != &other) {
116 fArray = std::move(other.fArray);
117 SkDEBUGCODE(fCount = other.fCount; other.fCount = 0;)
118 }
119 return *this;
120 }
121
122 /** Reallocates given a new count. Reallocation occurs even if new count equals old count.
123 */
124 void reset(int count = 0) { *this = AutoTArray(count); }
125
126 /** Return the array of T elements. Will be NULL if count == 0
127 */
get()128 T* get() const { return fArray.get(); }
129
130 /** Return the nth element in the array
131 */
132 T& operator[](int index) const {
133 SkASSERT((unsigned)index < (unsigned)fCount);
134 return fArray[index];
135 }
136
137 /** Aliases matching other types, like std::vector. */
data()138 const T* data() const { return fArray.get(); }
data()139 T* data() { return fArray.get(); }
140
141 private:
142 std::unique_ptr<T[]> fArray;
143 SkDEBUGCODE(int fCount = 0;)
144 };
145
146 /** Wraps AutoTArray, with room for kCountRequested elements preallocated.
147 */
148 template <int kCountRequested, typename T> class AutoSTArray {
149 public:
150 AutoSTArray(AutoSTArray&&) = delete;
151 AutoSTArray(const AutoSTArray&) = delete;
152 AutoSTArray& operator=(AutoSTArray&&) = delete;
153 AutoSTArray& operator=(const AutoSTArray&) = delete;
154
155 /** Initialize with no objects */
AutoSTArray()156 AutoSTArray() {
157 fArray = nullptr;
158 fCount = 0;
159 }
160
161 /** Allocate count number of T elements
162 */
AutoSTArray(int count)163 AutoSTArray(int count) {
164 fArray = nullptr;
165 fCount = 0;
166 this->reset(count);
167 }
168
~AutoSTArray()169 ~AutoSTArray() {
170 this->reset(0);
171 }
172
173 /** Destroys previous objects in the array and default constructs count number of objects */
reset(int count)174 void reset(int count) {
175 T* start = fArray;
176 T* iter = start + fCount;
177 while (iter > start) {
178 (--iter)->~T();
179 }
180
181 SkASSERT(count >= 0);
182 if (fCount != count) {
183 if (fCount > kCount) {
184 // 'fArray' was allocated last time so free it now
185 SkASSERT((T*) fStorage != fArray);
186 sk_free(fArray);
187 }
188
189 if (count > kCount) {
190 fArray = (T*) sk_malloc_throw(count, sizeof(T));
191 } else if (count > 0) {
192 fArray = (T*) fStorage;
193 } else {
194 fArray = nullptr;
195 }
196
197 fCount = count;
198 }
199
200 iter = fArray;
201 T* stop = fArray + count;
202 while (iter < stop) {
203 new (iter++) T;
204 }
205 }
206
207 /** Return the number of T elements in the array
208 */
count()209 int count() const { return fCount; }
210
211 /** Return the array of T elements. Will be NULL if count == 0
212 */
get()213 T* get() const { return fArray; }
214
begin()215 T* begin() { return fArray; }
216
begin()217 const T* begin() const { return fArray; }
218
end()219 T* end() { return fArray + fCount; }
220
end()221 const T* end() const { return fArray + fCount; }
222
223 /** Return the nth element in the array
224 */
225 T& operator[](int index) const {
226 SkASSERT(index < fCount);
227 return fArray[index];
228 }
229
230 /** Aliases matching other types, like std::vector. */
data()231 const T* data() const { return fArray; }
data()232 T* data() { return fArray; }
size()233 size_t size() const { return fCount; }
234
235 private:
236 #if defined(SK_BUILD_FOR_GOOGLE3)
237 // Stack frame size is limited for SK_BUILD_FOR_GOOGLE3. 4k is less than the actual max,
238 // but some functions have multiple large stack allocations.
239 static const int kMaxBytes = 4 * 1024;
240 static const int kCount = kCountRequested * sizeof(T) > kMaxBytes
241 ? kMaxBytes / sizeof(T)
242 : kCountRequested;
243 #else
244 static const int kCount = kCountRequested;
245 #endif
246
247 int fCount;
248 T* fArray;
249 alignas(T) char fStorage[kCount * sizeof(T)];
250 };
251
252 /** Manages an array of T elements, freeing the array in the destructor.
253 * Does NOT call any constructors/destructors on T (T must be POD).
254 */
255 template <typename T,
256 typename = std::enable_if_t<std::is_trivially_default_constructible<T>::value &&
257 std::is_trivially_destructible<T>::value>>
258 class AutoTMalloc {
259 public:
260 /** Takes ownership of the ptr. The ptr must be a value which can be passed to sk_free. */
fPtr(ptr)261 explicit AutoTMalloc(T* ptr = nullptr) : fPtr(ptr) {}
262
263 /** Allocates space for 'count' Ts. */
AutoTMalloc(size_t count)264 explicit AutoTMalloc(size_t count)
265 : fPtr(count ? (T*)sk_malloc_throw(count, sizeof(T)) : nullptr) {}
266
267 AutoTMalloc(AutoTMalloc&&) = default;
268 AutoTMalloc& operator=(AutoTMalloc&&) = default;
269
270 /** Resize the memory area pointed to by the current ptr preserving contents. */
realloc(size_t count)271 void realloc(size_t count) {
272 fPtr.reset(count ? (T*)sk_realloc_throw(fPtr.release(), count * sizeof(T)) : nullptr);
273 }
274
275 /** Resize the memory area pointed to by the current ptr without preserving contents. */
276 T* reset(size_t count = 0) {
277 fPtr.reset(count ? (T*)sk_malloc_throw(count, sizeof(T)) : nullptr);
278 return this->get();
279 }
280
get()281 T* get() const { return fPtr.get(); }
282
283 operator T*() { return fPtr.get(); }
284
285 operator const T*() const { return fPtr.get(); }
286
287 T& operator[](int index) { return fPtr.get()[index]; }
288
289 const T& operator[](int index) const { return fPtr.get()[index]; }
290
291 /** Aliases matching other types, like std::vector. */
data()292 const T* data() const { return fPtr.get(); }
data()293 T* data() { return fPtr.get(); }
294
295 /**
296 * Transfer ownership of the ptr to the caller, setting the internal
297 * pointer to NULL. Note that this differs from get(), which also returns
298 * the pointer, but it does not transfer ownership.
299 */
release()300 T* release() { return fPtr.release(); }
301
302 private:
303 std::unique_ptr<T, SkOverloadedFunctionObject<void(void*), sk_free>> fPtr;
304 };
305
306 template <size_t kCountRequested,
307 typename T,
308 typename = std::enable_if_t<std::is_trivially_default_constructible<T>::value &&
309 std::is_trivially_destructible<T>::value>>
310 class AutoSTMalloc {
311 public:
AutoSTMalloc()312 AutoSTMalloc() : fPtr(fTStorage) {}
313
AutoSTMalloc(size_t count)314 AutoSTMalloc(size_t count) {
315 if (count > kCount) {
316 fPtr = (T*)sk_malloc_throw(count, sizeof(T));
317 } else if (count) {
318 fPtr = fTStorage;
319 } else {
320 fPtr = nullptr;
321 }
322 }
323
324 AutoSTMalloc(AutoSTMalloc&&) = delete;
325 AutoSTMalloc(const AutoSTMalloc&) = delete;
326 AutoSTMalloc& operator=(AutoSTMalloc&&) = delete;
327 AutoSTMalloc& operator=(const AutoSTMalloc&) = delete;
328
~AutoSTMalloc()329 ~AutoSTMalloc() {
330 if (fPtr != fTStorage) {
331 sk_free(fPtr);
332 }
333 }
334
335 // doesn't preserve contents
reset(size_t count)336 T* reset(size_t count) {
337 if (fPtr != fTStorage) {
338 sk_free(fPtr);
339 }
340 if (count > kCount) {
341 fPtr = (T*)sk_malloc_throw(count, sizeof(T));
342 } else if (count) {
343 fPtr = fTStorage;
344 } else {
345 fPtr = nullptr;
346 }
347 return fPtr;
348 }
349
get()350 T* get() const { return fPtr; }
351
352 operator T*() {
353 return fPtr;
354 }
355
356 operator const T*() const {
357 return fPtr;
358 }
359
360 T& operator[](int index) {
361 return fPtr[index];
362 }
363
364 const T& operator[](int index) const {
365 return fPtr[index];
366 }
367
368 /** Aliases matching other types, like std::vector. */
data()369 const T* data() const { return fPtr; }
data()370 T* data() { return fPtr; }
371
372 // Reallocs the array, can be used to shrink the allocation. Makes no attempt to be intelligent
realloc(size_t count)373 void realloc(size_t count) {
374 if (count > kCount) {
375 if (fPtr == fTStorage) {
376 fPtr = (T*)sk_malloc_throw(count, sizeof(T));
377 memcpy((void*)fPtr, fTStorage, kCount * sizeof(T));
378 } else {
379 fPtr = (T*)sk_realloc_throw(fPtr, count, sizeof(T));
380 }
381 } else if (count) {
382 if (fPtr != fTStorage) {
383 fPtr = (T*)sk_realloc_throw(fPtr, count, sizeof(T));
384 }
385 } else {
386 this->reset(0);
387 }
388 }
389
390 private:
391 // Since we use uint32_t storage, we might be able to get more elements for free.
392 static const size_t kCountWithPadding = SkAlign4(kCountRequested*sizeof(T)) / sizeof(T);
393 #if defined(SK_BUILD_FOR_GOOGLE3)
394 // Stack frame size is limited for SK_BUILD_FOR_GOOGLE3. 4k is less than the actual max, but some functions
395 // have multiple large stack allocations.
396 static const size_t kMaxBytes = 4 * 1024;
397 static const size_t kCount = kCountRequested * sizeof(T) > kMaxBytes
398 ? kMaxBytes / sizeof(T)
399 : kCountWithPadding;
400 #else
401 static const size_t kCount = kCountWithPadding;
402 #endif
403
404 T* fPtr;
405 union {
406 uint32_t fStorage32[SkAlign4(kCount*sizeof(T)) >> 2];
407 T fTStorage[1]; // do NOT want to invoke T::T()
408 };
409 };
410
411 using UniqueVoidPtr = std::unique_ptr<void, SkOverloadedFunctionObject<void(void*), sk_free>>;
412
413 } // namespace skia_private
414
415 template<typename C, std::size_t... Is>
416 constexpr auto SkMakeArrayFromIndexSequence(C c, std::index_sequence<Is...> is)
417 -> std::array<decltype(c(std::declval<typename decltype(is)::value_type>())), sizeof...(Is)> {
418 return {{ c(Is)... }};
419 }
420
421 template<size_t N, typename C> constexpr auto SkMakeArray(C c)
422 -> std::array<decltype(c(std::declval<typename std::index_sequence<N>::value_type>())), N> {
423 return SkMakeArrayFromIndexSequence(c, std::make_index_sequence<N>{});
424 }
425
426 #endif
427