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