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