Imported Upstream version 1.7.6
[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 #define _GNU_SOURCE 1
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #include "hb.h"
39 #define HB_H_IN
40 #ifdef HAVE_OT
41 #include "hb-ot.h"
42 #define HB_OT_H_IN
43 #endif
44
45 #include <math.h>
46 #include <stdlib.h>
47 #include <stddef.h>
48 #include <string.h>
49 #include <assert.h>
50 #include <errno.h>
51 #include <stdio.h>
52 #include <stdarg.h>
53
54 #if defined(_MSC_VER) || defined(__MINGW32__)
55 #include <intrin.h>
56 #endif
57
58 #define HB_PASTE1(a,b) a##b
59 #define HB_PASTE(a,b) HB_PASTE1(a,b)
60
61 /* Compile-time custom allocator support. */
62
63 #if defined(hb_malloc_impl) \
64  && defined(hb_calloc_impl) \
65  && defined(hb_realloc_impl) \
66  && defined(hb_free_impl)
67 extern "C" void* hb_malloc_impl(size_t size);
68 extern "C" void* hb_calloc_impl(size_t nmemb, size_t size);
69 extern "C" void* hb_realloc_impl(void *ptr, size_t size);
70 extern "C" void  hb_free_impl(void *ptr);
71 #define malloc hb_malloc_impl
72 #define calloc hb_calloc_impl
73 #define realloc hb_realloc_impl
74 #define free hb_free_impl
75 #endif
76
77
78 /* Compiler attributes */
79
80
81 #if __cplusplus < 201103L
82
83 #ifndef nullptr
84 #define nullptr NULL
85 #endif
86
87 // Static assertions
88 #ifndef static_assert
89 #define static_assert(e, msg) \
90         HB_UNUSED typedef int HB_PASTE(static_assertion_failed_at_line_, __LINE__) [(e) ? 1 : -1]
91 #endif // static_assert
92
93 #endif // __cplusplus < 201103L
94
95 #if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE__)
96 #define likely(expr) (__builtin_expect (!!(expr), 1))
97 #define unlikely(expr) (__builtin_expect (!!(expr), 0))
98 #else
99 #define likely(expr) (expr)
100 #define unlikely(expr) (expr)
101 #endif
102
103 #if !defined(__GNUC__) && !defined(__clang__)
104 #undef __attribute__
105 #define __attribute__(x)
106 #endif
107
108 #if __GNUC__ >= 3
109 #define HB_PURE_FUNC    __attribute__((pure))
110 #define HB_CONST_FUNC   __attribute__((const))
111 #define HB_PRINTF_FUNC(format_idx, arg_idx) __attribute__((__format__ (__printf__, format_idx, arg_idx)))
112 #else
113 #define HB_PURE_FUNC
114 #define HB_CONST_FUNC
115 #define HB_PRINTF_FUNC(format_idx, arg_idx)
116 #endif
117 #if __GNUC__ >= 4
118 #define HB_UNUSED       __attribute__((unused))
119 #elif defined(_MSC_VER) /* https://github.com/harfbuzz/harfbuzz/issues/635 */
120 #define HB_UNUSED __pragma(warning(suppress: 4100 4101))
121 #else
122 #define HB_UNUSED
123 #endif
124
125 #ifndef HB_INTERNAL
126 # if !defined(HB_NO_VISIBILITY) && !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(_MSC_VER) && !defined(__SUNPRO_CC)
127 #  define HB_INTERNAL __attribute__((__visibility__("hidden")))
128 # else
129 #  define HB_INTERNAL
130 #  define HB_NO_VISIBILITY 1
131 # endif
132 #endif
133
134 #if __GNUC__ >= 3
135 #define HB_FUNC __PRETTY_FUNCTION__
136 #elif defined(_MSC_VER)
137 #define HB_FUNC __FUNCSIG__
138 #else
139 #define HB_FUNC __func__
140 #endif
141
142 #ifdef __SUNPRO_CC
143 /* https://github.com/harfbuzz/harfbuzz/issues/630 */
144 #define __restrict
145 #endif
146
147 /*
148  * Borrowed from https://bugzilla.mozilla.org/show_bug.cgi?id=1215411
149  * HB_FALLTHROUGH is an annotation to suppress compiler warnings about switch
150  * cases that fall through without a break or return statement. HB_FALLTHROUGH
151  * is only needed on cases that have code:
152  *
153  * switch (foo) {
154  *   case 1: // These cases have no code. No fallthrough annotations are needed.
155  *   case 2:
156  *   case 3:
157  *     foo = 4; // This case has code, so a fallthrough annotation is needed:
158  *     HB_FALLTHROUGH;
159  *   default:
160  *     return foo;
161  * }
162  */
163 #if defined(__clang__) && __cplusplus >= 201103L
164    /* clang's fallthrough annotations are only available starting in C++11. */
165 #  define HB_FALLTHROUGH [[clang::fallthrough]]
166 #elif __GNUC__ >= 7
167    /* GNU fallthrough attribute is available from GCC7 */
168 #  define HB_FALLTHROUGH __attribute__((fallthrough))
169 #elif defined(_MSC_VER)
170    /*
171     * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis):
172     * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx
173     */
174 #  include <sal.h>
175 #  define HB_FALLTHROUGH __fallthrough
176 #else
177 #  define HB_FALLTHROUGH /* FALLTHROUGH */
178 #endif
179
180 #if defined(_WIN32) || defined(__CYGWIN__)
181    /* We need Windows Vista for both Uniscribe backend and for
182     * MemoryBarrier.  We don't support compiling on Windows XP,
183     * though we run on it fine. */
184 #  if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600
185 #    undef _WIN32_WINNT
186 #  endif
187 #  ifndef _WIN32_WINNT
188 #    define _WIN32_WINNT 0x0600
189 #  endif
190 #  ifndef WIN32_LEAN_AND_MEAN
191 #    define WIN32_LEAN_AND_MEAN 1
192 #  endif
193 #  ifndef STRICT
194 #    define STRICT 1
195 #  endif
196
197 #  if defined(_WIN32_WCE)
198      /* Some things not defined on Windows CE. */
199 #    define vsnprintf _vsnprintf
200 #    define getenv(Name) nullptr
201 #    if _WIN32_WCE < 0x800
202 #      define setlocale(Category, Locale) "C"
203 static int errno = 0; /* Use something better? */
204 #    endif
205 #  elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
206 #    define getenv(Name) nullptr
207 #  endif
208 #  if defined(_MSC_VER) && _MSC_VER < 1900
209 #    define snprintf _snprintf
210 #  endif
211 #endif
212
213 #if HAVE_ATEXIT
214 /* atexit() is only safe to be called from shared libraries on certain
215  * platforms.  Whitelist.
216  * https://bugs.freedesktop.org/show_bug.cgi?id=82246 */
217 #  if defined(__linux) && defined(__GLIBC_PREREQ)
218 #    if __GLIBC_PREREQ(2,3)
219 /* From atexit() manpage, it's safe with glibc 2.2.3 on Linux. */
220 #      define HB_USE_ATEXIT 1
221 #    endif
222 #  elif defined(_MSC_VER) || defined(__MINGW32__)
223 /* For MSVC:
224  * http://msdn.microsoft.com/en-ca/library/tze57ck3.aspx
225  * http://msdn.microsoft.com/en-ca/library/zk17ww08.aspx
226  * mingw32 headers say atexit is safe to use in shared libraries.
227  */
228 #    define HB_USE_ATEXIT 1
229 #  elif defined(__ANDROID__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
230 /* This was fixed in Android NKD r8 or r8b:
231  * https://code.google.com/p/android/issues/detail?id=6455
232  * which introduced GCC 4.6:
233  * https://developer.android.com/tools/sdk/ndk/index.html
234  */
235 #    define HB_USE_ATEXIT 1
236 #  elif defined(__APPLE__)
237 /* For macOS and related platforms, the atexit man page indicates
238  * that it will be invoked when the library is unloaded, not only
239  * at application exit.
240  */
241 #    define HB_USE_ATEXIT 1
242 #  endif
243 #endif
244
245 /* Basics */
246
247 #undef MIN
248 template <typename Type>
249 static inline Type MIN (const Type &a, const Type &b) { return a < b ? a : b; }
250
251 #undef MAX
252 template <typename Type>
253 static inline Type MAX (const Type &a, const Type &b) { return a > b ? a : b; }
254
255 static inline unsigned int DIV_CEIL (const unsigned int a, unsigned int b)
256 { return (a + (b - 1)) / b; }
257
258
259 #undef  ARRAY_LENGTH
260 template <typename Type, unsigned int n>
261 static inline unsigned int ARRAY_LENGTH (const Type (&)[n]) { return n; }
262 /* A const version, but does not detect erratically being called on pointers. */
263 #define ARRAY_LENGTH_CONST(__array) ((signed int) (sizeof (__array) / sizeof (__array[0])))
264
265 #define HB_STMT_START do
266 #define HB_STMT_END   while (0)
267
268 template <unsigned int cond> class hb_assert_constant_t;
269 template <> class hb_assert_constant_t<1> {};
270
271 #define ASSERT_STATIC_EXPR_ZERO(_cond) (0 * (unsigned int) sizeof (hb_assert_constant_t<_cond>))
272
273 /* Lets assert int types.  Saves trouble down the road. */
274
275 static_assert ((sizeof (int8_t) == 1), "");
276 static_assert ((sizeof (uint8_t) == 1), "");
277 static_assert ((sizeof (int16_t) == 2), "");
278 static_assert ((sizeof (uint16_t) == 2), "");
279 static_assert ((sizeof (int32_t) == 4), "");
280 static_assert ((sizeof (uint32_t) == 4), "");
281 static_assert ((sizeof (int64_t) == 8), "");
282 static_assert ((sizeof (uint64_t) == 8), "");
283
284 static_assert ((sizeof (hb_codepoint_t) == 4), "");
285 static_assert ((sizeof (hb_position_t) == 4), "");
286 static_assert ((sizeof (hb_mask_t) == 4), "");
287 static_assert ((sizeof (hb_var_int_t) == 4), "");
288
289
290 /* We like our types POD */
291
292 #define _ASSERT_TYPE_POD1(_line, _type) union _type_##_type##_on_line_##_line##_is_not_POD { _type instance; }
293 #define _ASSERT_TYPE_POD0(_line, _type) _ASSERT_TYPE_POD1 (_line, _type)
294 #define ASSERT_TYPE_POD(_type)          _ASSERT_TYPE_POD0 (__LINE__, _type)
295
296 #ifdef __GNUC__
297 # define _ASSERT_INSTANCE_POD1(_line, _instance) \
298         HB_STMT_START { \
299                 typedef __typeof__(_instance) _type_##_line; \
300                 _ASSERT_TYPE_POD1 (_line, _type_##_line); \
301         } HB_STMT_END
302 #else
303 # define _ASSERT_INSTANCE_POD1(_line, _instance)        typedef int _assertion_on_line_##_line##_not_tested
304 #endif
305 # define _ASSERT_INSTANCE_POD0(_line, _instance)        _ASSERT_INSTANCE_POD1 (_line, _instance)
306 # define ASSERT_INSTANCE_POD(_instance)                 _ASSERT_INSTANCE_POD0 (__LINE__, _instance)
307
308 /* Check _assertion in a method environment */
309 #define _ASSERT_POD1(_line) \
310         HB_UNUSED inline void _static_assertion_on_line_##_line (void) const \
311         { _ASSERT_INSTANCE_POD1 (_line, *this); /* Make sure it's POD. */ }
312 # define _ASSERT_POD0(_line)    _ASSERT_POD1 (_line)
313 # define ASSERT_POD()           _ASSERT_POD0 (__LINE__)
314
315
316
317 /* Misc */
318
319 /*
320  * Void!
321  */
322 typedef const struct _hb_void_t *hb_void_t;
323 #define HB_VOID ((const _hb_void_t *) nullptr)
324
325 /* Return the number of 1 bits in v. */
326 template <typename T>
327 static inline HB_CONST_FUNC unsigned int
328 _hb_popcount (T v)
329 {
330 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) && defined(__OPTIMIZE__)
331   if (sizeof (T) <= sizeof (unsigned int))
332     return __builtin_popcount (v);
333
334   if (sizeof (T) <= sizeof (unsigned long))
335     return __builtin_popcountl (v);
336
337   if (sizeof (T) <= sizeof (unsigned long long))
338     return __builtin_popcountll (v);
339 #endif
340
341   if (sizeof (T) <= 4)
342   {
343     /* "HACKMEM 169" */
344     uint32_t y;
345     y = (v >> 1) &033333333333;
346     y = v - y - ((y >>1) & 033333333333);
347     return (((y + (y >> 3)) & 030707070707) % 077);
348   }
349
350   if (sizeof (T) == 8)
351   {
352     unsigned int shift = 32;
353     return _hb_popcount<uint32_t> ((uint32_t) v) + _hb_popcount ((uint32_t) (v >> shift));
354   }
355
356   if (sizeof (T) == 16)
357   {
358     unsigned int shift = 64;
359     return _hb_popcount<uint64_t> ((uint64_t) v) + _hb_popcount ((uint64_t) (v >> shift));
360   }
361
362   assert (0);
363 }
364
365 /* Returns the number of bits needed to store number */
366 template <typename T>
367 static inline HB_CONST_FUNC unsigned int
368 _hb_bit_storage (T v)
369 {
370   if (unlikely (!v)) return 0;
371
372 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
373   if (sizeof (T) <= sizeof (unsigned int))
374     return sizeof (unsigned int) * 8 - __builtin_clz (v);
375
376   if (sizeof (T) <= sizeof (unsigned long))
377     return sizeof (unsigned long) * 8 - __builtin_clzl (v);
378
379   if (sizeof (T) <= sizeof (unsigned long long))
380     return sizeof (unsigned long long) * 8 - __builtin_clzll (v);
381 #endif
382
383 #if defined(_MSC_VER) || defined(__MINGW32__)
384   if (sizeof (T) <= sizeof (unsigned int))
385   {
386     unsigned long where;
387     _BitScanReverse (&where, v);
388     return 1 + where;
389   }
390 # if _WIN64
391   if (sizeof (T) <= 8)
392   {
393     unsigned long where;
394     _BitScanReverse64 (&where, v);
395     return 1 + where;
396   }
397 # endif
398 #endif
399
400   if (sizeof (T) <= 4)
401   {
402     /* "bithacks" */
403     const unsigned int b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
404     const unsigned int S[] = {1, 2, 4, 8, 16};
405     unsigned int r = 0;
406     for (int i = 4; i >= 0; i--)
407       if (v & b[i])
408       {
409         v >>= S[i];
410         r |= S[i];
411       }
412     return r + 1;
413   }
414   if (sizeof (T) <= 8)
415   {
416     /* "bithacks" */
417     const uint64_t b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000};
418     const unsigned int S[] = {1, 2, 4, 8, 16, 32};
419     unsigned int r = 0;
420     for (int i = 5; i >= 0; i--)
421       if (v & b[i])
422       {
423         v >>= S[i];
424         r |= S[i];
425       }
426     return r + 1;
427   }
428   if (sizeof (T) == 16)
429   {
430     unsigned int shift = 64;
431     return (v >> shift) ? _hb_bit_storage<uint64_t> ((uint64_t) v >> shift) + shift :
432                           _hb_bit_storage<uint64_t> ((uint64_t) v);
433   }
434
435   assert (0);
436 }
437
438 /* Returns the number of zero bits in the least significant side of v */
439 template <typename T>
440 static inline HB_CONST_FUNC unsigned int
441 _hb_ctz (T v)
442 {
443   if (unlikely (!v)) return 0;
444
445 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__OPTIMIZE__)
446   if (sizeof (T) <= sizeof (unsigned int))
447     return __builtin_ctz (v);
448
449   if (sizeof (T) <= sizeof (unsigned long))
450     return __builtin_ctzl (v);
451
452   if (sizeof (T) <= sizeof (unsigned long long))
453     return __builtin_ctzll (v);
454 #endif
455
456 #if defined(_MSC_VER) || defined(__MINGW32__)
457   if (sizeof (T) <= sizeof (unsigned int))
458   {
459     unsigned long where;
460     _BitScanForward (&where, v);
461     return where;
462   }
463 # if _WIN64
464   if (sizeof (T) <= 8)
465   {
466     unsigned long where;
467     _BitScanForward64 (&where, v);
468     return where;
469   }
470 # endif
471 #endif
472
473   if (sizeof (T) <= 4)
474   {
475     /* "bithacks" */
476     unsigned int c = 32;
477     v &= - (int32_t) v;
478     if (v) c--;
479     if (v & 0x0000FFFF) c -= 16;
480     if (v & 0x00FF00FF) c -= 8;
481     if (v & 0x0F0F0F0F) c -= 4;
482     if (v & 0x33333333) c -= 2;
483     if (v & 0x55555555) c -= 1;
484     return c;
485   }
486   if (sizeof (T) <= 8)
487   {
488     /* "bithacks" */
489     unsigned int c = 64;
490     v &= - (int64_t) (v);
491     if (v) c--;
492     if (v & 0x00000000FFFFFFFF) c -= 32;
493     if (v & 0x0000FFFF0000FFFF) c -= 16;
494     if (v & 0x00FF00FF00FF00FF) c -= 8;
495     if (v & 0x0F0F0F0F0F0F0F0F) c -= 4;
496     if (v & 0x3333333333333333) c -= 2;
497     if (v & 0x5555555555555555) c -= 1;
498     return c;
499   }
500   if (sizeof (T) == 16)
501   {
502     unsigned int shift = 64;
503     return (uint64_t) v ? _hb_bit_storage<uint64_t> ((uint64_t) v) :
504                           _hb_bit_storage<uint64_t> ((uint64_t) v >> shift) + shift;
505   }
506
507   assert (0);
508 }
509
510 static inline bool
511 _hb_unsigned_int_mul_overflows (unsigned int count, unsigned int size)
512 {
513   return (size > 0) && (count >= ((unsigned int) -1) / size);
514 }
515
516 static inline unsigned int
517 _hb_ceil_to_4 (unsigned int v)
518 {
519   return ((v - 1) | 3) + 1;
520 }
521
522
523
524 /* arrays and maps */
525
526
527 #define HB_PREALLOCED_ARRAY_INIT {0, 0, nullptr}
528 template <typename Type, unsigned int StaticSize=16>
529 struct hb_prealloced_array_t
530 {
531   unsigned int len;
532   unsigned int allocated;
533   Type *array;
534   Type static_array[StaticSize];
535
536   void init (void)
537   {
538     len = 0;
539     allocated = ARRAY_LENGTH (static_array);
540     array = static_array;
541   }
542
543   inline Type& operator [] (unsigned int i) { return array[i]; }
544   inline const Type& operator [] (unsigned int i) const { return array[i]; }
545
546   inline Type *push (void)
547   {
548     if (unlikely (!resize (len + 1)))
549       return nullptr;
550
551     return &array[len - 1];
552   }
553
554   /* Allocate for size but don't adjust len. */
555   inline bool alloc(unsigned int size)
556   {
557     if (likely (size <= allocated))
558       return true;
559
560     /* Reallocate */
561
562     unsigned int new_allocated = allocated;
563     while (size >= new_allocated)
564       new_allocated += (new_allocated >> 1) + 8;
565
566     Type *new_array = nullptr;
567
568     if (array == static_array) {
569       new_array = (Type *) calloc (new_allocated, sizeof (Type));
570       if (new_array)
571         memcpy (new_array, array, len * sizeof (Type));
572           } else {
573       bool overflows = (new_allocated < allocated) || _hb_unsigned_int_mul_overflows (new_allocated, sizeof (Type));
574       if (likely (!overflows)) {
575         new_array = (Type *) realloc (array, new_allocated * sizeof (Type));
576       }
577     }
578
579     if (unlikely (!new_array))
580       return false;
581
582     array = new_array;
583     allocated = new_allocated;
584
585     return true;
586   }
587
588   inline bool resize (unsigned int size)
589   {
590     if (!alloc (size))
591       return false;
592
593     len = size;
594     return true;
595   }
596
597   inline void pop (void)
598   {
599     len--;
600   }
601
602   inline void remove (unsigned int i)
603   {
604      if (unlikely (i >= len))
605        return;
606      memmove (static_cast<void *> (&array[i]),
607               static_cast<void *> (&array[i + 1]),
608               (len - i - 1) * sizeof (Type));
609      len--;
610   }
611
612   inline void shrink (unsigned int l)
613   {
614      if (l < len)
615        len = l;
616   }
617
618   template <typename T>
619   inline Type *find (T v) {
620     for (unsigned int i = 0; i < len; i++)
621       if (array[i] == v)
622         return &array[i];
623     return nullptr;
624   }
625   template <typename T>
626   inline const Type *find (T v) const {
627     for (unsigned int i = 0; i < len; i++)
628       if (array[i] == v)
629         return &array[i];
630     return nullptr;
631   }
632
633   inline void qsort (int (*cmp)(const void*, const void*))
634   {
635     ::qsort (array, len, sizeof (Type), cmp);
636   }
637
638   inline void qsort (void)
639   {
640     ::qsort (array, len, sizeof (Type), Type::cmp);
641   }
642
643   inline void qsort (unsigned int start, unsigned int end)
644   {
645     ::qsort (array + start, end - start, sizeof (Type), Type::cmp);
646   }
647
648   template <typename T>
649   inline Type *lsearch (const T &x)
650   {
651     for (unsigned int i = 0; i < len; i++)
652       if (0 == this->array[i].cmp (&x))
653         return &array[i];
654     return nullptr;
655   }
656
657   template <typename T>
658   inline Type *bsearch (const T &x)
659   {
660     unsigned int i;
661     return bfind (x, &i) ? &array[i] : nullptr;
662   }
663   template <typename T>
664   inline const Type *bsearch (const T &x) const
665   {
666     unsigned int i;
667     return bfind (x, &i) ? &array[i] : nullptr;
668   }
669   template <typename T>
670   inline bool bfind (const T &x, unsigned int *i) const
671   {
672     int min = 0, max = (int) this->len - 1;
673     while (min <= max)
674     {
675       int mid = (min + max) / 2;
676       int c = this->array[mid].cmp (&x);
677       if (c < 0)
678         max = mid - 1;
679       else if (c > 0)
680         min = mid + 1;
681       else
682       {
683         *i = mid;
684         return true;
685       }
686     }
687     if (max < 0 || (max < (int) this->len && this->array[max].cmp (&x) > 0))
688       max++;
689     *i = max;
690     return false;
691   }
692
693   inline void finish (void)
694   {
695     if (array != static_array)
696       free (array);
697     array = nullptr;
698     allocated = len = 0;
699   }
700 };
701
702 template <typename Type>
703 struct hb_auto_array_t : hb_prealloced_array_t <Type>
704 {
705   hb_auto_array_t (void) { hb_prealloced_array_t<Type>::init (); }
706   ~hb_auto_array_t (void) { hb_prealloced_array_t<Type>::finish (); }
707 };
708
709
710 #define HB_LOCKABLE_SET_INIT {HB_PREALLOCED_ARRAY_INIT}
711 template <typename item_t, typename lock_t>
712 struct hb_lockable_set_t
713 {
714   hb_prealloced_array_t <item_t, 1> items;
715
716   inline void init (void) { items.init (); }
717
718   template <typename T>
719   inline item_t *replace_or_insert (T v, lock_t &l, bool replace)
720   {
721     l.lock ();
722     item_t *item = items.find (v);
723     if (item) {
724       if (replace) {
725         item_t old = *item;
726         *item = v;
727         l.unlock ();
728         old.finish ();
729       }
730       else {
731         item = nullptr;
732         l.unlock ();
733       }
734     } else {
735       item = items.push ();
736       if (likely (item))
737         *item = v;
738       l.unlock ();
739     }
740     return item;
741   }
742
743   template <typename T>
744   inline void remove (T v, lock_t &l)
745   {
746     l.lock ();
747     item_t *item = items.find (v);
748     if (item) {
749       item_t old = *item;
750       *item = items[items.len - 1];
751       items.pop ();
752       l.unlock ();
753       old.finish ();
754     } else {
755       l.unlock ();
756     }
757   }
758
759   template <typename T>
760   inline bool find (T v, item_t *i, lock_t &l)
761   {
762     l.lock ();
763     item_t *item = items.find (v);
764     if (item)
765       *i = *item;
766     l.unlock ();
767     return !!item;
768   }
769
770   template <typename T>
771   inline item_t *find_or_insert (T v, lock_t &l)
772   {
773     l.lock ();
774     item_t *item = items.find (v);
775     if (!item) {
776       item = items.push ();
777       if (likely (item))
778         *item = v;
779     }
780     l.unlock ();
781     return item;
782   }
783
784   inline void finish (lock_t &l)
785   {
786     if (!items.len) {
787       /* No need for locking. */
788       items.finish ();
789       return;
790     }
791     l.lock ();
792     while (items.len) {
793       item_t old = items[items.len - 1];
794         items.pop ();
795         l.unlock ();
796         old.finish ();
797         l.lock ();
798     }
799     items.finish ();
800     l.unlock ();
801   }
802
803 };
804
805
806 /* ASCII tag/character handling */
807
808 static inline bool ISALPHA (unsigned char c)
809 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
810 static inline bool ISALNUM (unsigned char c)
811 { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
812 static inline bool ISSPACE (unsigned char c)
813 { return c == ' ' || c =='\f'|| c =='\n'|| c =='\r'|| c =='\t'|| c =='\v'; }
814 static inline unsigned char TOUPPER (unsigned char c)
815 { return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; }
816 static inline unsigned char TOLOWER (unsigned char c)
817 { return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; }
818
819
820 /* HB_NDEBUG disables some sanity checks that are very safe to disable and
821  * should be disabled in production systems.  If NDEBUG is defined, enable
822  * HB_NDEBUG; but if it's desirable that normal assert()s (which are very
823  * light-weight) to be enabled, then HB_DEBUG can be defined to disable
824  * the costlier checks. */
825 #ifdef NDEBUG
826 #define HB_NDEBUG
827 #endif
828
829
830 /* Misc */
831
832 template <typename T> class hb_assert_unsigned_t;
833 template <> class hb_assert_unsigned_t<unsigned char> {};
834 template <> class hb_assert_unsigned_t<unsigned short> {};
835 template <> class hb_assert_unsigned_t<unsigned int> {};
836 template <> class hb_assert_unsigned_t<unsigned long> {};
837
838 template <typename T> static inline bool
839 hb_in_range (T u, T lo, T hi)
840 {
841   /* The sizeof() is here to force template instantiation.
842    * I'm sure there are better ways to do this but can't think of
843    * one right now.  Declaring a variable won't work as HB_UNUSED
844    * is unusable on some platforms and unused types are less likely
845    * to generate a warning than unused variables. */
846   static_assert ((sizeof (hb_assert_unsigned_t<T>) >= 0), "");
847
848   /* The casts below are important as if T is smaller than int,
849    * the subtract results will become a signed int! */
850   return (T)(u - lo) <= (T)(hi - lo);
851 }
852
853 template <typename T> static inline bool
854 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2)
855 {
856   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2);
857 }
858
859 template <typename T> static inline bool
860 hb_in_ranges (T u, T lo1, T hi1, T lo2, T hi2, T lo3, T hi3)
861 {
862   return hb_in_range (u, lo1, hi1) || hb_in_range (u, lo2, hi2) || hb_in_range (u, lo3, hi3);
863 }
864
865
866 /* Enable bitwise ops on enums marked as flags_t */
867 /* To my surprise, looks like the function resolver is happy to silently cast
868  * one enum to another...  So this doesn't provide the type-checking that I
869  * originally had in mind... :(.
870  *
871  * For MSVC warnings, see: https://github.com/harfbuzz/harfbuzz/pull/163
872  */
873 #ifdef _MSC_VER
874 # pragma warning(disable:4200)
875 # pragma warning(disable:4800)
876 #endif
877 #define HB_MARK_AS_FLAG_T(T) \
878         extern "C++" { \
879           static inline T operator | (T l, T r) { return T ((unsigned) l | (unsigned) r); } \
880           static inline T operator & (T l, T r) { return T ((unsigned) l & (unsigned) r); } \
881           static inline T operator ^ (T l, T r) { return T ((unsigned) l ^ (unsigned) r); } \
882           static inline T operator ~ (T r) { return T (~(unsigned int) r); } \
883           static inline T& operator |= (T &l, T r) { l = l | r; return l; } \
884           static inline T& operator &= (T& l, T r) { l = l & r; return l; } \
885           static inline T& operator ^= (T& l, T r) { l = l ^ r; return l; } \
886         }
887
888
889 /* Useful for set-operations on small enums.
890  * For example, for testing "x ∈ {x1, x2, x3}" use:
891  * (FLAG_UNSAFE(x) & (FLAG(x1) | FLAG(x2) | FLAG(x3)))
892  */
893 #define FLAG(x) (ASSERT_STATIC_EXPR_ZERO ((unsigned int)(x) < 32) + (1U << (unsigned int)(x)))
894 #define FLAG_UNSAFE(x) ((unsigned int)(x) < 32 ? (1U << (unsigned int)(x)) : 0)
895 #define FLAG_RANGE(x,y) (ASSERT_STATIC_EXPR_ZERO ((x) < (y)) + FLAG(y+1) - FLAG(x))
896
897
898 template <typename T, typename T2> static inline void
899 hb_stable_sort (T *array, unsigned int len, int(*compar)(const T *, const T *), T2 *array2)
900 {
901   for (unsigned int i = 1; i < len; i++)
902   {
903     unsigned int j = i;
904     while (j && compar (&array[j - 1], &array[i]) > 0)
905       j--;
906     if (i == j)
907       continue;
908     /* Move item i to occupy place for item j, shift what's in between. */
909     {
910       T t = array[i];
911       memmove (&array[j + 1], &array[j], (i - j) * sizeof (T));
912       array[j] = t;
913     }
914     if (array2)
915     {
916       T2 t = array2[i];
917       memmove (&array2[j + 1], &array2[j], (i - j) * sizeof (T2));
918       array2[j] = t;
919     }
920   }
921 }
922
923 template <typename T> static inline void
924 hb_stable_sort (T *array, unsigned int len, int(*compar)(const T *, const T *))
925 {
926   hb_stable_sort (array, len, compar, (int *) nullptr);
927 }
928
929 static inline hb_bool_t
930 hb_codepoint_parse (const char *s, unsigned int len, int base, hb_codepoint_t *out)
931 {
932   /* Pain because we don't know whether s is nul-terminated. */
933   char buf[64];
934   len = MIN (ARRAY_LENGTH (buf) - 1, len);
935   strncpy (buf, s, len);
936   buf[len] = '\0';
937
938   char *end;
939   errno = 0;
940   unsigned long v = strtoul (buf, &end, base);
941   if (errno) return false;
942   if (*end) return false;
943   *out = v;
944   return true;
945 }
946
947
948 /* Vectorization */
949
950 struct HbOpOr
951 {
952   static const bool passthru_left = true;
953   static const bool passthru_right = true;
954   template <typename T> static void process (T &o, const T &a, const T &b) { o = a | b; }
955 };
956 struct HbOpAnd
957 {
958   static const bool passthru_left = false;
959   static const bool passthru_right = false;
960   template <typename T> static void process (T &o, const T &a, const T &b) { o = a & b; }
961 };
962 struct HbOpMinus
963 {
964   static const bool passthru_left = true;
965   static const bool passthru_right = false;
966   template <typename T> static void process (T &o, const T &a, const T &b) { o = a & ~b; }
967 };
968 struct HbOpXor
969 {
970   static const bool passthru_left = true;
971   static const bool passthru_right = true;
972   template <typename T> static void process (T &o, const T &a, const T &b) { o = a ^ b; }
973 };
974
975 /* Type behaving similar to vectorized vars defined using __attribute__((vector_size(...))). */
976 template <typename elt_t, unsigned int byte_size>
977 struct hb_vector_size_t
978 {
979   elt_t& operator [] (unsigned int i) { return v[i]; }
980   const elt_t& operator [] (unsigned int i) const { return v[i]; }
981
982   template <class Op>
983   inline hb_vector_size_t process (const hb_vector_size_t &o) const
984   {
985     hb_vector_size_t r;
986     for (unsigned int i = 0; i < ARRAY_LENGTH (v); i++)
987       Op::process (r.v[i], v[i], o.v[i]);
988     return r;
989   }
990   inline hb_vector_size_t operator | (const hb_vector_size_t &o) const
991   { return process<HbOpOr> (o); }
992   inline hb_vector_size_t operator & (const hb_vector_size_t &o) const
993   { return process<HbOpAnd> (o); }
994   inline hb_vector_size_t operator ^ (const hb_vector_size_t &o) const
995   { return process<HbOpXor> (o); }
996   inline hb_vector_size_t operator ~ () const
997   {
998     hb_vector_size_t r;
999     for (unsigned int i = 0; i < ARRAY_LENGTH (v); i++)
1000       r.v[i] = ~v[i];
1001     return r;
1002   }
1003
1004   private:
1005   static_assert (byte_size / sizeof (elt_t) * sizeof (elt_t) == byte_size, "");
1006   elt_t v[byte_size / sizeof (elt_t)];
1007 };
1008
1009 /* The `vector_size' attribute was introduced in gcc 3.1. */
1010 #if defined( __GNUC__ ) && ( __GNUC__ >= 4 )
1011 #define HAVE_VECTOR_SIZE 1
1012 #endif
1013
1014
1015 /* Global runtime options. */
1016
1017 struct hb_options_t
1018 {
1019   unsigned int initialized : 1;
1020   unsigned int uniscribe_bug_compatible : 1;
1021 };
1022
1023 union hb_options_union_t {
1024   unsigned int i;
1025   hb_options_t opts;
1026 };
1027 static_assert ((sizeof (int) == sizeof (hb_options_union_t)), "");
1028
1029 HB_INTERNAL void
1030 _hb_options_init (void);
1031
1032 extern HB_INTERNAL hb_options_union_t _hb_options;
1033
1034 static inline hb_options_t
1035 hb_options (void)
1036 {
1037   if (unlikely (!_hb_options.i))
1038     _hb_options_init ();
1039
1040   return _hb_options.opts;
1041 }
1042
1043 /* Size signifying variable-sized array */
1044 #define VAR 1
1045
1046
1047 /* String type. */
1048
1049 struct hb_string_t
1050 {
1051   inline hb_string_t (void) : bytes (nullptr), len (0) {}
1052   inline hb_string_t (const char *bytes_, unsigned int len_) : bytes (bytes_), len (len_) {}
1053
1054   inline int cmp (const hb_string_t &a) const
1055   {
1056     if (len != a.len)
1057       return (int) a.len - (int) len;
1058
1059     return memcmp (a.bytes, bytes, len);
1060   }
1061   static inline int cmp (const void *pa, const void *pb)
1062   {
1063     hb_string_t *a = (hb_string_t *) pa;
1064     hb_string_t *b = (hb_string_t *) pb;
1065     return b->cmp (*a);
1066   }
1067
1068   const char *bytes;
1069   unsigned int len;
1070 };
1071
1072
1073 #endif /* HB_PRIVATE_HH */