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