Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / include / core / SkTypes.h
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 SkTypes_DEFINED
9 #define SkTypes_DEFINED
10
11 #include "SkPreConfig.h"
12 #include "SkUserConfig.h"
13 #include "SkPostConfig.h"
14 #include <stdint.h>
15
16 /** \file SkTypes.h
17 */
18
19 /** See SkGraphics::GetVersion() to retrieve these at runtime
20  */
21 #define SKIA_VERSION_MAJOR  1
22 #define SKIA_VERSION_MINOR  0
23 #define SKIA_VERSION_PATCH  0
24
25 /*
26     memory wrappers to be implemented by the porting layer (platform)
27 */
28
29 /** Called internally if we run out of memory. The platform implementation must
30     not return, but should either throw an exception or otherwise exit.
31 */
32 SK_API extern void sk_out_of_memory(void);
33 /** Called internally if we hit an unrecoverable error.
34     The platform implementation must not return, but should either throw
35     an exception or otherwise exit.
36 */
37 SK_API extern void sk_throw(void);
38
39 enum {
40     SK_MALLOC_TEMP  = 0x01, //!< hint to sk_malloc that the requested memory will be freed in the scope of the stack frame
41     SK_MALLOC_THROW = 0x02  //!< instructs sk_malloc to call sk_throw if the memory cannot be allocated.
42 };
43 /** Return a block of memory (at least 4-byte aligned) of at least the
44     specified size. If the requested memory cannot be returned, either
45     return null (if SK_MALLOC_TEMP bit is clear) or throw an exception
46     (if SK_MALLOC_TEMP bit is set). To free the memory, call sk_free().
47 */
48 SK_API extern void* sk_malloc_flags(size_t size, unsigned flags);
49 /** Same as sk_malloc(), but hard coded to pass SK_MALLOC_THROW as the flag
50 */
51 SK_API extern void* sk_malloc_throw(size_t size);
52 /** Same as standard realloc(), but this one never returns null on failure. It will throw
53     an exception if it fails.
54 */
55 SK_API extern void* sk_realloc_throw(void* buffer, size_t size);
56 /** Free memory returned by sk_malloc(). It is safe to pass null.
57 */
58 SK_API extern void sk_free(void*);
59
60 /** Much like calloc: returns a pointer to at least size zero bytes, or NULL on failure.
61  */
62 SK_API extern void* sk_calloc(size_t size);
63
64 /** Same as sk_calloc, but throws an exception instead of returning NULL on failure.
65  */
66 SK_API extern void* sk_calloc_throw(size_t size);
67
68 // bzero is safer than memset, but we can't rely on it, so... sk_bzero()
69 static inline void sk_bzero(void* buffer, size_t size) {
70     memset(buffer, 0, size);
71 }
72
73 ///////////////////////////////////////////////////////////////////////////////
74
75 #ifdef SK_OVERRIDE_GLOBAL_NEW
76 #include <new>
77
78 inline void* operator new(size_t size) {
79     return sk_malloc_throw(size);
80 }
81
82 inline void operator delete(void* p) {
83     sk_free(p);
84 }
85 #endif
86
87 ///////////////////////////////////////////////////////////////////////////////
88
89 #define SK_INIT_TO_AVOID_WARNING    = 0
90
91 #ifndef SkDebugf
92     void SkDebugf(const char format[], ...);
93 #endif
94
95 #ifdef SK_DEBUG
96     #define SkASSERT(cond)              SK_DEBUGBREAK(cond)
97     #define SkDEBUGFAIL(message)        SkASSERT(false && message)
98     #define SkDEBUGCODE(code)           code
99     #define SkDECLAREPARAM(type, var)   , type var
100     #define SkPARAM(var)                , var
101 //  #define SkDEBUGF(args       )       SkDebugf##args
102     #define SkDEBUGF(args       )       SkDebugf args
103     #define SkAssertResult(cond)        SkASSERT(cond)
104 #else
105     #define SkASSERT(cond)
106     #define SkDEBUGFAIL(message)
107     #define SkDEBUGCODE(code)
108     #define SkDEBUGF(args)
109     #define SkDECLAREPARAM(type, var)
110     #define SkPARAM(var)
111
112     // unlike SkASSERT, this guy executes its condition in the non-debug build
113     #define SkAssertResult(cond)        cond
114 #endif
115
116 #ifdef SK_DEVELOPER
117     #define SkDEVCODE(code)             code
118     // the 'toString' helper functions convert Sk* objects to human-readable
119     // form in developer mode
120     #define SK_DEVELOPER_TO_STRING()    virtual void toString(SkString* str) const SK_OVERRIDE;
121 #else
122     #define SkDEVCODE(code)
123     #define SK_DEVELOPER_TO_STRING()
124 #endif
125
126 template <bool>
127 struct SkCompileAssert {
128 };
129
130 #define SK_COMPILE_ASSERT(expr, msg) \
131     typedef SkCompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] SK_UNUSED
132
133 /*
134  *  Usage:  SK_MACRO_CONCAT(a, b)   to construct the symbol ab
135  *
136  *  SK_MACRO_CONCAT_IMPL_PRIV just exists to make this work. Do not use directly
137  *
138  */
139 #define SK_MACRO_CONCAT(X, Y)           SK_MACRO_CONCAT_IMPL_PRIV(X, Y)
140 #define SK_MACRO_CONCAT_IMPL_PRIV(X, Y)  X ## Y
141
142 /*
143  *  Usage: SK_MACRO_APPEND_LINE(foo)    to make foo123, where 123 is the current
144  *                                      line number. Easy way to construct
145  *                                      unique names for local functions or
146  *                                      variables.
147  */
148 #define SK_MACRO_APPEND_LINE(name)  SK_MACRO_CONCAT(name, __LINE__)
149
150 /**
151  * For some classes, it's almost always an error to instantiate one without a name, e.g.
152  *   {
153  *       SkAutoMutexAcquire(&mutex);
154  *       <some code>
155  *   }
156  * In this case, the writer meant to hold mutex while the rest of the code in the block runs,
157  * but instead the mutex is acquired and then immediately released.  The correct usage is
158  *   {
159  *       SkAutoMutexAcquire lock(&mutex);
160  *       <some code>
161  *   }
162  *
163  * To prevent callers from instantiating your class without a name, use SK_REQUIRE_LOCAL_VAR
164  * like this:
165  *   class classname {
166  *       <your class>
167  *   };
168  *   #define classname(...) SK_REQUIRE_LOCAL_VAR(classname)
169  *
170  * This won't work with templates, and you must inline the class' constructors and destructors.
171  * Take a look at SkAutoFree and SkAutoMalloc in this file for examples.
172  */
173 #define SK_REQUIRE_LOCAL_VAR(classname) \
174     SK_COMPILE_ASSERT(false, missing_name_for_##classname)
175
176 ///////////////////////////////////////////////////////////////////////
177
178 /**
179  *  Fast type for signed 8 bits. Use for parameter passing and local variables,
180  *  not for storage.
181  */
182 typedef int S8CPU;
183
184 /**
185  *  Fast type for unsigned 8 bits. Use for parameter passing and local
186  *  variables, not for storage
187  */
188 typedef unsigned U8CPU;
189
190 /**
191  *  Fast type for signed 16 bits. Use for parameter passing and local variables,
192  *  not for storage
193  */
194 typedef int S16CPU;
195
196 /**
197  *  Fast type for unsigned 16 bits. Use for parameter passing and local
198  *  variables, not for storage
199  */
200 typedef unsigned U16CPU;
201
202 /**
203  *  Meant to be faster than bool (doesn't promise to be 0 or 1,
204  *  just 0 or non-zero
205  */
206 typedef int SkBool;
207
208 /**
209  *  Meant to be a small version of bool, for storage purposes. Will be 0 or 1
210  */
211 typedef uint8_t SkBool8;
212
213 #ifdef SK_DEBUG
214     SK_API int8_t      SkToS8(intmax_t);
215     SK_API uint8_t     SkToU8(uintmax_t);
216     SK_API int16_t     SkToS16(intmax_t);
217     SK_API uint16_t    SkToU16(uintmax_t);
218     SK_API int32_t     SkToS32(intmax_t);
219     SK_API uint32_t    SkToU32(uintmax_t);
220     SK_API int         SkToInt(intmax_t);
221     SK_API unsigned    SkToUInt(uintmax_t);
222 #else
223     #define SkToS8(x)   ((int8_t)(x))
224     #define SkToU8(x)   ((uint8_t)(x))
225     #define SkToS16(x)  ((int16_t)(x))
226     #define SkToU16(x)  ((uint16_t)(x))
227     #define SkToS32(x)  ((int32_t)(x))
228     #define SkToU32(x)  ((uint32_t)(x))
229     #define SkToInt(x)  ((int)(x))
230     #define SkToUInt(x) ((unsigned)(x))
231 #endif
232
233 /** Returns 0 or 1 based on the condition
234 */
235 #define SkToBool(cond)  ((cond) != 0)
236
237 #define SK_MaxS16   32767
238 #define SK_MinS16   -32767
239 #define SK_MaxU16   0xFFFF
240 #define SK_MinU16   0
241 #define SK_MaxS32   0x7FFFFFFF
242 #define SK_MinS32   -SK_MaxS32
243 #define SK_MaxU32   0xFFFFFFFF
244 #define SK_MinU32   0
245 #define SK_NaN32    (1 << 31)
246
247 /** Returns true if the value can be represented with signed 16bits
248  */
249 static inline bool SkIsS16(long x) {
250     return (int16_t)x == x;
251 }
252
253 /** Returns true if the value can be represented with unsigned 16bits
254  */
255 static inline bool SkIsU16(long x) {
256     return (uint16_t)x == x;
257 }
258
259 //////////////////////////////////////////////////////////////////////////////
260 #ifndef SK_OFFSETOF
261     #define SK_OFFSETOF(type, field)    (size_t)((char*)&(((type*)1)->field) - (char*)1)
262 #endif
263
264 /** Returns the number of entries in an array (not a pointer)
265 */
266 #define SK_ARRAY_COUNT(array)       (sizeof(array) / sizeof(array[0]))
267
268 #define SkAlign2(x)     (((x) + 1) >> 1 << 1)
269 #define SkIsAlign2(x)   (0 == ((x) & 1))
270
271 #define SkAlign4(x)     (((x) + 3) >> 2 << 2)
272 #define SkIsAlign4(x)   (0 == ((x) & 3))
273
274 #define SkAlign8(x)     (((x) + 7) >> 3 << 3)
275 #define SkIsAlign8(x)   (0 == ((x) & 7))
276
277 typedef uint32_t SkFourByteTag;
278 #define SkSetFourByteTag(a, b, c, d)    (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
279
280 /** 32 bit integer to hold a unicode value
281 */
282 typedef int32_t SkUnichar;
283 /** 32 bit value to hold a millisecond count
284 */
285 typedef uint32_t SkMSec;
286 /** 1 second measured in milliseconds
287 */
288 #define SK_MSec1 1000
289 /** maximum representable milliseconds
290 */
291 #define SK_MSecMax 0x7FFFFFFF
292 /** Returns a < b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
293 */
294 #define SkMSec_LT(a, b)     ((int32_t)(a) - (int32_t)(b) < 0)
295 /** Returns a <= b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
296 */
297 #define SkMSec_LE(a, b)     ((int32_t)(a) - (int32_t)(b) <= 0)
298
299 /****************************************************************************
300     The rest of these only build with C++
301 */
302 #ifdef __cplusplus
303
304 /** Faster than SkToBool for integral conditions. Returns 0 or 1
305 */
306 static inline int Sk32ToBool(uint32_t n) {
307     return (n | (0-n)) >> 31;
308 }
309
310 /** Generic swap function. Classes with efficient swaps should specialize this function to take
311     their fast path. This function is used by SkTSort. */
312 template <typename T> inline void SkTSwap(T& a, T& b) {
313     T c(a);
314     a = b;
315     b = c;
316 }
317
318 static inline int32_t SkAbs32(int32_t value) {
319     if (value < 0) {
320         value = -value;
321     }
322     return value;
323 }
324
325 template <typename T> inline T SkTAbs(T value) {
326     if (value < 0) {
327         value = -value;
328     }
329     return value;
330 }
331
332 static inline int32_t SkMax32(int32_t a, int32_t b) {
333     if (a < b)
334         a = b;
335     return a;
336 }
337
338 static inline int32_t SkMin32(int32_t a, int32_t b) {
339     if (a > b)
340         a = b;
341     return a;
342 }
343
344 template <typename T> const T& SkTMin(const T& a, const T& b) {
345     return (a < b) ? a : b;
346 }
347
348 template <typename T> const T& SkTMax(const T& a, const T& b) {
349     return (b < a) ? a : b;
350 }
351
352 static inline int32_t SkSign32(int32_t a) {
353     return (a >> 31) | ((unsigned) -a >> 31);
354 }
355
356 static inline int32_t SkFastMin32(int32_t value, int32_t max) {
357     if (value > max) {
358         value = max;
359     }
360     return value;
361 }
362
363 /** Returns signed 32 bit value pinned between min and max, inclusively
364 */
365 static inline int32_t SkPin32(int32_t value, int32_t min, int32_t max) {
366     if (value < min) {
367         value = min;
368     }
369     if (value > max) {
370         value = max;
371     }
372     return value;
373 }
374
375 static inline uint32_t SkSetClearShift(uint32_t bits, bool cond,
376                                        unsigned shift) {
377     SkASSERT((int)cond == 0 || (int)cond == 1);
378     return (bits & ~(1 << shift)) | ((int)cond << shift);
379 }
380
381 static inline uint32_t SkSetClearMask(uint32_t bits, bool cond,
382                                       uint32_t mask) {
383     return cond ? bits | mask : bits & ~mask;
384 }
385
386 ///////////////////////////////////////////////////////////////////////////////
387
388 /** Use to combine multiple bits in a bitmask in a type safe way.
389  */
390 template <typename T>
391 T SkTBitOr(T a, T b) {
392     return (T)(a | b);
393 }
394
395 /**
396  *  Use to cast a pointer to a different type, and maintaining strict-aliasing
397  */
398 template <typename Dst> Dst SkTCast(const void* ptr) {
399     union {
400         const void* src;
401         Dst dst;
402     } data;
403     data.src = ptr;
404     return data.dst;
405 }
406
407 //////////////////////////////////////////////////////////////////////////////
408
409 /** \class SkNoncopyable
410
411 SkNoncopyable is the base class for objects that may do not want to
412 be copied. It hides its copy-constructor and its assignment-operator.
413 */
414 class SK_API SkNoncopyable {
415 public:
416     SkNoncopyable() {}
417
418 private:
419     SkNoncopyable(const SkNoncopyable&);
420     SkNoncopyable& operator=(const SkNoncopyable&);
421 };
422
423 class SkAutoFree : SkNoncopyable {
424 public:
425     SkAutoFree() : fPtr(NULL) {}
426     explicit SkAutoFree(void* ptr) : fPtr(ptr) {}
427     ~SkAutoFree() { sk_free(fPtr); }
428
429     /** Return the currently allocate buffer, or null
430     */
431     void* get() const { return fPtr; }
432
433     /** Assign a new ptr allocated with sk_malloc (or null), and return the
434         previous ptr. Note it is the caller's responsibility to sk_free the
435         returned ptr.
436     */
437     void* set(void* ptr) {
438         void* prev = fPtr;
439         fPtr = ptr;
440         return prev;
441     }
442
443     /** Transfer ownership of the current ptr to the caller, setting the
444         internal reference to null. Note the caller is reponsible for calling
445         sk_free on the returned address.
446     */
447     void* detach() { return this->set(NULL); }
448
449     /** Free the current buffer, and set the internal reference to NULL. Same
450         as calling sk_free(detach())
451     */
452     void free() {
453         sk_free(fPtr);
454         fPtr = NULL;
455     }
456
457 private:
458     void* fPtr;
459     // illegal
460     SkAutoFree(const SkAutoFree&);
461     SkAutoFree& operator=(const SkAutoFree&);
462 };
463 #define SkAutoFree(...) SK_REQUIRE_LOCAL_VAR(SkAutoFree)
464
465 /**
466  *  Manage an allocated block of heap memory. This object is the sole manager of
467  *  the lifetime of the block, so the caller must not call sk_free() or delete
468  *  on the block, unless detach() was called.
469  */
470 class SkAutoMalloc : public SkNoncopyable {
471 public:
472     explicit SkAutoMalloc(size_t size = 0) {
473         fPtr = size ? sk_malloc_throw(size) : NULL;
474         fSize = size;
475     }
476
477     ~SkAutoMalloc() {
478         sk_free(fPtr);
479     }
480
481     /**
482      *  Passed to reset to specify what happens if the requested size is smaller
483      *  than the current size (and the current block was dynamically allocated).
484      */
485     enum OnShrink {
486         /**
487          *  If the requested size is smaller than the current size, and the
488          *  current block is dynamically allocated, free the old block and
489          *  malloc a new block of the smaller size.
490          */
491         kAlloc_OnShrink,
492
493         /**
494          *  If the requested size is smaller than the current size, and the
495          *  current block is dynamically allocated, just return the old
496          *  block.
497          */
498         kReuse_OnShrink
499     };
500
501     /**
502      *  Reallocates the block to a new size. The ptr may or may not change.
503      */
504     void* reset(size_t size, OnShrink shrink = kAlloc_OnShrink,  bool* didChangeAlloc = NULL) {
505         if (size == fSize || (kReuse_OnShrink == shrink && size < fSize)) {
506             if (NULL != didChangeAlloc) {
507                 *didChangeAlloc = false;
508             }
509             return fPtr;
510         }
511
512         sk_free(fPtr);
513         fPtr = size ? sk_malloc_throw(size) : NULL;
514         fSize = size;
515         if (NULL != didChangeAlloc) {
516             *didChangeAlloc = true;
517         }
518
519         return fPtr;
520     }
521
522     /**
523      *  Releases the block back to the heap
524      */
525     void free() {
526         this->reset(0);
527     }
528
529     /**
530      *  Return the allocated block.
531      */
532     void* get() { return fPtr; }
533     const void* get() const { return fPtr; }
534
535    /** Transfer ownership of the current ptr to the caller, setting the
536        internal reference to null. Note the caller is reponsible for calling
537        sk_free on the returned address.
538     */
539     void* detach() {
540         void* ptr = fPtr;
541         fPtr = NULL;
542         fSize = 0;
543         return ptr;
544     }
545
546 private:
547     void*   fPtr;
548     size_t  fSize;  // can be larger than the requested size (see kReuse)
549 };
550 #define SkAutoMalloc(...) SK_REQUIRE_LOCAL_VAR(SkAutoMalloc)
551
552 /**
553  *  Manage an allocated block of memory. If the requested size is <= kSize, then
554  *  the allocation will come from the stack rather than the heap. This object
555  *  is the sole manager of the lifetime of the block, so the caller must not
556  *  call sk_free() or delete on the block.
557  */
558 template <size_t kSize> class SkAutoSMalloc : SkNoncopyable {
559 public:
560     /**
561      *  Creates initially empty storage. get() returns a ptr, but it is to
562      *  a zero-byte allocation. Must call reset(size) to return an allocated
563      *  block.
564      */
565     SkAutoSMalloc() {
566         fPtr = fStorage;
567         fSize = kSize;
568     }
569
570     /**
571      *  Allocate a block of the specified size. If size <= kSize, then the
572      *  allocation will come from the stack, otherwise it will be dynamically
573      *  allocated.
574      */
575     explicit SkAutoSMalloc(size_t size) {
576         fPtr = fStorage;
577         fSize = kSize;
578         this->reset(size);
579     }
580
581     /**
582      *  Free the allocated block (if any). If the block was small enought to
583      *  have been allocated on the stack (size <= kSize) then this does nothing.
584      */
585     ~SkAutoSMalloc() {
586         if (fPtr != (void*)fStorage) {
587             sk_free(fPtr);
588         }
589     }
590
591     /**
592      *  Return the allocated block. May return non-null even if the block is
593      *  of zero size. Since this may be on the stack or dynamically allocated,
594      *  the caller must not call sk_free() on it, but must rely on SkAutoSMalloc
595      *  to manage it.
596      */
597     void* get() const { return fPtr; }
598
599     /**
600      *  Return a new block of the requested size, freeing (as necessary) any
601      *  previously allocated block. As with the constructor, if size <= kSize
602      *  then the return block may be allocated locally, rather than from the
603      *  heap.
604      */
605     void* reset(size_t size,
606                 SkAutoMalloc::OnShrink shrink = SkAutoMalloc::kAlloc_OnShrink,
607                 bool* didChangeAlloc = NULL) {
608         size = (size < kSize) ? kSize : size;
609         bool alloc = size != fSize && (SkAutoMalloc::kAlloc_OnShrink == shrink || size > fSize);
610         if (NULL != didChangeAlloc) {
611             *didChangeAlloc = alloc;
612         }
613         if (alloc) {
614             if (fPtr != (void*)fStorage) {
615                 sk_free(fPtr);
616             }
617
618             if (size == kSize) {
619                 SkASSERT(fPtr != fStorage); // otherwise we lied when setting didChangeAlloc.
620                 fPtr = fStorage;
621             } else {
622                 fPtr = sk_malloc_flags(size, SK_MALLOC_THROW | SK_MALLOC_TEMP);
623             }
624
625             fSize = size;
626         }
627         SkASSERT(fSize >= size && fSize >= kSize);
628         SkASSERT((fPtr == fStorage) || fSize > kSize);
629         return fPtr;
630     }
631
632 private:
633     void*       fPtr;
634     size_t      fSize;  // can be larger than the requested size (see kReuse)
635     uint32_t    fStorage[(kSize + 3) >> 2];
636 };
637 // Can't guard the constructor because it's a template class.
638
639 #endif /* C++ */
640
641 #endif