06b24a80f8d63b2d3073f6fc310157d9892e762d
[platform/upstream/harfbuzz.git] / src / hb-private.hh
1 /*
2  * Copyright © 2007,2008,2009  Red Hat, Inc.
3  * Copyright © 2011,2012  Google, Inc.
4  *
5  *  This is part of HarfBuzz, a text shaping library.
6  *
7  * Permission is hereby granted, without written agreement and without
8  * license or royalty fees, to use, copy, modify, and distribute this
9  * software and its documentation for any purpose, provided that the
10  * above copyright notice and the following two paragraphs appear in
11  * all copies of this software.
12  *
13  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17  * DAMAGE.
18  *
19  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
22  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24  *
25  * Red Hat Author(s): Behdad Esfahbod
26  * Google Author(s): Behdad Esfahbod
27  */
28
29 #ifndef HB_PRIVATE_HH
30 #define HB_PRIVATE_HH
31
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "hb.h"
37 #define HB_H_IN
38 #ifdef HAVE_OT
39 #include "hb-ot.h"
40 #define HB_OT_H_IN
41 #endif
42
43 #include <stdlib.h>
44 #include <stddef.h>
45 #include <string.h>
46 #include <assert.h>
47
48 /* We only use these two for debug output.  However, the debug code is
49  * always seen by the compiler (and optimized out in non-debug builds.
50  * If including these becomes a problem, we can start thinking about
51  * someway around that. */
52 #include <stdio.h>
53 #include <errno.h>
54 #include <stdarg.h>
55
56
57 /* Compiler attributes */
58
59
60 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
61 #define _HB_BOOLEAN_EXPR(expr) ((expr) ? 1 : 0)
62 #define likely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 1))
63 #define unlikely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 0))
64 #else
65 #define likely(expr) (expr)
66 #define unlikely(expr) (expr)
67 #endif
68
69 #ifndef __GNUC__
70 #undef __attribute__
71 #define __attribute__(x)
72 #endif
73
74 #if __GNUC__ >= 3
75 #define HB_PURE_FUNC    __attribute__((pure))
76 #define HB_CONST_FUNC   __attribute__((const))
77 #define HB_PRINTF_FUNC(format_idx, arg_idx) __attribute__((__format__ (__printf__, format_idx, arg_idx)))
78 #else
79 #define HB_PURE_FUNC
80 #define HB_CONST_FUNC
81 #define HB_PRINTF_FUNC(format_idx, arg_idx)
82 #endif
83 #if __GNUC__ >= 4
84 #define HB_UNUSED       __attribute__((unused))
85 #else
86 #define HB_UNUSED
87 #endif
88
89 #ifndef HB_INTERNAL
90 # if !defined(__MINGW32__) && !defined(__CYGWIN__)
91 #  define HB_INTERNAL __attribute__((__visibility__("hidden")))
92 # else
93 #  define HB_INTERNAL
94 # endif
95 #endif
96
97 #if __GNUC__ >= 3
98 #define HB_FUNC __PRETTY_FUNCTION__
99 #elif defined(_MSC_VER)
100 #define HB_FUNC __FUNCSIG__
101 #else
102 #define HB_FUNC __func__
103 #endif
104
105 #if defined(_WIN32) || defined(__CYGWIN__)
106    /* We need Windows Vista for both Uniscribe backend and for
107     * MemoryBarrier.  We don't support compiling on Windows XP,
108     * though we run on it fine. */
109 #  if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600
110 #    undef _WIN32_WINNT
111 #  endif
112 #  ifndef _WIN32_WINNT
113 #    define _WIN32_WINNT 0x0600
114 #  endif
115 #  ifndef WIN32_LEAN_AND_MEAN
116 #    define WIN32_LEAN_AND_MEAN 1
117 #  endif
118 #  ifndef STRICT
119 #    define STRICT 1
120 #  endif
121
122 #  if defined(_WIN32_WCE)
123      /* Some things not defined on Windows CE. */
124 #    define getenv(Name) NULL
125 #    define setlocale(Category, Locale) "C"
126 static int errno = 0; /* Use something better? */
127 #  elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
128 #    define getenv(Name) NULL
129 #  endif
130 #  if (defined(__WIN32__) && !defined(__WINE__)) || defined(_MSC_VER)
131 #    define snprintf _snprintf
132      /* Windows CE only has _strdup, while rest of Windows has both. */
133 #    define strdup _strdup
134 #  endif
135 #endif
136
137 #if HAVE_ATEXIT
138 /* atexit() is only safe to be called from shared libraries on certain
139  * platforms.  Whitelist.
140  * https://bugs.freedesktop.org/show_bug.cgi?id=82246 */
141 #  if defined(__linux) && defined(__GLIBC_PREREQ)
142 #    if __GLIBC_PREREQ(2,3)
143 /* From atexit() manpage, it's safe with glibc 2.2.3 on Linux. */
144 #      define HB_USE_ATEXIT 1
145 #    endif
146 #  elif defined(_MSC_VER) || defined(__MINGW32__)
147 /* For MSVC:
148  * http://msdn.microsoft.com/en-ca/library/tze57ck3.aspx
149  * http://msdn.microsoft.com/en-ca/library/zk17ww08.aspx
150  * mingw32 headers say atexit is safe to use in shared libraries.
151  */
152 #    define HB_USE_ATEXIT 1
153 #  elif defined(__ANDROID__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
154 /* This was fixed in Android NKD r8 or r8b:
155  * https://code.google.com/p/android/issues/detail?id=6455
156  * which introduced GCC 4.6:
157  * https://developer.android.com/tools/sdk/ndk/index.html
158  */
159 #    define HB_USE_ATEXIT 1
160 #  endif
161 #endif
162
163 /* Basics */
164
165
166 #ifndef NULL
167 # define NULL ((void *) 0)
168 #endif
169
170 #undef MIN
171 template <typename Type>
172 static inline Type MIN (const Type &a, const Type &b) { return a < b ? a : b; }
173
174 #undef MAX
175 template <typename Type>
176 static inline Type MAX (const Type &a, const Type &b) { return a > b ? a : b; }
177
178 static inline unsigned int DIV_CEIL (const unsigned int a, unsigned int b)
179 { return (a + (b - 1)) / b; }
180
181
182 #undef  ARRAY_LENGTH
183 template <typename Type, unsigned int n>
184 static inline unsigned int ARRAY_LENGTH (const Type (&)[n]) { return n; }
185 /* A const version, but does not detect erratically being called on pointers. */
186 #define ARRAY_LENGTH_CONST(__array) ((signed int) (sizeof (__array) / sizeof (__array[0])))
187
188 #define HB_STMT_START do
189 #define HB_STMT_END   while (0)
190
191 #define _ASSERT_STATIC1(_line, _cond)   HB_UNUSED typedef int _static_assert_on_line_##_line##_failed[(_cond)?1:-1]
192 #define _ASSERT_STATIC0(_line, _cond)   _ASSERT_STATIC1 (_line, (_cond))
193 #define ASSERT_STATIC(_cond)            _ASSERT_STATIC0 (__LINE__, (_cond))
194
195 #define ASSERT_STATIC_EXPR(_cond)((void) sizeof (char[(_cond) ? 1 : -1]))
196 #define ASSERT_STATIC_EXPR_ZERO(_cond) (0 * sizeof (char[(_cond) ? 1 : -1]))
197
198 #define _PASTE1(a,b) a##b
199 #define PASTE(a,b) _PASTE1(a,b)
200
201 /* Lets assert int types.  Saves trouble down the road. */
202
203 ASSERT_STATIC (sizeof (int8_t) == 1);
204 ASSERT_STATIC (sizeof (uint8_t) == 1);
205 ASSERT_STATIC (sizeof (int16_t) == 2);
206 ASSERT_STATIC (sizeof (uint16_t) == 2);
207 ASSERT_STATIC (sizeof (int32_t) == 4);
208 ASSERT_STATIC (sizeof (uint32_t) == 4);
209 ASSERT_STATIC (sizeof (int64_t) == 8);
210 ASSERT_STATIC (sizeof (uint64_t) == 8);
211
212 ASSERT_STATIC (sizeof (hb_codepoint_t) == 4);
213 ASSERT_STATIC (sizeof (hb_position_t) == 4);
214 ASSERT_STATIC (sizeof (hb_mask_t) == 4);
215 ASSERT_STATIC (sizeof (hb_var_int_t) == 4);
216
217
218 /* We like our types POD */
219
220 #define _ASSERT_TYPE_POD1(_line, _type) union _type_##_type##_on_line_##_line##_is_not_POD { _type instance; }
221 #define _ASSERT_TYPE_POD0(_line, _type) _ASSERT_TYPE_POD1 (_line, _type)
222 #define ASSERT_TYPE_POD(_type)          _ASSERT_TYPE_POD0 (__LINE__, _type)
223
224 #ifdef __GNUC__
225 # define _ASSERT_INSTANCE_POD1(_line, _instance) \
226         HB_STMT_START { \
227                 typedef __typeof__(_instance) _type_##_line; \
228                 _ASSERT_TYPE_POD1 (_line, _type_##_line); \
229         } HB_STMT_END
230 #else
231 # define _ASSERT_INSTANCE_POD1(_line, _instance)        typedef int _assertion_on_line_##_line##_not_tested
232 #endif
233 # define _ASSERT_INSTANCE_POD0(_line, _instance)        _ASSERT_INSTANCE_POD1 (_line, _instance)
234 # define ASSERT_INSTANCE_POD(_instance)                 _ASSERT_INSTANCE_POD0 (__LINE__, _instance)
235
236 /* Check _assertion in a method environment */
237 #define _ASSERT_POD1(_line) \
238         HB_UNUSED inline void _static_assertion_on_line_##_line (void) const \
239         { _ASSERT_INSTANCE_POD1 (_line, *this); /* Make sure it's POD. */ }
240 # define _ASSERT_POD0(_line)    _ASSERT_POD1 (_line)
241 # define ASSERT_POD()           _ASSERT_POD0 (__LINE__)
242
243
244
245 /* Misc */
246
247 /* Void! */
248 struct _hb_void_t {};
249 typedef const _hb_void_t &hb_void_t;
250 #define HB_VOID (* (const _hb_void_t *) NULL)
251
252 /* Return the number of 1 bits in mask. */
253 static inline HB_CONST_FUNC unsigned int
254 _hb_popcount32 (uint32_t mask)
255 {
256 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
257   return __builtin_popcount (mask);
258 #else
259   /* "HACKMEM 169" */
260   uint32_t y;
261   y = (mask >> 1) &033333333333;
262   y = mask - y - ((y >>1) & 033333333333);
263   return (((y + (y >> 3)) & 030707070707) % 077);
264 #endif
265 }
266
267 /* Returns the number of bits needed to store number */
268 static inline HB_CONST_FUNC unsigned int
269 _hb_bit_storage (unsigned int number)
270 {
271 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
272   return likely (number) ? (sizeof (unsigned int) * 8 - __builtin_clz (number)) : 0;
273 #else
274   unsigned int n_bits = 0;
275   while (number) {
276     n_bits++;
277     number >>= 1;
278   }
279   return n_bits;
280 #endif
281 }
282
283 /* Returns the number of zero bits in the least significant side of number */
284 static inline HB_CONST_FUNC unsigned int
285 _hb_ctz (unsigned int number)
286 {
287 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
288   return likely (number) ? __builtin_ctz (number) : 0;
289 #else
290   unsigned int n_bits = 0;
291   if (unlikely (!number)) return 0;
292   while (!(number & 1)) {
293     n_bits++;
294     number >>= 1;
295   }
296   return n_bits;
297 #endif
298 }
299
300 static inline bool
301 _hb_unsigned_int_mul_overflows (unsigned int count, unsigned int size)
302 {
303   return (size > 0) && (count >= ((unsigned int) -1) / size);
304 }
305
306
307 /* Type of bsearch() / qsort() compare function */
308 typedef int (*hb_compare_func_t) (const void *, const void *);
309
310
311
312
313 /* arrays and maps */
314
315
316 #define HB_PREALLOCED_ARRAY_INIT {0, 0, NULL}
317 template <typename Type, unsigned int StaticSize=16>
318 struct hb_prealloced_array_t
319 {
320   unsigned int len;
321   unsigned int allocated;
322   Type *array;
323   Type static_array[StaticSize];
324
325   void init (void) { memset (this, 0, sizeof (*this)); }
326
327   inline Type& operator [] (unsigned int i) { return array[i]; }
328   inline const Type& operator [] (unsigned int i) const { return array[i]; }
329
330   inline Type *push (void)
331   {
332     if (!array) {
333       array = static_array;
334       allocated = ARRAY_LENGTH (static_array);
335     }
336     if (likely (len < allocated))
337       return &array[len++];
338
339     /* Need to reallocate */
340     unsigned int new_allocated = allocated + (allocated >> 1) + 8;
341     Type *new_array = NULL;
342
343     if (array == static_array) {
344       new_array = (Type *) calloc (new_allocated, sizeof (Type));
345       if (new_array)
346         memcpy (new_array, array, len * sizeof (Type));
347     } else {
348       bool overflows = (new_allocated < allocated) || _hb_unsigned_int_mul_overflows (new_allocated, sizeof (Type));
349       if (likely (!overflows)) {
350         new_array = (Type *) realloc (array, new_allocated * sizeof (Type));
351       }
352     }
353
354     if (unlikely (!new_array))
355       return NULL;
356
357     array = new_array;
358     allocated = new_allocated;
359     return &array[len++];
360   }
361
362   inline void pop (void)
363   {
364     len--;
365   }
366
367   inline void remove (unsigned int i)
368   {
369      if (unlikely (i >= len))
370        return;
371      memmove (static_cast<void *> (&array[i]),
372               static_cast<void *> (&array[i + 1]),
373               (len - i - 1) * sizeof (Type));
374      len--;
375   }
376
377   inline void shrink (unsigned int l)
378   {
379      if (l < len)
380        len = l;
381   }
382
383   template <typename T>
384   inline Type *find (T v) {
385     for (unsigned int i = 0; i < len; i++)
386       if (array[i] == v)
387         return &array[i];
388     return NULL;
389   }
390   template <typename T>
391   inline const Type *find (T v) const {
392     for (unsigned int i = 0; i < len; i++)
393       if (array[i] == v)
394         return &array[i];
395     return NULL;
396   }
397
398   inline void qsort (void)
399   {
400     ::qsort (array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
401   }
402
403   inline void qsort (unsigned int start, unsigned int end)
404   {
405     ::qsort (array + start, end - start, sizeof (Type), (hb_compare_func_t) Type::cmp);
406   }
407
408   template <typename T>
409   inline Type *bsearch (T *key)
410   {
411     return (Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
412   }
413   template <typename T>
414   inline const Type *bsearch (T *key) const
415   {
416     return (const Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
417   }
418
419   inline void finish (void)
420   {
421     if (array != static_array)
422       free (array);
423     array = NULL;
424     allocated = len = 0;
425   }
426 };
427
428 template <typename Type>
429 struct hb_auto_array_t : hb_prealloced_array_t <Type>
430 {
431   hb_auto_array_t (void) { hb_prealloced_array_t<Type>::init (); }
432   ~hb_auto_array_t (void) { hb_prealloced_array_t<Type>::finish (); }
433 };
434
435
436 #define HB_LOCKABLE_SET_INIT {HB_PREALLOCED_ARRAY_INIT}
437 template <typename item_t, typename lock_t>
438 struct hb_lockable_set_t
439 {
440   hb_prealloced_array_t <item_t, 2> items;
441
442   inline void init (void) { items.init (); }
443
444   template <typename T>
445   inline item_t *replace_or_insert (T v, lock_t &l, bool replace)
446   {
447     l.lock ();
448     item_t *item = items.find (v);
449     if (item) {
450       if (replace) {
451         item_t old = *item;
452         *item = v;
453         l.unlock ();
454         old.finish ();
455       }
456       else {
457         item = NULL;
458         l.unlock ();
459       }
460     } else {
461       item = items.push ();
462       if (likely (item))
463         *item = v;
464       l.unlock ();
465     }
466     return item;
467   }
468
469   template <typename T>
470   inline void remove (T v, lock_t &l)
471   {
472     l.lock ();
473     item_t *item = items.find (v);
474     if (item) {
475       item_t old = *item;
476       *item = items[items.len - 1];
477       items.pop ();
478       l.unlock ();
479       old.finish ();
480     } else {
481       l.unlock ();
482     }
483   }
484
485   template <typename T>
486   inline bool find (T v, item_t *i, lock_t &l)
487   {
488     l.lock ();
489     item_t *item = items.find (v);
490     if (item)
491       *i = *item;
492     l.unlock ();
493     return !!item;
494   }
495
496   template <typename T>
497   inline item_t *find_or_insert (T v, lock_t &l)
498   {
499     l.lock ();
500     item_t *item = items.find (v);
501     if (!item) {
502       item = items.push ();
503       if (likely (item))
504         *item = v;
505     }
506     l.unlock ();
507     return item;
508   }
509
510   inline void finish (lock_t &l)
511   {
512     if (!items.len) {
513       /* No need for locking. */
514       items.finish ();
515       return;
516     }
517     l.lock ();
518     while (items.len) {
519       item_t old = items[items.len - 1];
520         items.pop ();
521         l.unlock ();
522         old.finish ();
523         l.lock ();
524     }
525     items.finish ();
526     l.unlock ();
527   }
528
529 };
530
531
532 /* ASCII tag/character handling */
533
534 static inline bool ISALPHA (unsigned char c)
535 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
536 static inline bool ISALNUM (unsigned char c)
537 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
538 static inline bool ISSPACE (unsigned char c)
539 { return c == ' ' || c =='\f'|| c =='\n'|| c =='\r'|| c =='\t'|| c =='\v'; }
540 static inline unsigned char TOUPPER (unsigned char c)
541 { return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; }
542 static inline unsigned char TOLOWER (unsigned char c)
543 { return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; }
544
545 #define HB_TAG_CHAR4(s)   (HB_TAG(((const char *) s)[0], \
546                                   ((const char *) s)[1], \
547                                   ((const char *) s)[2], \
548                                   ((const char *) s)[3]))
549
550
551 /* C++ helpers */
552
553 /* Makes class uncopyable.  Use in private: section. */
554 #define NO_COPY(T) \
555   T (const T &o); \
556   T &operator = (const T &o)
557
558
559 /* Debug */
560
561
562 #ifndef HB_DEBUG
563 #define HB_DEBUG 0
564 #endif
565
566 static inline bool
567 _hb_debug (unsigned int level,
568            unsigned int max_level)
569 {
570   return level < max_level;
571 }
572
573 #define DEBUG_LEVEL_ENABLED(WHAT, LEVEL) (_hb_debug ((LEVEL), HB_DEBUG_##WHAT))
574 #define DEBUG_ENABLED(WHAT) (DEBUG_LEVEL_ENABLED (WHAT, 0))
575
576 static inline void
577 _hb_print_func (const char *func)
578 {
579   if (func)
580   {
581     unsigned int func_len = strlen (func);
582     /* Skip "static" */
583     if (0 == strncmp (func, "static ", 7))
584       func += 7;
585     /* Skip "typename" */
586     if (0 == strncmp (func, "typename ", 9))
587       func += 9;
588     /* Skip return type */
589     const char *space = strchr (func, ' ');
590     if (space)
591       func = space + 1;
592     /* Skip parameter list */
593     const char *paren = strchr (func, '(');
594     if (paren)
595       func_len = paren - func;
596     fprintf (stderr, "%.*s", func_len, func);
597   }
598 }
599
600 template <int max_level> static inline void
601 _hb_debug_msg_va (const char *what,
602                   const void *obj,
603                   const char *func,
604                   bool indented,
605                   unsigned int level,
606                   int level_dir,
607                   const char *message,
608                   va_list ap) HB_PRINTF_FUNC(7, 0);
609 template <int max_level> static inline void
610 _hb_debug_msg_va (const char *what,
611                   const void *obj,
612                   const char *func,
613                   bool indented,
614                   unsigned int level,
615                   int level_dir,
616                   const char *message,
617                   va_list ap)
618 {
619   if (!_hb_debug (level, max_level))
620     return;
621
622   fprintf (stderr, "%-10s", what ? what : "");
623
624   if (obj)
625     fprintf (stderr, "(%0*lx) ", (unsigned int) (2 * sizeof (void *)), (unsigned long) obj);
626   else
627     fprintf (stderr, " %*s  ", (unsigned int) (2 * sizeof (void *)), "");
628
629   if (indented) {
630 /* One may want to add ASCII version of these.  See:
631  * https://bugs.freedesktop.org/show_bug.cgi?id=50970 */
632 #define VBAR    "\342\224\202"  /* U+2502 BOX DRAWINGS LIGHT VERTICAL */
633 #define VRBAR   "\342\224\234"  /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
634 #define DLBAR   "\342\225\256"  /* U+256E BOX DRAWINGS LIGHT ARC DOWN AND LEFT */
635 #define ULBAR   "\342\225\257"  /* U+256F BOX DRAWINGS LIGHT ARC UP AND LEFT */
636 #define LBAR    "\342\225\264"  /* U+2574 BOX DRAWINGS LIGHT LEFT */
637     static const char bars[] = VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR VBAR;
638     fprintf (stderr, "%2u %s" VRBAR "%s",
639              level,
640              bars + sizeof (bars) - 1 - MIN ((unsigned int) sizeof (bars), (unsigned int) (sizeof (VBAR) - 1) * level),
641              level_dir ? (level_dir > 0 ? DLBAR : ULBAR) : LBAR);
642   } else
643     fprintf (stderr, "   " VRBAR LBAR);
644
645   _hb_print_func (func);
646
647   if (message)
648   {
649     fprintf (stderr, ": ");
650     vfprintf (stderr, message, ap);
651   }
652
653   fprintf (stderr, "\n");
654 }
655 template <> inline void
656 _hb_debug_msg_va<0> (const char *what HB_UNUSED,
657                      const void *obj HB_UNUSED,
658                      const char *func HB_UNUSED,
659                      bool indented HB_UNUSED,
660                      unsigned int level HB_UNUSED,
661                      int level_dir HB_UNUSED,
662                      const char *message HB_UNUSED,
663                      va_list ap HB_UNUSED) {}
664
665 template <int max_level> static inline void
666 _hb_debug_msg (const char *what,
667                const void *obj,
668                const char *func,
669                bool indented,
670                unsigned int level,
671                int level_dir,
672                const char *message,
673                ...) HB_PRINTF_FUNC(7, 8);
674 template <int max_level> static inline void
675 _hb_debug_msg (const char *what,
676                const void *obj,
677                const char *func,
678                bool indented,
679                unsigned int level,
680                int level_dir,
681                const char *message,
682                ...)
683 {
684   va_list ap;
685   va_start (ap, message);
686   _hb_debug_msg_va<max_level> (what, obj, func, indented, level, level_dir, message, ap);
687   va_end (ap);
688 }
689 template <> inline void
690 _hb_debug_msg<0> (const char *what HB_UNUSED,
691                   const void *obj HB_UNUSED,
692                   const char *func HB_UNUSED,
693                   bool indented HB_UNUSED,
694                   unsigned int level HB_UNUSED,
695                   int level_dir HB_UNUSED,
696                   const char *message HB_UNUSED,
697                   ...) HB_PRINTF_FUNC(7, 8);
698 template <> inline void
699 _hb_debug_msg<0> (const char *what HB_UNUSED,
700                   const void *obj HB_UNUSED,
701                   const char *func HB_UNUSED,
702                   bool indented HB_UNUSED,
703                   unsigned int level HB_UNUSED,
704                   int level_dir HB_UNUSED,
705                   const char *message HB_UNUSED,
706                   ...) {}
707
708 #define DEBUG_MSG_LEVEL(WHAT, OBJ, LEVEL, LEVEL_DIR, ...)       _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    true, (LEVEL), (LEVEL_DIR), __VA_ARGS__)
709 #define DEBUG_MSG(WHAT, OBJ, ...)                               _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    false, 0, 0, __VA_ARGS__)
710 #define DEBUG_MSG_FUNC(WHAT, OBJ, ...)                          _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), HB_FUNC, false, 0, 0, __VA_ARGS__)
711
712
713 /*
714  * Printer
715  */
716
717 template <typename T>
718 struct hb_printer_t {
719   const char *print (const T&) { return "something"; }
720 };
721
722 template <>
723 struct hb_printer_t<bool> {
724   const char *print (bool v) { return v ? "true" : "false"; }
725 };
726
727 template <>
728 struct hb_printer_t<hb_void_t> {
729   const char *print (hb_void_t) { return ""; }
730 };
731
732
733 /*
734  * Trace
735  */
736
737 template <typename T>
738 static inline void _hb_warn_no_return (bool returned)
739 {
740   if (unlikely (!returned)) {
741     fprintf (stderr, "OUCH, returned with no call to TRACE_RETURN.  This is a bug, please report.\n");
742   }
743 }
744 template <>
745 /*static*/ inline void _hb_warn_no_return<hb_void_t> (bool returned HB_UNUSED)
746 {}
747
748 template <int max_level, typename ret_t>
749 struct hb_auto_trace_t {
750   explicit inline hb_auto_trace_t (unsigned int *plevel_,
751                                    const char *what_,
752                                    const void *obj_,
753                                    const char *func,
754                                    const char *message,
755                                    ...) : plevel (plevel_), what (what_), obj (obj_), returned (false)
756   {
757     if (plevel) ++*plevel;
758
759     va_list ap;
760     va_start (ap, message);
761     _hb_debug_msg_va<max_level> (what, obj, func, true, plevel ? *plevel : 0, +1, message, ap);
762     va_end (ap);
763   }
764   inline ~hb_auto_trace_t (void)
765   {
766     _hb_warn_no_return<ret_t> (returned);
767     if (!returned) {
768       _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1, " ");
769     }
770     if (plevel) --*plevel;
771   }
772
773   inline ret_t ret (ret_t v, unsigned int line = 0)
774   {
775     if (unlikely (returned)) {
776       fprintf (stderr, "OUCH, double calls to TRACE_RETURN.  This is a bug, please report.\n");
777       return v;
778     }
779
780     _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1,
781                               "return %s (line %d)",
782                               hb_printer_t<ret_t>().print (v), line);
783     if (plevel) --*plevel;
784     plevel = NULL;
785     returned = true;
786     return v;
787   }
788
789   private:
790   unsigned int *plevel;
791   const char *what;
792   const void *obj;
793   bool returned;
794 };
795 template <typename ret_t> /* Optimize when tracing is disabled */
796 struct hb_auto_trace_t<0, ret_t> {
797   explicit inline hb_auto_trace_t (unsigned int *plevel_ HB_UNUSED,
798                                    const char *what HB_UNUSED,
799                                    const void *obj HB_UNUSED,
800                                    const char *func HB_UNUSED,
801                                    const char *message HB_UNUSED,
802                                    ...) {}
803
804   inline ret_t ret (ret_t v, unsigned int line HB_UNUSED = 0) { return v; }
805 };
806
807 #define TRACE_RETURN(RET) trace.ret (RET, __LINE__)
808
809 /* Misc */
810
811 template <typename T> class hb_assert_unsigned_t;
812 template <> class hb_assert_unsigned_t<unsigned char> {};
813 template <> class hb_assert_unsigned_t<unsigned short> {};
814 template <> class hb_assert_unsigned_t<unsigned int> {};
815 template <> class hb_assert_unsigned_t<unsigned long> {};
816
817 template <typename T> static inline bool
818 hb_in_range (T u, T lo, T hi)
819 {
820   /* The sizeof() is here to force template instantiation.
821    * I'm sure there are better ways to do this but can't think of
822    * one right now.  Declaring a variable won't work as HB_UNUSED
823    * is unusable on some platforms and unused types are less likely
824    * to generate a warning than unused variables. */
825   ASSERT_STATIC (sizeof (hb_assert_unsigned_t<T>) >= 0);
826
827   /* The casts below are important as if T is smaller than int,
828    * the subtract results will become a signed int! */
829   return (T)(u - lo) <= (T)(hi - lo);
830 }
831
832 template <typename T> static inline bool
833 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2)
834 {
835   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2);
836 }
837
838 template <typename T> static inline bool
839 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2, T lo3, T hi3)
840 {
841   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2) || hb_in_range (u, lo3, hi3);
842 }
843
844
845 /* Useful for set-operations on small enums.
846  * For example, for testing "x ∈ {x1, x2, x3}" use:
847  * (FLAG(x) & (FLAG(x1) | FLAG(x2) | FLAG(x3)))
848  */
849 #define FLAG(x) (1<<(x))
850 #define FLAG_RANGE(x,y) (ASSERT_STATIC_EXPR_ZERO ((x) < (y)) + FLAG(y+1) - FLAG(x))
851
852
853 template <typename T, typename T2> static inline void
854 hb_bubble_sort (T *array, unsigned int len, int(*compar)(const T *, const T *), T2 *array2)
855 {
856   if (unlikely (!len))
857     return;
858
859   unsigned int k = len - 1;
860   do {
861     unsigned int new_k = 0;
862
863     for (unsigned int j = 0; j < k; j++)
864       if (compar (&array[j], &array[j+1]) > 0)
865       {
866         {
867           T t;
868           t = array[j];
869           array[j] = array[j + 1];
870           array[j + 1] = t;
871         }
872         if (array2)
873         {
874           T2 t;
875           t = array2[j];
876           array2[j] = array2[j + 1];
877           array2[j + 1] = t;
878         }
879
880         new_k = j;
881       }
882     k = new_k;
883   } while (k);
884 }
885
886 template <typename T> static inline void
887 hb_bubble_sort (T *array, unsigned int len, int(*compar)(const T *, const T *))
888 {
889   hb_bubble_sort (array, len, compar, (int *) NULL);
890 }
891
892 static inline hb_bool_t
893 hb_codepoint_parse (const char *s, unsigned int len, int base, hb_codepoint_t *out)
894 {
895   /* Pain because we don't know whether s is nul-terminated. */
896   char buf[64];
897   len = MIN (ARRAY_LENGTH (buf) - 1, len);
898   strncpy (buf, s, len);
899   buf[len] = '\0';
900
901   char *end;
902   errno = 0;
903   unsigned long v = strtoul (buf, &end, base);
904   if (errno) return false;
905   if (*end) return false;
906   *out = v;
907   return true;
908 }
909
910
911 /* Global runtime options. */
912
913 struct hb_options_t
914 {
915   unsigned int initialized : 1;
916   unsigned int uniscribe_bug_compatible : 1;
917 };
918
919 union hb_options_union_t {
920   unsigned int i;
921   hb_options_t opts;
922 };
923 ASSERT_STATIC (sizeof (int) == sizeof (hb_options_union_t));
924
925 HB_INTERNAL void
926 _hb_options_init (void);
927
928 extern HB_INTERNAL hb_options_union_t _hb_options;
929
930 static inline hb_options_t
931 hb_options (void)
932 {
933   if (unlikely (!_hb_options.i))
934     _hb_options_init ();
935
936   return _hb_options.opts;
937 }
938
939
940 #endif /* HB_PRIVATE_HH */