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