Imported Upstream version 0.9.3
[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
58 /* Essentials */
59
60 #ifndef NULL
61 # define NULL ((void *) 0)
62 #endif
63
64
65 /* Basics */
66
67
68 #undef MIN
69 template <typename Type>
70 static inline Type MIN (const Type &a, const Type &b) { return a < b ? a : b; }
71
72 #undef MAX
73 template <typename Type>
74 static inline Type MAX (const Type &a, const Type &b) { return a > b ? a : b; }
75
76
77 #undef  ARRAY_LENGTH
78 template <typename Type, unsigned int n>
79 static inline unsigned int ARRAY_LENGTH (const Type (&a)[n]) { return n; }
80
81 #define HB_STMT_START do
82 #define HB_STMT_END   while (0)
83
84 #define _ASSERT_STATIC1(_line, _cond)   typedef int _static_assert_on_line_##_line##_failed[(_cond)?1:-1]
85 #define _ASSERT_STATIC0(_line, _cond)   _ASSERT_STATIC1 (_line, (_cond))
86 #define ASSERT_STATIC(_cond)            _ASSERT_STATIC0 (__LINE__, (_cond))
87
88 #define ASSERT_STATIC_EXPR(_cond)((void) sizeof (char[(_cond) ? 1 : -1]))
89 #define ASSERT_STATIC_EXPR_ZERO(_cond) (0 * sizeof (char[(_cond) ? 1 : -1]))
90
91 #define _PASTE1(a,b) a##b
92 #define PASTE(a,b) _PASTE1(a,b)
93
94 /* Lets assert int types.  Saves trouble down the road. */
95
96 ASSERT_STATIC (sizeof (int8_t) == 1);
97 ASSERT_STATIC (sizeof (uint8_t) == 1);
98 ASSERT_STATIC (sizeof (int16_t) == 2);
99 ASSERT_STATIC (sizeof (uint16_t) == 2);
100 ASSERT_STATIC (sizeof (int32_t) == 4);
101 ASSERT_STATIC (sizeof (uint32_t) == 4);
102 ASSERT_STATIC (sizeof (int64_t) == 8);
103 ASSERT_STATIC (sizeof (uint64_t) == 8);
104
105 ASSERT_STATIC (sizeof (hb_codepoint_t) == 4);
106 ASSERT_STATIC (sizeof (hb_position_t) == 4);
107 ASSERT_STATIC (sizeof (hb_mask_t) == 4);
108 ASSERT_STATIC (sizeof (hb_var_int_t) == 4);
109
110
111 /* We like our types POD */
112
113 #define _ASSERT_TYPE_POD1(_line, _type) union _type_##_type##_on_line_##_line##_is_not_POD { _type instance; }
114 #define _ASSERT_TYPE_POD0(_line, _type) _ASSERT_TYPE_POD1 (_line, _type)
115 #define ASSERT_TYPE_POD(_type)          _ASSERT_TYPE_POD0 (__LINE__, _type)
116
117 #ifdef __GNUC__
118 # define _ASSERT_INSTANCE_POD1(_line, _instance) \
119         HB_STMT_START { \
120                 typedef __typeof__(_instance) _type_##_line; \
121                 _ASSERT_TYPE_POD1 (_line, _type_##_line); \
122         } HB_STMT_END
123 #else
124 # define _ASSERT_INSTANCE_POD1(_line, _instance)        typedef int _assertion_on_line_##_line##_not_tested
125 #endif
126 # define _ASSERT_INSTANCE_POD0(_line, _instance)        _ASSERT_INSTANCE_POD1 (_line, _instance)
127 # define ASSERT_INSTANCE_POD(_instance)                 _ASSERT_INSTANCE_POD0 (__LINE__, _instance)
128
129 /* Check _assertion in a method environment */
130 #define _ASSERT_POD1(_line) \
131         inline void _static_assertion_on_line_##_line (void) const \
132         { _ASSERT_INSTANCE_POD1 (_line, *this); /* Make sure it's POD. */ }
133 # define _ASSERT_POD0(_line)    _ASSERT_POD1 (_line)
134 # define ASSERT_POD()           _ASSERT_POD0 (__LINE__)
135
136
137
138 /* Misc */
139
140
141 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
142 #define _HB_BOOLEAN_EXPR(expr) ((expr) ? 1 : 0)
143 #define likely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 1))
144 #define unlikely(expr) (__builtin_expect (_HB_BOOLEAN_EXPR(expr), 0))
145 #else
146 #define likely(expr) (expr)
147 #define unlikely(expr) (expr)
148 #endif
149
150 #ifndef __GNUC__
151 #undef __attribute__
152 #define __attribute__(x)
153 #endif
154
155 #if __GNUC__ >= 3
156 #define HB_PURE_FUNC    __attribute__((pure))
157 #define HB_CONST_FUNC   __attribute__((const))
158 #define HB_PRINTF_FUNC(format_idx, arg_idx) __attribute__((__format__ (__printf__, format_idx, arg_idx)))
159 #else
160 #define HB_PURE_FUNC
161 #define HB_CONST_FUNC
162 #define HB_PRINTF_FUNC(format_idx, arg_idx)
163 #endif
164 #if __GNUC__ >= 4
165 #define HB_UNUSED       __attribute__((unused))
166 #else
167 #define HB_UNUSED
168 #endif
169
170 #ifndef HB_INTERNAL
171 # ifndef __MINGW32__
172 #  define HB_INTERNAL __attribute__((__visibility__("hidden")))
173 # else
174 #  define HB_INTERNAL
175 # endif
176 #endif
177
178
179 #if (defined(__WIN32__) && !defined(__WINE__)) || defined(_MSC_VER)
180 #define snprintf _snprintf
181 #endif
182
183 #ifdef _MSC_VER
184 #undef inline
185 #define inline __inline
186 #endif
187
188 #ifdef __STRICT_ANSI__
189 #undef inline
190 #define inline __inline__
191 #endif
192
193
194 #if __GNUC__ >= 3
195 #define HB_FUNC __PRETTY_FUNCTION__
196 #elif defined(_MSC_VER)
197 #define HB_FUNC __FUNCSIG__
198 #else
199 #define HB_FUNC __func__
200 #endif
201
202
203 /* Return the number of 1 bits in mask. */
204 static inline HB_CONST_FUNC unsigned int
205 _hb_popcount32 (uint32_t mask)
206 {
207 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
208   return __builtin_popcount (mask);
209 #else
210   /* "HACKMEM 169" */
211   register uint32_t y;
212   y = (mask >> 1) &033333333333;
213   y = mask - y - ((y >>1) & 033333333333);
214   return (((y + (y >> 3)) & 030707070707) % 077);
215 #endif
216 }
217
218 /* Returns the number of bits needed to store number */
219 static inline HB_CONST_FUNC unsigned int
220 _hb_bit_storage (unsigned int number)
221 {
222 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
223   return likely (number) ? (sizeof (unsigned int) * 8 - __builtin_clz (number)) : 0;
224 #else
225   register unsigned int n_bits = 0;
226   while (number) {
227     n_bits++;
228     number >>= 1;
229   }
230   return n_bits;
231 #endif
232 }
233
234 /* Returns the number of zero bits in the least significant side of number */
235 static inline HB_CONST_FUNC unsigned int
236 _hb_ctz (unsigned int number)
237 {
238 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
239   return likely (number) ? __builtin_ctz (number) : 0;
240 #else
241   register unsigned int n_bits = 0;
242   if (unlikely (!number)) return 0;
243   while (!(number & 1)) {
244     n_bits++;
245     number >>= 1;
246   }
247   return n_bits;
248 #endif
249 }
250
251 static inline bool
252 _hb_unsigned_int_mul_overflows (unsigned int count, unsigned int size)
253 {
254   return (size > 0) && (count >= ((unsigned int) -1) / size);
255 }
256
257
258 /* Type of bsearch() / qsort() compare function */
259 typedef int (*hb_compare_func_t) (const void *, const void *);
260
261
262
263
264 /* arrays and maps */
265
266
267 #define HB_PREALLOCED_ARRAY_INIT {0}
268 template <typename Type, unsigned int StaticSize>
269 struct hb_prealloced_array_t
270 {
271   unsigned int len;
272   unsigned int allocated;
273   Type *array;
274   Type static_array[StaticSize];
275
276   void init (void) { memset (this, 0, sizeof (*this)); }
277
278   inline Type& operator [] (unsigned int i) { return array[i]; }
279   inline const Type& operator [] (unsigned int i) const { return array[i]; }
280
281   inline Type *push (void)
282   {
283     if (!array) {
284       array = static_array;
285       allocated = ARRAY_LENGTH (static_array);
286     }
287     if (likely (len < allocated))
288       return &array[len++];
289
290     /* Need to reallocate */
291     unsigned int new_allocated = allocated + (allocated >> 1) + 8;
292     Type *new_array = NULL;
293
294     if (array == static_array) {
295       new_array = (Type *) calloc (new_allocated, sizeof (Type));
296       if (new_array)
297         memcpy (new_array, array, len * sizeof (Type));
298     } else {
299       bool overflows = (new_allocated < allocated) || _hb_unsigned_int_mul_overflows (new_allocated, sizeof (Type));
300       if (likely (!overflows)) {
301         new_array = (Type *) realloc (array, new_allocated * sizeof (Type));
302       }
303     }
304
305     if (unlikely (!new_array))
306       return NULL;
307
308     array = new_array;
309     allocated = new_allocated;
310     return &array[len++];
311   }
312
313   inline void pop (void)
314   {
315     len--;
316     /* TODO: shrink array if needed */
317   }
318
319   inline void shrink (unsigned int l)
320   {
321      if (l < len)
322        len = l;
323     /* TODO: shrink array if needed */
324   }
325
326   template <typename T>
327   inline Type *find (T v) {
328     for (unsigned int i = 0; i < len; i++)
329       if (array[i] == v)
330         return &array[i];
331     return NULL;
332   }
333   template <typename T>
334   inline const Type *find (T v) const {
335     for (unsigned int i = 0; i < len; i++)
336       if (array[i] == v)
337         return &array[i];
338     return NULL;
339   }
340
341   inline void sort (void)
342   {
343     qsort (array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
344   }
345
346   inline void sort (unsigned int start, unsigned int end)
347   {
348     qsort (array + start, end - start, sizeof (Type), (hb_compare_func_t) Type::cmp);
349   }
350
351   template <typename T>
352   inline Type *bsearch (T *key)
353   {
354     return (Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
355   }
356   template <typename T>
357   inline const Type *bsearch (T *key) const
358   {
359     return (const Type *) ::bsearch (key, array, len, sizeof (Type), (hb_compare_func_t) Type::cmp);
360   }
361
362   inline void finish (void)
363   {
364     if (array != static_array)
365       free (array);
366     array = NULL;
367     allocated = len = 0;
368   }
369 };
370
371
372 #define HB_LOCKABLE_SET_INIT {HB_PREALLOCED_ARRAY_INIT}
373 template <typename item_t, typename lock_t>
374 struct hb_lockable_set_t
375 {
376   hb_prealloced_array_t <item_t, 2> items;
377
378   inline void init (void) { items.init (); }
379
380   template <typename T>
381   inline item_t *replace_or_insert (T v, lock_t &l, bool replace)
382   {
383     l.lock ();
384     item_t *item = items.find (v);
385     if (item) {
386       if (replace) {
387         item_t old = *item;
388         *item = v;
389         l.unlock ();
390         old.finish ();
391       }
392       else {
393         item = NULL;
394         l.unlock ();
395       }
396     } else {
397       item = items.push ();
398       if (likely (item))
399         *item = v;
400       l.unlock ();
401     }
402     return item;
403   }
404
405   template <typename T>
406   inline void remove (T v, lock_t &l)
407   {
408     l.lock ();
409     item_t *item = items.find (v);
410     if (item) {
411       item_t old = *item;
412       *item = items[items.len - 1];
413       items.pop ();
414       l.unlock ();
415       old.finish ();
416     } else {
417       l.unlock ();
418     }
419   }
420
421   template <typename T>
422   inline bool find (T v, item_t *i, lock_t &l)
423   {
424     l.lock ();
425     item_t *item = items.find (v);
426     if (item)
427       *i = *item;
428     l.unlock ();
429     return !!item;
430   }
431
432   template <typename T>
433   inline item_t *find_or_insert (T v, lock_t &l)
434   {
435     l.lock ();
436     item_t *item = items.find (v);
437     if (!item) {
438       item = items.push ();
439       if (likely (item))
440         *item = v;
441     }
442     l.unlock ();
443     return item;
444   }
445
446   inline void finish (lock_t &l)
447   {
448     if (!items.len) {
449       /* No need for locking. */
450       items.finish ();
451       return;
452     }
453     l.lock ();
454     while (items.len) {
455       item_t old = items[items.len - 1];
456         items.pop ();
457         l.unlock ();
458         old.finish ();
459         l.lock ();
460     }
461     items.finish ();
462     l.unlock ();
463   }
464
465 };
466
467
468
469
470 /* Big-endian handling */
471
472 static inline uint16_t hb_be_uint16 (const uint16_t v)
473 {
474   const uint8_t *V = (const uint8_t *) &v;
475   return (V[0] << 8) | V[1];
476 }
477
478 static inline uint16_t hb_uint16_swap (const uint16_t v)
479 {
480   return (v >> 8) | (v << 8);
481 }
482
483 static inline uint32_t hb_uint32_swap (const uint32_t v)
484 {
485   return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16);
486 }
487
488 /* Note, of the following macros, uint16_get is the one called many many times.
489  * If there is any optimizations to be done, it's in that macro.  However, I
490  * already confirmed that on my T400 ThinkPad at least, using bswap_16(), which
491  * results in a single ror instruction, does NOT speed this up.  In fact, it
492  * resulted in a minor slowdown.  At any rate, note that v may not be correctly
493  * aligned, so I think the current implementation is optimal.
494  */
495
496 #define hb_be_uint16_put(v,V)   HB_STMT_START { v[0] = (V>>8); v[1] = (V); } HB_STMT_END
497 #define hb_be_uint16_get(v)     (uint16_t) ((v[0] << 8) + v[1])
498 #define hb_be_uint16_eq(a,b)    (a[0] == b[0] && a[1] == b[1])
499
500 #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
501 #define hb_be_uint32_get(v)     (uint32_t) ((v[0] << 24) + (v[1] << 16) + (v[2] << 8) + v[3])
502 #define hb_be_uint32_eq(a,b)    (a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3])
503
504
505 /* ASCII tag/character handling */
506
507 static inline unsigned char ISALPHA (unsigned char c)
508 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
509 static inline unsigned char ISALNUM (unsigned char c)
510 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
511 static inline unsigned char TOUPPER (unsigned char c)
512 { return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; }
513 static inline unsigned char TOLOWER (unsigned char c)
514 { return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; }
515
516 #define HB_TAG_CHAR4(s)   (HB_TAG(((const char *) s)[0], \
517                                   ((const char *) s)[1], \
518                                   ((const char *) s)[2], \
519                                   ((const char *) s)[3]))
520
521
522 /* C++ helpers */
523
524 /* Makes class uncopyable.  Use in private: section. */
525 #define NO_COPY(T) \
526   T (const T &o); \
527   T &operator = (const T &o)
528
529
530 /* Debug */
531
532
533 #ifndef HB_DEBUG
534 #define HB_DEBUG 0
535 #endif
536
537 static inline bool
538 _hb_debug (unsigned int level,
539            unsigned int max_level)
540 {
541   return level < max_level;
542 }
543
544 #define DEBUG_LEVEL(WHAT, LEVEL) (_hb_debug ((LEVEL), HB_DEBUG_##WHAT))
545 #define DEBUG(WHAT) (DEBUG_LEVEL (WHAT, 0))
546
547 template <int max_level> inline void
548 _hb_debug_msg_va (const char *what,
549                   const void *obj,
550                   const char *func,
551                   bool indented,
552                   unsigned int level,
553                   int level_dir,
554                   const char *message,
555                   va_list ap)
556 {
557   if (!_hb_debug (level, max_level))
558     return;
559
560   fprintf (stderr, "%-10s", what ? what : "");
561
562   if (obj)
563     fprintf (stderr, "(%0*lx) ", (unsigned int) (2 * sizeof (void *)), (unsigned long) obj);
564   else
565     fprintf (stderr, " %*s  ", (unsigned int) (2 * sizeof (void *)), "");
566
567   if (indented) {
568 /* One may want to add ASCII version of these.  See:
569  * https://bugs.freedesktop.org/show_bug.cgi?id=50970 */
570 #define VBAR    "\342\224\202"  /* U+2502 BOX DRAWINGS LIGHT VERTICAL */
571 #define VRBAR   "\342\224\234"  /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
572 #define DLBAR   "\342\225\256"  /* U+256E BOX DRAWINGS LIGHT ARC DOWN AND LEFT */
573 #define ULBAR   "\342\225\257"  /* U+256F BOX DRAWINGS LIGHT ARC UP AND LEFT */
574 #define LBAR    "\342\225\264"  /* U+2574 BOX DRAWINGS LIGHT LEFT */
575     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;
576     fprintf (stderr, "%2d %s" VRBAR "%s",
577              level,
578              bars + sizeof (bars) - 1 - MIN ((unsigned int) sizeof (bars), (unsigned int) (sizeof (VBAR) - 1) * level),
579              level_dir ? (level_dir > 0 ? DLBAR : ULBAR) : LBAR);
580   } else
581     fprintf (stderr, "   " VRBAR LBAR);
582
583   if (func) {
584     /* If there's a class name, just write that. */
585     const char *dotdot = strstr (func, "::");
586     const char *space = strchr (func, ' ');
587     if (space && dotdot && space < dotdot)
588       func = space + 1;
589     unsigned int func_len = dotdot ? dotdot - func : strlen (func);
590     fprintf (stderr, "%.*s: ", func_len, func);
591   }
592
593   if (message)
594     vfprintf (stderr, message, ap);
595
596   fprintf (stderr, "\n");
597 }
598 template <> inline void
599 _hb_debug_msg_va<0> (const char *what HB_UNUSED,
600                      const void *obj HB_UNUSED,
601                      const char *func HB_UNUSED,
602                      bool indented HB_UNUSED,
603                      unsigned int level HB_UNUSED,
604                      int level_dir HB_UNUSED,
605                      const char *message HB_UNUSED,
606                      va_list ap HB_UNUSED) {}
607
608 template <int max_level> inline void
609 _hb_debug_msg (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                ...) HB_PRINTF_FUNC(7, 8);
617 template <int max_level> inline void
618 _hb_debug_msg (const char *what,
619                const void *obj,
620                const char *func,
621                bool indented,
622                unsigned int level,
623                int level_dir,
624                const char *message,
625                ...)
626 {
627   va_list ap;
628   va_start (ap, message);
629   _hb_debug_msg_va<max_level> (what, obj, func, indented, level, level_dir, message, ap);
630   va_end (ap);
631 }
632 template <> inline void
633 _hb_debug_msg<0> (const char *what HB_UNUSED,
634                   const void *obj HB_UNUSED,
635                   const char *func HB_UNUSED,
636                   bool indented HB_UNUSED,
637                   unsigned int level HB_UNUSED,
638                   int level_dir HB_UNUSED,
639                   const char *message HB_UNUSED,
640                   ...) HB_PRINTF_FUNC(7, 8);
641 template <> inline void
642 _hb_debug_msg<0> (const char *what HB_UNUSED,
643                   const void *obj HB_UNUSED,
644                   const char *func HB_UNUSED,
645                   bool indented HB_UNUSED,
646                   unsigned int level HB_UNUSED,
647                   int level_dir HB_UNUSED,
648                   const char *message HB_UNUSED,
649                   ...) {}
650
651 #define DEBUG_MSG_LEVEL(WHAT, OBJ, LEVEL, LEVEL_DIR, ...)       _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    true, (LEVEL), (LEVEL_DIR), __VA_ARGS__)
652 #define DEBUG_MSG(WHAT, OBJ, ...)                               _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), NULL,    false, 0, 0, __VA_ARGS__)
653 #define DEBUG_MSG_FUNC(WHAT, OBJ, ...)                          _hb_debug_msg<HB_DEBUG_##WHAT> (#WHAT, (OBJ), HB_FUNC, false, 0, 0, __VA_ARGS__)
654
655
656 /*
657  * Trace
658  */
659
660 template <int max_level>
661 struct hb_auto_trace_t {
662   explicit inline hb_auto_trace_t (unsigned int *plevel_,
663                                    const char *what_,
664                                    const void *obj_,
665                                    const char *func,
666                                    const char *message,
667                                    ...) : plevel (plevel_), what (what_), obj (obj_), returned (false)
668   {
669     if (plevel) ++*plevel;
670
671     va_list ap;
672     va_start (ap, message);
673     _hb_debug_msg_va<max_level> (what, obj, func, true, plevel ? *plevel : 0, +1, message, ap);
674     va_end (ap);
675   }
676   inline ~hb_auto_trace_t (void)
677   {
678     if (unlikely (!returned)) {
679       fprintf (stderr, "OUCH, returned with no call to TRACE_RETURN.  This is a bug, please report.  Level was %d.\n", plevel ? *plevel : -1);
680       _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1, " ");
681       return;
682     }
683
684     if (plevel) --*plevel;
685   }
686
687   inline bool ret (bool v, unsigned int line = 0)
688   {
689     if (unlikely (returned)) {
690       fprintf (stderr, "OUCH, double calls to TRACE_RETURN.  This is a bug, please report.\n");
691       return v;
692     }
693
694     _hb_debug_msg<max_level> (what, obj, NULL, true, plevel ? *plevel : 1, -1, "return %s (line %d)", v ? "true" : "false", line);
695     if (plevel) --*plevel;
696     plevel = NULL;
697     returned = true;
698     return v;
699   }
700
701   private:
702   unsigned int *plevel;
703   bool returned;
704   const char *what;
705   const void *obj;
706 };
707 template <> /* Optimize when tracing is disabled */
708 struct hb_auto_trace_t<0> {
709   explicit inline hb_auto_trace_t (unsigned int *plevel_ HB_UNUSED,
710                                    const char *what HB_UNUSED,
711                                    const void *obj HB_UNUSED,
712                                    const char *func HB_UNUSED,
713                                    const char *message HB_UNUSED,
714                                    ...) {}
715
716   template <typename T>
717   inline T ret (T v, unsigned int line = 0) { return v; }
718 };
719
720 #define TRACE_RETURN(RET) trace.ret (RET, __LINE__)
721
722 /* Misc */
723
724
725 /* Pre-mature optimization:
726  * Checks for lo <= u <= hi but with an optimization if lo and hi
727  * are only different in a contiguous set of lower-most bits.
728  */
729 template <typename T> static inline bool
730 hb_in_range (T u, T lo, T hi)
731 {
732   if ( ((lo^hi) & lo) == 0 &&
733        ((lo^hi) & hi) == (lo^hi) &&
734        ((lo^hi) & ((lo^hi) + 1)) == 0 )
735     return (u & ~(lo^hi)) == lo;
736   else
737     return lo <= u && u <= hi;
738 }
739
740 template <typename T> static inline bool
741 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2, T lo3, T hi3)
742 {
743   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2) || hb_in_range (u, lo3, hi3);
744 }
745
746
747 /* Useful for set-operations on small enums.
748  * For example, for testing "x ∈ {x1, x2, x3}" use:
749  * (FLAG(x) & (FLAG(x1) | FLAG(x2) | FLAG(x3)))
750  */
751 #define FLAG(x) (1<<(x))
752 #define FLAG_RANGE(x,y) (ASSERT_STATIC_EXPR_ZERO ((x) < (y)) + FLAG(y+1) - FLAG(x))
753
754
755 template <typename T, typename T2> inline void
756 hb_bubble_sort (T *array, unsigned int len, int(*compar)(const T *, const T *), T2 *array2)
757 {
758   if (unlikely (!len))
759     return;
760
761   unsigned int k = len - 1;
762   do {
763     unsigned int new_k = 0;
764
765     for (unsigned int j = 0; j < k; j++)
766       if (compar (&array[j], &array[j+1]) > 0)
767       {
768         {
769           T t;
770           t = array[j];
771           array[j] = array[j + 1];
772           array[j + 1] = t;
773         }
774         if (array2)
775         {
776           T2 t;
777           t = array2[j];
778           array2[j] = array2[j + 1];
779           array2[j + 1] = t;
780         }
781
782         new_k = j;
783       }
784     k = new_k;
785   } while (k);
786 }
787
788 template <typename T> inline void
789 hb_bubble_sort (T *array, unsigned int len, int(*compar)(const T *, const T *))
790 {
791   hb_bubble_sort (array, len, compar, (int *) NULL);
792 }
793
794 static inline hb_bool_t
795 hb_codepoint_parse (const char *s, unsigned int len, int base, hb_codepoint_t *out)
796 {
797   /* Pain because we don't know whether s is nul-terminated. */
798   char buf[64];
799   strncpy (buf, s, MIN (ARRAY_LENGTH (buf) - 1, len));
800   buf[MIN (ARRAY_LENGTH (buf) - 1, len)] = '\0';
801
802   char *end;
803   errno = 0;
804   unsigned long v = strtoul (buf, &end, base);
805   if (errno) return false;
806   if (*end) return false;
807   *out = v;
808   return true;
809 }
810
811
812 #endif /* HB_PRIVATE_HH */