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*/
32SK_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*/
37SK_API extern void sk_throw(void);
38
39enum {
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*/
48SK_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*/
51SK_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*/
55SK_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*/
58SK_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 */
62SK_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 */
66SK_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()
69static 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
78inline void* operator new(size_t size) {
79    return sk_malloc_throw(size);
80}
81
82inline 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_ALWAYSBREAK(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#define SkFAIL(message)                 SK_ALWAYSBREAK(false && message)
117
118// We want to evaluate cond only once, and inside the SkASSERT somewhere so we see its string form.
119// So we use the comma operator to make an SkDebugf that always returns false: we'll evaluate cond,
120// and if it's true the assert passes; if it's false, we'll print the message and the assert fails.
121#define SkASSERTF(cond, fmt, ...)       SkASSERT((cond) || (SkDebugf(fmt"\n", __VA_ARGS__), false))
122
123#ifdef SK_DEVELOPER
124    #define SkDEVCODE(code)             code
125#else
126    #define SkDEVCODE(code)
127#endif
128
129#ifdef SK_IGNORE_TO_STRING
130    #define SK_TO_STRING_NONVIRT()
131    #define SK_TO_STRING_VIRT()
132    #define SK_TO_STRING_PUREVIRT()
133    #define SK_TO_STRING_OVERRIDE()
134#else
135    // the 'toString' helper functions convert Sk* objects to human-readable
136    // form in developer mode
137    #define SK_TO_STRING_NONVIRT() void toString(SkString* str) const;
138    #define SK_TO_STRING_VIRT() virtual void toString(SkString* str) const;
139    #define SK_TO_STRING_PUREVIRT() virtual void toString(SkString* str) const = 0;
140    #define SK_TO_STRING_OVERRIDE() virtual void toString(SkString* str) const SK_OVERRIDE;
141#endif
142
143template <bool>
144struct SkCompileAssert {
145};
146
147// Uses static_cast<bool>(expr) instead of bool(expr) due to
148// https://connect.microsoft.com/VisualStudio/feedback/details/832915
149
150// The extra parentheses in SkCompileAssert<(...)> are a work around for
151// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57771
152// which was fixed in gcc 4.8.2.
153#define SK_COMPILE_ASSERT(expr, msg) \
154    typedef SkCompileAssert<(static_cast<bool>(expr))> \
155            msg[static_cast<bool>(expr) ? 1 : -1] SK_UNUSED
156
157/*
158 *  Usage:  SK_MACRO_CONCAT(a, b)   to construct the symbol ab
159 *
160 *  SK_MACRO_CONCAT_IMPL_PRIV just exists to make this work. Do not use directly
161 *
162 */
163#define SK_MACRO_CONCAT(X, Y)           SK_MACRO_CONCAT_IMPL_PRIV(X, Y)
164#define SK_MACRO_CONCAT_IMPL_PRIV(X, Y)  X ## Y
165
166/*
167 *  Usage: SK_MACRO_APPEND_LINE(foo)    to make foo123, where 123 is the current
168 *                                      line number. Easy way to construct
169 *                                      unique names for local functions or
170 *                                      variables.
171 */
172#define SK_MACRO_APPEND_LINE(name)  SK_MACRO_CONCAT(name, __LINE__)
173
174/**
175 * For some classes, it's almost always an error to instantiate one without a name, e.g.
176 *   {
177 *       SkAutoMutexAcquire(&mutex);
178 *       <some code>
179 *   }
180 * In this case, the writer meant to hold mutex while the rest of the code in the block runs,
181 * but instead the mutex is acquired and then immediately released.  The correct usage is
182 *   {
183 *       SkAutoMutexAcquire lock(&mutex);
184 *       <some code>
185 *   }
186 *
187 * To prevent callers from instantiating your class without a name, use SK_REQUIRE_LOCAL_VAR
188 * like this:
189 *   class classname {
190 *       <your class>
191 *   };
192 *   #define classname(...) SK_REQUIRE_LOCAL_VAR(classname)
193 *
194 * This won't work with templates, and you must inline the class' constructors and destructors.
195 * Take a look at SkAutoFree and SkAutoMalloc in this file for examples.
196 */
197#define SK_REQUIRE_LOCAL_VAR(classname) \
198    SK_COMPILE_ASSERT(false, missing_name_for_##classname)
199
200///////////////////////////////////////////////////////////////////////
201
202/**
203 *  Fast type for signed 8 bits. Use for parameter passing and local variables,
204 *  not for storage.
205 */
206typedef int S8CPU;
207
208/**
209 *  Fast type for unsigned 8 bits. Use for parameter passing and local
210 *  variables, not for storage
211 */
212typedef unsigned U8CPU;
213
214/**
215 *  Fast type for signed 16 bits. Use for parameter passing and local variables,
216 *  not for storage
217 */
218typedef int S16CPU;
219
220/**
221 *  Fast type for unsigned 16 bits. Use for parameter passing and local
222 *  variables, not for storage
223 */
224typedef unsigned U16CPU;
225
226/**
227 *  Meant to be faster than bool (doesn't promise to be 0 or 1,
228 *  just 0 or non-zero
229 */
230typedef int SkBool;
231
232/**
233 *  Meant to be a small version of bool, for storage purposes. Will be 0 or 1
234 */
235typedef uint8_t SkBool8;
236
237#ifdef SK_DEBUG
238    SK_API int8_t      SkToS8(intmax_t);
239    SK_API uint8_t     SkToU8(uintmax_t);
240    SK_API int16_t     SkToS16(intmax_t);
241    SK_API uint16_t    SkToU16(uintmax_t);
242    SK_API int32_t     SkToS32(intmax_t);
243    SK_API uint32_t    SkToU32(uintmax_t);
244    SK_API int         SkToInt(intmax_t);
245    SK_API unsigned    SkToUInt(uintmax_t);
246    SK_API size_t      SkToSizeT(uintmax_t);
247#else
248    #define SkToS8(x)   ((int8_t)(x))
249    #define SkToU8(x)   ((uint8_t)(x))
250    #define SkToS16(x)  ((int16_t)(x))
251    #define SkToU16(x)  ((uint16_t)(x))
252    #define SkToS32(x)  ((int32_t)(x))
253    #define SkToU32(x)  ((uint32_t)(x))
254    #define SkToInt(x)  ((int)(x))
255    #define SkToUInt(x) ((unsigned)(x))
256    #define SkToSizeT(x) ((size_t)(x))
257#endif
258
259/** Returns 0 or 1 based on the condition
260*/
261#define SkToBool(cond)  ((cond) != 0)
262
263#define SK_MaxS16   32767
264#define SK_MinS16   -32767
265#define SK_MaxU16   0xFFFF
266#define SK_MinU16   0
267#define SK_MaxS32   0x7FFFFFFF
268#define SK_MinS32   -SK_MaxS32
269#define SK_MaxU32   0xFFFFFFFF
270#define SK_MinU32   0
271#define SK_NaN32    (1 << 31)
272
273/** Returns true if the value can be represented with signed 16bits
274 */
275static inline bool SkIsS16(long x) {
276    return (int16_t)x == x;
277}
278
279/** Returns true if the value can be represented with unsigned 16bits
280 */
281static inline bool SkIsU16(long x) {
282    return (uint16_t)x == x;
283}
284
285//////////////////////////////////////////////////////////////////////////////
286#ifndef SK_OFFSETOF
287    #define SK_OFFSETOF(type, field)    (size_t)((char*)&(((type*)1)->field) - (char*)1)
288#endif
289
290/** Returns the number of entries in an array (not a pointer)
291*/
292#define SK_ARRAY_COUNT(array)       (sizeof(array) / sizeof(array[0]))
293
294#define SkAlign2(x)     (((x) + 1) >> 1 << 1)
295#define SkIsAlign2(x)   (0 == ((x) & 1))
296
297#define SkAlign4(x)     (((x) + 3) >> 2 << 2)
298#define SkIsAlign4(x)   (0 == ((x) & 3))
299
300#define SkAlign8(x)     (((x) + 7) >> 3 << 3)
301#define SkIsAlign8(x)   (0 == ((x) & 7))
302
303typedef uint32_t SkFourByteTag;
304#define SkSetFourByteTag(a, b, c, d)    (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
305
306/** 32 bit integer to hold a unicode value
307*/
308typedef int32_t SkUnichar;
309/** 32 bit value to hold a millisecond count
310*/
311typedef uint32_t SkMSec;
312/** 1 second measured in milliseconds
313*/
314#define SK_MSec1 1000
315/** maximum representable milliseconds
316*/
317#define SK_MSecMax 0x7FFFFFFF
318/** Returns a < b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
319*/
320#define SkMSec_LT(a, b)     ((int32_t)(a) - (int32_t)(b) < 0)
321/** Returns a <= b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
322*/
323#define SkMSec_LE(a, b)     ((int32_t)(a) - (int32_t)(b) <= 0)
324
325/** The generation IDs in Skia reserve 0 has an invalid marker.
326 */
327#define SK_InvalidGenID     0
328
329/****************************************************************************
330    The rest of these only build with C++
331*/
332#ifdef __cplusplus
333
334/** Faster than SkToBool for integral conditions. Returns 0 or 1
335*/
336static inline int Sk32ToBool(uint32_t n) {
337    return (n | (0-n)) >> 31;
338}
339
340/** Generic swap function. Classes with efficient swaps should specialize this function to take
341    their fast path. This function is used by SkTSort. */
342template <typename T> inline void SkTSwap(T& a, T& b) {
343    T c(a);
344    a = b;
345    b = c;
346}
347
348static inline int32_t SkAbs32(int32_t value) {
349    if (value < 0) {
350        value = -value;
351    }
352    return value;
353}
354
355template <typename T> inline T SkTAbs(T value) {
356    if (value < 0) {
357        value = -value;
358    }
359    return value;
360}
361
362static inline int32_t SkMax32(int32_t a, int32_t b) {
363    if (a < b)
364        a = b;
365    return a;
366}
367
368static inline int32_t SkMin32(int32_t a, int32_t b) {
369    if (a > b)
370        a = b;
371    return a;
372}
373
374template <typename T> const T& SkTMin(const T& a, const T& b) {
375    return (a < b) ? a : b;
376}
377
378template <typename T> const T& SkTMax(const T& a, const T& b) {
379    return (b < a) ? a : b;
380}
381
382static inline int32_t SkSign32(int32_t a) {
383    return (a >> 31) | ((unsigned) -a >> 31);
384}
385
386static inline int32_t SkFastMin32(int32_t value, int32_t max) {
387    if (value > max) {
388        value = max;
389    }
390    return value;
391}
392
393/** Returns signed 32 bit value pinned between min and max, inclusively
394*/
395static inline int32_t SkPin32(int32_t value, int32_t min, int32_t max) {
396    if (value < min) {
397        value = min;
398    }
399    if (value > max) {
400        value = max;
401    }
402    return value;
403}
404
405static inline uint32_t SkSetClearShift(uint32_t bits, bool cond,
406                                       unsigned shift) {
407    SkASSERT((int)cond == 0 || (int)cond == 1);
408    return (bits & ~(1 << shift)) | ((int)cond << shift);
409}
410
411static inline uint32_t SkSetClearMask(uint32_t bits, bool cond,
412                                      uint32_t mask) {
413    return cond ? bits | mask : bits & ~mask;
414}
415
416///////////////////////////////////////////////////////////////////////////////
417
418/** Use to combine multiple bits in a bitmask in a type safe way.
419 */
420template <typename T>
421T SkTBitOr(T a, T b) {
422    return (T)(a | b);
423}
424
425/**
426 *  Use to cast a pointer to a different type, and maintaining strict-aliasing
427 */
428template <typename Dst> Dst SkTCast(const void* ptr) {
429    union {
430        const void* src;
431        Dst dst;
432    } data;
433    data.src = ptr;
434    return data.dst;
435}
436
437//////////////////////////////////////////////////////////////////////////////
438
439/** \class SkNoncopyable
440
441SkNoncopyable is the base class for objects that may do not want to
442be copied. It hides its copy-constructor and its assignment-operator.
443*/
444class SK_API SkNoncopyable {
445public:
446    SkNoncopyable() {}
447
448private:
449    SkNoncopyable(const SkNoncopyable&);
450    SkNoncopyable& operator=(const SkNoncopyable&);
451};
452
453class SkAutoFree : SkNoncopyable {
454public:
455    SkAutoFree() : fPtr(NULL) {}
456    explicit SkAutoFree(void* ptr) : fPtr(ptr) {}
457    ~SkAutoFree() { sk_free(fPtr); }
458
459    /** Return the currently allocate buffer, or null
460    */
461    void* get() const { return fPtr; }
462
463    /** Assign a new ptr allocated with sk_malloc (or null), and return the
464        previous ptr. Note it is the caller's responsibility to sk_free the
465        returned ptr.
466    */
467    void* set(void* ptr) {
468        void* prev = fPtr;
469        fPtr = ptr;
470        return prev;
471    }
472
473    /** Transfer ownership of the current ptr to the caller, setting the
474        internal reference to null. Note the caller is reponsible for calling
475        sk_free on the returned address.
476    */
477    void* detach() { return this->set(NULL); }
478
479    /** Free the current buffer, and set the internal reference to NULL. Same
480        as calling sk_free(detach())
481    */
482    void free() {
483        sk_free(fPtr);
484        fPtr = NULL;
485    }
486
487private:
488    void* fPtr;
489    // illegal
490    SkAutoFree(const SkAutoFree&);
491    SkAutoFree& operator=(const SkAutoFree&);
492};
493#define SkAutoFree(...) SK_REQUIRE_LOCAL_VAR(SkAutoFree)
494
495/**
496 *  Manage an allocated block of heap memory. This object is the sole manager of
497 *  the lifetime of the block, so the caller must not call sk_free() or delete
498 *  on the block, unless detach() was called.
499 */
500class SkAutoMalloc : SkNoncopyable {
501public:
502    explicit SkAutoMalloc(size_t size = 0) {
503        fPtr = size ? sk_malloc_throw(size) : NULL;
504        fSize = size;
505    }
506
507    ~SkAutoMalloc() {
508        sk_free(fPtr);
509    }
510
511    /**
512     *  Passed to reset to specify what happens if the requested size is smaller
513     *  than the current size (and the current block was dynamically allocated).
514     */
515    enum OnShrink {
516        /**
517         *  If the requested size is smaller than the current size, and the
518         *  current block is dynamically allocated, free the old block and
519         *  malloc a new block of the smaller size.
520         */
521        kAlloc_OnShrink,
522
523        /**
524         *  If the requested size is smaller than the current size, and the
525         *  current block is dynamically allocated, just return the old
526         *  block.
527         */
528        kReuse_OnShrink
529    };
530
531    /**
532     *  Reallocates the block to a new size. The ptr may or may not change.
533     */
534    void* reset(size_t size, OnShrink shrink = kAlloc_OnShrink,  bool* didChangeAlloc = NULL) {
535        if (size == fSize || (kReuse_OnShrink == shrink && size < fSize)) {
536            if (NULL != didChangeAlloc) {
537                *didChangeAlloc = false;
538            }
539            return fPtr;
540        }
541
542        sk_free(fPtr);
543        fPtr = size ? sk_malloc_throw(size) : NULL;
544        fSize = size;
545        if (NULL != didChangeAlloc) {
546            *didChangeAlloc = true;
547        }
548
549        return fPtr;
550    }
551
552    /**
553     *  Releases the block back to the heap
554     */
555    void free() {
556        this->reset(0);
557    }
558
559    /**
560     *  Return the allocated block.
561     */
562    void* get() { return fPtr; }
563    const void* get() const { return fPtr; }
564
565   /** Transfer ownership of the current ptr to the caller, setting the
566       internal reference to null. Note the caller is reponsible for calling
567       sk_free on the returned address.
568    */
569    void* detach() {
570        void* ptr = fPtr;
571        fPtr = NULL;
572        fSize = 0;
573        return ptr;
574    }
575
576private:
577    void*   fPtr;
578    size_t  fSize;  // can be larger than the requested size (see kReuse)
579};
580#define SkAutoMalloc(...) SK_REQUIRE_LOCAL_VAR(SkAutoMalloc)
581
582/**
583 *  Manage an allocated block of memory. If the requested size is <= kSize, then
584 *  the allocation will come from the stack rather than the heap. This object
585 *  is the sole manager of the lifetime of the block, so the caller must not
586 *  call sk_free() or delete on the block.
587 */
588template <size_t kSize> class SkAutoSMalloc : SkNoncopyable {
589public:
590    /**
591     *  Creates initially empty storage. get() returns a ptr, but it is to
592     *  a zero-byte allocation. Must call reset(size) to return an allocated
593     *  block.
594     */
595    SkAutoSMalloc() {
596        fPtr = fStorage;
597        fSize = kSize;
598    }
599
600    /**
601     *  Allocate a block of the specified size. If size <= kSize, then the
602     *  allocation will come from the stack, otherwise it will be dynamically
603     *  allocated.
604     */
605    explicit SkAutoSMalloc(size_t size) {
606        fPtr = fStorage;
607        fSize = kSize;
608        this->reset(size);
609    }
610
611    /**
612     *  Free the allocated block (if any). If the block was small enought to
613     *  have been allocated on the stack (size <= kSize) then this does nothing.
614     */
615    ~SkAutoSMalloc() {
616        if (fPtr != (void*)fStorage) {
617            sk_free(fPtr);
618        }
619    }
620
621    /**
622     *  Return the allocated block. May return non-null even if the block is
623     *  of zero size. Since this may be on the stack or dynamically allocated,
624     *  the caller must not call sk_free() on it, but must rely on SkAutoSMalloc
625     *  to manage it.
626     */
627    void* get() const { return fPtr; }
628
629    /**
630     *  Return a new block of the requested size, freeing (as necessary) any
631     *  previously allocated block. As with the constructor, if size <= kSize
632     *  then the return block may be allocated locally, rather than from the
633     *  heap.
634     */
635    void* reset(size_t size,
636                SkAutoMalloc::OnShrink shrink = SkAutoMalloc::kAlloc_OnShrink,
637                bool* didChangeAlloc = NULL) {
638        size = (size < kSize) ? kSize : size;
639        bool alloc = size != fSize && (SkAutoMalloc::kAlloc_OnShrink == shrink || size > fSize);
640        if (NULL != didChangeAlloc) {
641            *didChangeAlloc = alloc;
642        }
643        if (alloc) {
644            if (fPtr != (void*)fStorage) {
645                sk_free(fPtr);
646            }
647
648            if (size == kSize) {
649                SkASSERT(fPtr != fStorage); // otherwise we lied when setting didChangeAlloc.
650                fPtr = fStorage;
651            } else {
652                fPtr = sk_malloc_flags(size, SK_MALLOC_THROW | SK_MALLOC_TEMP);
653            }
654
655            fSize = size;
656        }
657        SkASSERT(fSize >= size && fSize >= kSize);
658        SkASSERT((fPtr == fStorage) || fSize > kSize);
659        return fPtr;
660    }
661
662private:
663    void*       fPtr;
664    size_t      fSize;  // can be larger than the requested size (see kReuse)
665    uint32_t    fStorage[(kSize + 3) >> 2];
666};
667// Can't guard the constructor because it's a template class.
668
669#endif /* C++ */
670
671#endif
672