90f28364019a8c60cdcbc991ffef875a60475530
[platform/upstream/harfbuzz.git] / src / hb-open-type-private.hh
1 /*
2  * Copyright © 2007,2008,2009,2010  Red Hat, Inc.
3  * Copyright © 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_OPEN_TYPE_PRIVATE_HH
30 #define HB_OPEN_TYPE_PRIVATE_HH
31
32 #include "hb-private.hh"
33
34 #include "hb-blob.h"
35
36
37 namespace OT {
38
39
40
41 /*
42  * Casts
43  */
44
45 /* Cast to struct T, reference to reference */
46 template<typename Type, typename TObject>
47 inline const Type& CastR(const TObject &X)
48 { return reinterpret_cast<const Type&> (X); }
49 template<typename Type, typename TObject>
50 inline Type& CastR(TObject &X)
51 { return reinterpret_cast<Type&> (X); }
52
53 /* Cast to struct T, pointer to pointer */
54 template<typename Type, typename TObject>
55 inline const Type* CastP(const TObject *X)
56 { return reinterpret_cast<const Type*> (X); }
57 template<typename Type, typename TObject>
58 inline Type* CastP(TObject *X)
59 { return reinterpret_cast<Type*> (X); }
60
61 /* StructAtOffset<T>(P,Ofs) returns the struct T& that is placed at memory
62  * location pointed to by P plus Ofs bytes. */
63 template<typename Type>
64 inline const Type& StructAtOffset(const void *P, unsigned int offset)
65 { return * reinterpret_cast<const Type*> ((const char *) P + offset); }
66 template<typename Type>
67 inline Type& StructAtOffset(void *P, unsigned int offset)
68 { return * reinterpret_cast<Type*> ((char *) P + offset); }
69
70 /* StructAfter<T>(X) returns the struct T& that is placed after X.
71  * Works with X of variable size also.  X must implement get_size() */
72 template<typename Type, typename TObject>
73 inline const Type& StructAfter(const TObject &X)
74 { return StructAtOffset<Type>(&X, X.get_size()); }
75 template<typename Type, typename TObject>
76 inline Type& StructAfter(TObject &X)
77 { return StructAtOffset<Type>(&X, X.get_size()); }
78
79
80
81 /*
82  * Size checking
83  */
84
85 /* Check _assertion in a method environment */
86 #define _DEFINE_INSTANCE_ASSERTION1(_line, _assertion) \
87   inline void _instance_assertion_on_line_##_line (void) const \
88   { \
89     ASSERT_STATIC (_assertion); \
90     ASSERT_INSTANCE_POD (*this); /* Make sure it's POD. */ \
91   }
92 # define _DEFINE_INSTANCE_ASSERTION0(_line, _assertion) _DEFINE_INSTANCE_ASSERTION1 (_line, _assertion)
93 # define DEFINE_INSTANCE_ASSERTION(_assertion) _DEFINE_INSTANCE_ASSERTION0 (__LINE__, _assertion)
94
95 /* Check that _code compiles in a method environment */
96 #define _DEFINE_COMPILES_ASSERTION1(_line, _code) \
97   inline void _compiles_assertion_on_line_##_line (void) const \
98   { _code; }
99 # define _DEFINE_COMPILES_ASSERTION0(_line, _code) _DEFINE_COMPILES_ASSERTION1 (_line, _code)
100 # define DEFINE_COMPILES_ASSERTION(_code) _DEFINE_COMPILES_ASSERTION0 (__LINE__, _code)
101
102
103 #define DEFINE_SIZE_STATIC(size) \
104   DEFINE_INSTANCE_ASSERTION (sizeof (*this) == (size)); \
105   static const unsigned int static_size = (size); \
106   static const unsigned int min_size = (size)
107
108 /* Size signifying variable-sized array */
109 #define VAR 1
110
111 #define DEFINE_SIZE_UNION(size, _member) \
112   DEFINE_INSTANCE_ASSERTION (this->u._member.static_size == (size)); \
113   static const unsigned int min_size = (size)
114
115 #define DEFINE_SIZE_MIN(size) \
116   DEFINE_INSTANCE_ASSERTION (sizeof (*this) >= (size)); \
117   static const unsigned int min_size = (size)
118
119 #define DEFINE_SIZE_ARRAY(size, array) \
120   DEFINE_INSTANCE_ASSERTION (sizeof (*this) == (size) + sizeof (array[0])); \
121   DEFINE_COMPILES_ASSERTION ((void) array[0].static_size) \
122   static const unsigned int min_size = (size)
123
124 #define DEFINE_SIZE_ARRAY2(size, array1, array2) \
125   DEFINE_INSTANCE_ASSERTION (sizeof (*this) == (size) + sizeof (this->array1[0]) + sizeof (this->array2[0])); \
126   DEFINE_COMPILES_ASSERTION ((void) array1[0].static_size; (void) array2[0].static_size) \
127   static const unsigned int min_size = (size)
128
129
130
131 /*
132  * Null objects
133  */
134
135 /* Global nul-content Null pool.  Enlarge as necessary. */
136 /* TODO This really should be a extern HB_INTERNAL and defined somewhere... */
137 static const void *_NullPool[64 / sizeof (void *)];
138
139 /* Generic nul-content Null objects. */
140 template <typename Type>
141 static inline const Type& Null (void) {
142   ASSERT_STATIC (sizeof (Type) <= sizeof (_NullPool));
143   return *CastP<Type> (_NullPool);
144 }
145
146 /* Specializaiton for arbitrary-content arbitrary-sized Null objects. */
147 #define DEFINE_NULL_DATA(Type, data) \
148 static const char _Null##Type[sizeof (Type) + 1] = data; /* +1 is for nul-termination in data */ \
149 template <> \
150 inline const Type& Null<Type> (void) { \
151   return *CastP<Type> (_Null##Type); \
152 } /* The following line really exists such that we end in a place needing semicolon */ \
153 ASSERT_STATIC (Type::min_size + 1 <= sizeof (_Null##Type))
154
155 /* Accessor macro. */
156 #define Null(Type) Null<Type>()
157
158
159
160 /*
161  * Sanitize
162  */
163
164 #ifndef HB_DEBUG_SANITIZE
165 #define HB_DEBUG_SANITIZE (HB_DEBUG+0)
166 #endif
167
168
169 #define TRACE_SANITIZE(this) \
170         hb_auto_trace_t<HB_DEBUG_SANITIZE, bool> trace \
171         (&c->debug_depth, c->get_name (), this, HB_FUNC, \
172          "");
173
174
175 struct hb_sanitize_context_t
176 {
177   inline const char *get_name (void) { return "SANITIZE"; }
178   static const unsigned int max_debug_depth = HB_DEBUG_SANITIZE;
179   typedef bool return_t;
180   template <typename T>
181   inline return_t process (const T &obj) { return obj.sanitize (this); }
182   static return_t default_return_value (void) { return true; }
183   bool stop_sublookup_iteration (const return_t r HB_UNUSED) const { return false; }
184
185   inline void init (hb_blob_t *b)
186   {
187     this->blob = hb_blob_reference (b);
188     this->writable = false;
189   }
190
191   inline void start_processing (void)
192   {
193     this->start = hb_blob_get_data (this->blob, NULL);
194     this->end = this->start + hb_blob_get_length (this->blob);
195     this->edit_count = 0;
196     this->debug_depth = 0;
197
198     DEBUG_MSG_LEVEL (SANITIZE, this->blob, 0, +1,
199                      "start [%p..%p] (%lu bytes)",
200                      this->start, this->end,
201                      (unsigned long) (this->end - this->start));
202   }
203
204   inline void end_processing (void)
205   {
206     DEBUG_MSG_LEVEL (SANITIZE, this->blob, 0, -1,
207                      "end [%p..%p] %u edit requests",
208                      this->start, this->end, this->edit_count);
209
210     hb_blob_destroy (this->blob);
211     this->blob = NULL;
212     this->start = this->end = NULL;
213   }
214
215   inline bool check_range (const void *base, unsigned int len) const
216   {
217     const char *p = (const char *) base;
218
219     hb_auto_trace_t<HB_DEBUG_SANITIZE, bool> trace
220       (&this->debug_depth, "SANITIZE", this->blob, NULL,
221        "check_range [%p..%p] (%d bytes) in [%p..%p]",
222        p, p + len, len,
223        this->start, this->end);
224
225     return TRACE_RETURN (likely (this->start <= p && p <= this->end && (unsigned int) (this->end - p) >= len));
226   }
227
228   inline bool check_array (const void *base, unsigned int record_size, unsigned int len) const
229   {
230     const char *p = (const char *) base;
231     bool overflows = _hb_unsigned_int_mul_overflows (len, record_size);
232
233     hb_auto_trace_t<HB_DEBUG_SANITIZE, bool> trace
234       (&this->debug_depth, "SANITIZE", this->blob, NULL,
235        "check_array [%p..%p] (%d*%d=%ld bytes) in [%p..%p]",
236        p, p + (record_size * len), record_size, len, (unsigned long) record_size * len,
237        this->start, this->end);
238
239     return TRACE_RETURN (likely (!overflows && this->check_range (base, record_size * len)));
240   }
241
242   template <typename Type>
243   inline bool check_struct (const Type *obj) const
244   {
245     return likely (this->check_range (obj, obj->min_size));
246   }
247
248   inline bool may_edit (const void *base HB_UNUSED, unsigned int len HB_UNUSED)
249   {
250     const char *p = (const char *) base;
251     this->edit_count++;
252
253     hb_auto_trace_t<HB_DEBUG_SANITIZE, bool> trace
254       (&this->debug_depth, "SANITIZE", this->blob, NULL,
255        "may_edit(%u) [%p..%p] (%d bytes) in [%p..%p] -> %s",
256        this->edit_count,
257        p, p + len, len,
258        this->start, this->end,
259        this->writable ? "GRANTED" : "DENIED");
260
261     return TRACE_RETURN (this->writable);
262   }
263
264   mutable unsigned int debug_depth;
265   const char *start, *end;
266   bool writable;
267   unsigned int edit_count;
268   hb_blob_t *blob;
269 };
270
271
272
273 /* Template to sanitize an object. */
274 template <typename Type>
275 struct Sanitizer
276 {
277   static hb_blob_t *sanitize (hb_blob_t *blob) {
278     hb_sanitize_context_t c[1] = {{0}};
279     bool sane;
280
281     /* TODO is_sane() stuff */
282
283     c->init (blob);
284
285   retry:
286     DEBUG_MSG_FUNC (SANITIZE, blob, "start");
287
288     c->start_processing ();
289
290     if (unlikely (!c->start)) {
291       c->end_processing ();
292       return blob;
293     }
294
295     Type *t = CastP<Type> (const_cast<char *> (c->start));
296
297     sane = t->sanitize (c);
298     if (sane) {
299       if (c->edit_count) {
300         DEBUG_MSG_FUNC (SANITIZE, blob, "passed first round with %d edits; going for second round", c->edit_count);
301
302         /* sanitize again to ensure no toe-stepping */
303         c->edit_count = 0;
304         sane = t->sanitize (c);
305         if (c->edit_count) {
306           DEBUG_MSG_FUNC (SANITIZE, blob, "requested %d edits in second round; FAILLING", c->edit_count);
307           sane = false;
308         }
309       }
310     } else {
311       unsigned int edit_count = c->edit_count;
312       if (edit_count && !c->writable) {
313         c->start = hb_blob_get_data_writable (blob, NULL);
314         c->end = c->start + hb_blob_get_length (blob);
315
316         if (c->start) {
317           c->writable = true;
318           /* ok, we made it writable by relocating.  try again */
319           DEBUG_MSG_FUNC (SANITIZE, blob, "retry");
320           goto retry;
321         }
322       }
323     }
324
325     c->end_processing ();
326
327     DEBUG_MSG_FUNC (SANITIZE, blob, sane ? "PASSED" : "FAILED");
328     if (sane)
329       return blob;
330     else {
331       hb_blob_destroy (blob);
332       return hb_blob_get_empty ();
333     }
334   }
335
336   static const Type* lock_instance (hb_blob_t *blob) {
337     hb_blob_make_immutable (blob);
338     const char *base = hb_blob_get_data (blob, NULL);
339     return unlikely (!base) ? &Null(Type) : CastP<Type> (base);
340   }
341 };
342
343
344
345 /*
346  * Serialize
347  */
348
349 #ifndef HB_DEBUG_SERIALIZE
350 #define HB_DEBUG_SERIALIZE (HB_DEBUG+0)
351 #endif
352
353
354 #define TRACE_SERIALIZE(this) \
355         hb_auto_trace_t<HB_DEBUG_SERIALIZE, bool> trace \
356         (&c->debug_depth, "SERIALIZE", c, HB_FUNC, \
357          "");
358
359
360 struct hb_serialize_context_t
361 {
362   inline hb_serialize_context_t (void *start, unsigned int size)
363   {
364     this->start = (char *) start;
365     this->end = this->start + size;
366
367     this->ran_out_of_room = false;
368     this->head = this->start;
369     this->debug_depth = 0;
370   }
371
372   template <typename Type>
373   inline Type *start_serialize (void)
374   {
375     DEBUG_MSG_LEVEL (SERIALIZE, this->start, 0, +1,
376                      "start [%p..%p] (%lu bytes)",
377                      this->start, this->end,
378                      (unsigned long) (this->end - this->start));
379
380     return start_embed<Type> ();
381   }
382
383   inline void end_serialize (void)
384   {
385     DEBUG_MSG_LEVEL (SERIALIZE, this->start, 0, -1,
386                      "end [%p..%p] serialized %d bytes; %s",
387                      this->start, this->end,
388                      (int) (this->head - this->start),
389                      this->ran_out_of_room ? "RAN OUT OF ROOM" : "did not ran out of room");
390
391   }
392
393   template <typename Type>
394   inline Type *copy (void)
395   {
396     assert (!this->ran_out_of_room);
397     unsigned int len = this->head - this->start;
398     void *p = malloc (len);
399     if (p)
400       memcpy (p, this->start, len);
401     return reinterpret_cast<Type *> (p);
402   }
403
404   template <typename Type>
405   inline Type *allocate_size (unsigned int size)
406   {
407     if (unlikely (this->ran_out_of_room || this->end - this->head < size)) {
408       this->ran_out_of_room = true;
409       return NULL;
410     }
411     memset (this->head, 0, size);
412     char *ret = this->head;
413     this->head += size;
414     return reinterpret_cast<Type *> (ret);
415   }
416
417   template <typename Type>
418   inline Type *allocate_min (void)
419   {
420     return this->allocate_size<Type> (Type::min_size);
421   }
422
423   template <typename Type>
424   inline Type *start_embed (void)
425   {
426     Type *ret = reinterpret_cast<Type *> (this->head);
427     return ret;
428   }
429
430   template <typename Type>
431   inline Type *embed (const Type &obj)
432   {
433     unsigned int size = obj.get_size ();
434     Type *ret = this->allocate_size<Type> (size);
435     if (unlikely (!ret)) return NULL;
436     memcpy (ret, obj, size);
437     return ret;
438   }
439
440   template <typename Type>
441   inline Type *extend_min (Type &obj)
442   {
443     unsigned int size = obj.min_size;
444     assert (this->start <= (char *) &obj && (char *) &obj <= this->head && (char *) &obj + size >= this->head);
445     if (unlikely (!this->allocate_size<Type> (((char *) &obj) + size - this->head))) return NULL;
446     return reinterpret_cast<Type *> (&obj);
447   }
448
449   template <typename Type>
450   inline Type *extend (Type &obj)
451   {
452     unsigned int size = obj.get_size ();
453     assert (this->start < (char *) &obj && (char *) &obj <= this->head && (char *) &obj + size >= this->head);
454     if (unlikely (!this->allocate_size<Type> (((char *) &obj) + size - this->head))) return NULL;
455     return reinterpret_cast<Type *> (&obj);
456   }
457
458   inline void truncate (void *head)
459   {
460     assert (this->start < head && head <= this->head);
461     this->head = (char *) head;
462   }
463
464   unsigned int debug_depth;
465   char *start, *end, *head;
466   bool ran_out_of_room;
467 };
468
469 template <typename Type>
470 struct Supplier
471 {
472   inline Supplier (const Type *array, unsigned int len_)
473   {
474     head = array;
475     len = len_;
476   }
477   inline const Type operator [] (unsigned int i) const
478   {
479     if (unlikely (i >= len)) return Type ();
480     return head[i];
481   }
482
483   inline void advance (unsigned int count)
484   {
485     if (unlikely (count > len))
486       count = len;
487     len -= count;
488     head += count;
489   }
490
491   private:
492   inline Supplier (const Supplier<Type> &); /* Disallow copy */
493   inline Supplier<Type>& operator= (const Supplier<Type> &); /* Disallow copy */
494
495   unsigned int len;
496   const Type *head;
497 };
498
499
500
501
502 /*
503  *
504  * The OpenType Font File: Data Types
505  */
506
507
508 /* "The following data types are used in the OpenType font file.
509  *  All OpenType fonts use Motorola-style byte ordering (Big Endian):" */
510
511 /*
512  * Int types
513  */
514
515
516 template <typename Type, int Bytes> struct BEInt;
517
518 template <typename Type>
519 struct BEInt<Type, 2>
520 {
521   public:
522   inline void set (Type i) { hb_be_uint16_put (v,i); }
523   inline operator Type (void) const { return hb_be_uint16_get (v); }
524   inline bool operator == (const BEInt<Type, 2>& o) const { return hb_be_uint16_eq (v, o.v); }
525   inline bool operator != (const BEInt<Type, 2>& o) const { return !(*this == o); }
526   private: uint8_t v[2];
527 };
528 template <typename Type>
529 struct BEInt<Type, 4>
530 {
531   public:
532   inline void set (Type i) { hb_be_uint32_put (v,i); }
533   inline operator Type (void) const { return hb_be_uint32_get (v); }
534   inline bool operator == (const BEInt<Type, 4>& o) const { return hb_be_uint32_eq (v, o.v); }
535   inline bool operator != (const BEInt<Type, 4>& o) const { return !(*this == o); }
536   private: uint8_t v[4];
537 };
538 template <typename Type>
539 struct BEInt<Type, 3>
540 {
541   public:
542   inline void set (Type i) { hb_be_uint24_put (v,i); }
543   inline operator Type (void) const { return hb_be_uint24_get (v); }
544   inline bool operator == (const BEInt<Type, 3>& o) const { return hb_be_uint24_eq (v, o.v); }
545   inline bool operator != (const BEInt<Type, 3>& o) const { return !(*this == o); }
546   private: uint8_t v[3];
547 };
548
549 /* Integer types in big-endian order and no alignment requirement */
550 template <typename Type, unsigned int Size>
551 struct IntType
552 {
553   inline void set (Type i) { v.set (i); }
554   inline operator Type(void) const { return v; }
555   inline bool operator == (const IntType<Type,Size> &o) const { return v == o.v; }
556   inline bool operator != (const IntType<Type,Size> &o) const { return v != o.v; }
557   static inline int cmp (const IntType<Type,Size> *a, const IntType<Type,Size> *b) { return b->cmp (*a); }
558   inline int cmp (IntType<Type,Size> va) const { Type a = va; Type b = v; return a < b ? -1 : a == b ? 0 : +1; }
559   inline int cmp (Type a) const { Type b = v; return a < b ? -1 : a == b ? 0 : +1; }
560   inline bool sanitize (hb_sanitize_context_t *c) {
561     TRACE_SANITIZE (this);
562     return TRACE_RETURN (likely (c->check_struct (this)));
563   }
564   protected:
565   BEInt<Type, Size> v;
566   public:
567   DEFINE_SIZE_STATIC (Size);
568 };
569
570 typedef IntType<uint16_t, 2> USHORT;    /* 16-bit unsigned integer. */
571 typedef IntType<int16_t,  2> SHORT;     /* 16-bit signed integer. */
572 typedef IntType<uint32_t, 4> ULONG;     /* 32-bit unsigned integer. */
573 typedef IntType<int32_t,  4> LONG;      /* 32-bit signed integer. */
574 typedef IntType<uint32_t, 3> UINT24;    /* 24-bit unsigned integer. */
575
576 /* 16-bit signed integer (SHORT) that describes a quantity in FUnits. */
577 typedef SHORT FWORD;
578
579 /* 16-bit unsigned integer (USHORT) that describes a quantity in FUnits. */
580 typedef USHORT UFWORD;
581
582 /* Date represented in number of seconds since 12:00 midnight, January 1,
583  * 1904. The value is represented as a signed 64-bit integer. */
584 struct LONGDATETIME
585 {
586   inline bool sanitize (hb_sanitize_context_t *c) {
587     TRACE_SANITIZE (this);
588     return TRACE_RETURN (likely (c->check_struct (this)));
589   }
590   private:
591   LONG major;
592   ULONG minor;
593   public:
594   DEFINE_SIZE_STATIC (8);
595 };
596
597 /* Array of four uint8s (length = 32 bits) used to identify a script, language
598  * system, feature, or baseline */
599 struct Tag : ULONG
600 {
601   /* What the char* converters return is NOT nul-terminated.  Print using "%.4s" */
602   inline operator const char* (void) const { return reinterpret_cast<const char *> (&this->v); }
603   inline operator char* (void) { return reinterpret_cast<char *> (&this->v); }
604   public:
605   DEFINE_SIZE_STATIC (4);
606 };
607 DEFINE_NULL_DATA (Tag, "    ");
608
609 /* Glyph index number, same as uint16 (length = 16 bits) */
610 typedef USHORT GlyphID;
611
612 /* Script/language-system/feature index */
613 struct Index : USHORT {
614   static const unsigned int NOT_FOUND_INDEX = 0xFFFF;
615 };
616 DEFINE_NULL_DATA (Index, "\xff\xff");
617
618 /* Offset to a table, same as uint16 (length = 16 bits), Null offset = 0x0000 */
619 struct Offset : USHORT
620 {
621   inline bool is_null (void) const { return 0 == *this; }
622   public:
623   DEFINE_SIZE_STATIC (2);
624 };
625
626 /* LongOffset to a table, same as uint32 (length = 32 bits), Null offset = 0x00000000 */
627 struct LongOffset : ULONG
628 {
629   inline bool is_null (void) const { return 0 == *this; }
630   public:
631   DEFINE_SIZE_STATIC (4);
632 };
633
634
635 /* CheckSum */
636 struct CheckSum : ULONG
637 {
638   static uint32_t CalcTableChecksum (ULONG *Table, uint32_t Length)
639   {
640     uint32_t Sum = 0L;
641     ULONG *EndPtr = Table+((Length+3) & ~3) / ULONG::static_size;
642
643     while (Table < EndPtr)
644       Sum += *Table++;
645     return Sum;
646   }
647   public:
648   DEFINE_SIZE_STATIC (4);
649 };
650
651
652 /*
653  * Version Numbers
654  */
655
656 struct FixedVersion
657 {
658   inline uint32_t to_int (void) const { return (major << 16) + minor; }
659
660   inline bool sanitize (hb_sanitize_context_t *c) {
661     TRACE_SANITIZE (this);
662     return TRACE_RETURN (c->check_struct (this));
663   }
664
665   USHORT major;
666   USHORT minor;
667   public:
668   DEFINE_SIZE_STATIC (4);
669 };
670
671
672
673 /*
674  * Template subclasses of Offset and LongOffset that do the dereferencing.
675  * Use: (base+offset)
676  */
677
678 template <typename OffsetType, typename Type>
679 struct GenericOffsetTo : OffsetType
680 {
681   inline const Type& operator () (const void *base) const
682   {
683     unsigned int offset = *this;
684     if (unlikely (!offset)) return Null(Type);
685     return StructAtOffset<Type> (base, offset);
686   }
687   inline Type& operator () (void *base)
688   {
689     unsigned int offset = *this;
690     return StructAtOffset<Type> (base, offset);
691   }
692
693   inline Type& serialize (hb_serialize_context_t *c, void *base)
694   {
695     Type *t = c->start_embed<Type> ();
696     this->set ((char *) t - (char *) base); /* TODO(serialize) Overflow? */
697     return *t;
698   }
699
700   inline bool sanitize (hb_sanitize_context_t *c, void *base) {
701     TRACE_SANITIZE (this);
702     if (unlikely (!c->check_struct (this))) return TRACE_RETURN (false);
703     unsigned int offset = *this;
704     if (unlikely (!offset)) return TRACE_RETURN (true);
705     Type &obj = StructAtOffset<Type> (base, offset);
706     return TRACE_RETURN (likely (obj.sanitize (c)) || neuter (c));
707   }
708   template <typename T>
709   inline bool sanitize (hb_sanitize_context_t *c, void *base, T user_data) {
710     TRACE_SANITIZE (this);
711     if (unlikely (!c->check_struct (this))) return TRACE_RETURN (false);
712     unsigned int offset = *this;
713     if (unlikely (!offset)) return TRACE_RETURN (true);
714     Type &obj = StructAtOffset<Type> (base, offset);
715     return TRACE_RETURN (likely (obj.sanitize (c, user_data)) || neuter (c));
716   }
717
718   inline bool try_set (hb_sanitize_context_t *c, const OffsetType &v) {
719     if (c->may_edit (this, this->static_size)) {
720       this->set (v);
721       return true;
722     }
723     return false;
724   }
725   /* Set the offset to Null */
726   inline bool neuter (hb_sanitize_context_t *c) {
727     if (c->may_edit (this, this->static_size)) {
728       this->set (0); /* 0 is Null offset */
729       return true;
730     }
731     return false;
732   }
733 };
734 template <typename Base, typename OffsetType, typename Type>
735 inline const Type& operator + (const Base &base, const GenericOffsetTo<OffsetType, Type> &offset) { return offset (base); }
736 template <typename Base, typename OffsetType, typename Type>
737 inline Type& operator + (Base &base, GenericOffsetTo<OffsetType, Type> &offset) { return offset (base); }
738
739 template <typename Type>
740 struct OffsetTo : GenericOffsetTo<Offset, Type> {};
741
742 template <typename Type>
743 struct LongOffsetTo : GenericOffsetTo<LongOffset, Type> {};
744
745
746 /*
747  * Array Types
748  */
749
750 template <typename LenType, typename Type>
751 struct GenericArrayOf
752 {
753   const Type *sub_array (unsigned int start_offset, unsigned int *pcount /* IN/OUT */) const
754   {
755     unsigned int count = len;
756     if (unlikely (start_offset > count))
757       count = 0;
758     else
759       count -= start_offset;
760     count = MIN (count, *pcount);
761     *pcount = count;
762     return array + start_offset;
763   }
764
765   inline const Type& operator [] (unsigned int i) const
766   {
767     if (unlikely (i >= len)) return Null(Type);
768     return array[i];
769   }
770   inline Type& operator [] (unsigned int i)
771   {
772     return array[i];
773   }
774   inline unsigned int get_size (void) const
775   { return len.static_size + len * Type::static_size; }
776
777   inline bool serialize (hb_serialize_context_t *c,
778                          unsigned int items_len)
779   {
780     TRACE_SERIALIZE (this);
781     if (unlikely (!c->extend_min (*this))) return TRACE_RETURN (false);
782     len.set (items_len); /* TODO(serialize) Overflow? */
783     if (unlikely (!c->extend (*this))) return TRACE_RETURN (false);
784     return TRACE_RETURN (true);
785   }
786
787   inline bool serialize (hb_serialize_context_t *c,
788                          Supplier<Type> &items,
789                          unsigned int items_len)
790   {
791     TRACE_SERIALIZE (this);
792     if (unlikely (!serialize (c, items_len))) return TRACE_RETURN (false);
793     for (unsigned int i = 0; i < items_len; i++)
794       array[i] = items[i];
795     items.advance (items_len);
796     return TRACE_RETURN (true);
797   }
798
799   inline bool sanitize (hb_sanitize_context_t *c) {
800     TRACE_SANITIZE (this);
801     if (unlikely (!sanitize_shallow (c))) return TRACE_RETURN (false);
802
803     /* Note: for structs that do not reference other structs,
804      * we do not need to call their sanitize() as we already did
805      * a bound check on the aggregate array size.  We just include
806      * a small unreachable expression to make sure the structs
807      * pointed to do have a simple sanitize(), ie. they do not
808      * reference other structs via offsets.
809      */
810     (void) (false && array[0].sanitize (c));
811
812     return TRACE_RETURN (true);
813   }
814   inline bool sanitize (hb_sanitize_context_t *c, void *base) {
815     TRACE_SANITIZE (this);
816     if (unlikely (!sanitize_shallow (c))) return TRACE_RETURN (false);
817     unsigned int count = len;
818     for (unsigned int i = 0; i < count; i++)
819       if (unlikely (!array[i].sanitize (c, base)))
820         return TRACE_RETURN (false);
821     return TRACE_RETURN (true);
822   }
823   template <typename T>
824   inline bool sanitize (hb_sanitize_context_t *c, void *base, T user_data) {
825     TRACE_SANITIZE (this);
826     if (unlikely (!sanitize_shallow (c))) return TRACE_RETURN (false);
827     unsigned int count = len;
828     for (unsigned int i = 0; i < count; i++)
829       if (unlikely (!array[i].sanitize (c, base, user_data)))
830         return TRACE_RETURN (false);
831     return TRACE_RETURN (true);
832   }
833
834   private:
835   inline bool sanitize_shallow (hb_sanitize_context_t *c) {
836     TRACE_SANITIZE (this);
837     return TRACE_RETURN (c->check_struct (this) && c->check_array (this, Type::static_size, len));
838   }
839
840   public:
841   LenType len;
842   Type array[VAR];
843   public:
844   DEFINE_SIZE_ARRAY (sizeof (LenType), array);
845 };
846
847 /* An array with a USHORT number of elements. */
848 template <typename Type>
849 struct ArrayOf : GenericArrayOf<USHORT, Type> {};
850
851 /* An array with a ULONG number of elements. */
852 template <typename Type>
853 struct LongArrayOf : GenericArrayOf<ULONG, Type> {};
854
855 /* Array of Offset's */
856 template <typename Type>
857 struct OffsetArrayOf : ArrayOf<OffsetTo<Type> > {};
858
859 /* Array of LongOffset's */
860 template <typename Type>
861 struct LongOffsetArrayOf : ArrayOf<LongOffsetTo<Type> > {};
862
863 /* LongArray of LongOffset's */
864 template <typename Type>
865 struct LongOffsetLongArrayOf : LongArrayOf<LongOffsetTo<Type> > {};
866
867 /* Array of offsets relative to the beginning of the array itself. */
868 template <typename Type>
869 struct OffsetListOf : OffsetArrayOf<Type>
870 {
871   inline const Type& operator [] (unsigned int i) const
872   {
873     if (unlikely (i >= this->len)) return Null(Type);
874     return this+this->array[i];
875   }
876
877   inline bool sanitize (hb_sanitize_context_t *c) {
878     TRACE_SANITIZE (this);
879     return TRACE_RETURN (OffsetArrayOf<Type>::sanitize (c, this));
880   }
881   template <typename T>
882   inline bool sanitize (hb_sanitize_context_t *c, T user_data) {
883     TRACE_SANITIZE (this);
884     return TRACE_RETURN (OffsetArrayOf<Type>::sanitize (c, this, user_data));
885   }
886 };
887
888
889 /* An array with a USHORT number of elements,
890  * starting at second element. */
891 template <typename Type>
892 struct HeadlessArrayOf
893 {
894   inline const Type& operator [] (unsigned int i) const
895   {
896     if (unlikely (i >= len || !i)) return Null(Type);
897     return array[i-1];
898   }
899   inline unsigned int get_size (void) const
900   { return len.static_size + (len ? len - 1 : 0) * Type::static_size; }
901
902   inline bool serialize (hb_serialize_context_t *c,
903                          Supplier<Type> &items,
904                          unsigned int items_len)
905   {
906     TRACE_SERIALIZE (this);
907     if (unlikely (!c->extend_min (*this))) return TRACE_RETURN (false);
908     len.set (items_len); /* TODO(serialize) Overflow? */
909     if (unlikely (!items_len)) return TRACE_RETURN (true);
910     if (unlikely (!c->extend (*this))) return TRACE_RETURN (false);
911     for (unsigned int i = 0; i < items_len - 1; i++)
912       array[i] = items[i];
913     items.advance (items_len - 1);
914     return TRACE_RETURN (true);
915   }
916
917   inline bool sanitize_shallow (hb_sanitize_context_t *c) {
918     return c->check_struct (this)
919         && c->check_array (this, Type::static_size, len);
920   }
921
922   inline bool sanitize (hb_sanitize_context_t *c) {
923     TRACE_SANITIZE (this);
924     if (unlikely (!sanitize_shallow (c))) return TRACE_RETURN (false);
925
926     /* Note: for structs that do not reference other structs,
927      * we do not need to call their sanitize() as we already did
928      * a bound check on the aggregate array size.  We just include
929      * a small unreachable expression to make sure the structs
930      * pointed to do have a simple sanitize(), ie. they do not
931      * reference other structs via offsets.
932      */
933     (void) (false && array[0].sanitize (c));
934
935     return TRACE_RETURN (true);
936   }
937
938   USHORT len;
939   Type array[VAR];
940   public:
941   DEFINE_SIZE_ARRAY (sizeof (USHORT), array);
942 };
943
944
945 /* An array with sorted elements.  Supports binary searching. */
946 template <typename Type>
947 struct SortedArrayOf : ArrayOf<Type> {
948
949   template <typename SearchType>
950   inline int search (const SearchType &x) const {
951     unsigned int count = this->len;
952     /* Linear search is *much* faster for small counts. */
953     if (likely (count < 32)) {
954       for (unsigned int i = 0; i < count; i++)
955         if (this->array[i].cmp (x) == 0)
956           return i;
957       return -1;
958     } else {
959       struct Cmp {
960         static int cmp (const SearchType *a, const Type *b) { return b->cmp (*a); }
961       };
962       const Type *p = (const Type *) bsearch (&x, this->array, this->len, sizeof (this->array[0]), (hb_compare_func_t) Cmp::cmp);
963       return p ? p - this->array : -1;
964     }
965   }
966 };
967
968
969 } /* namespace OT */
970
971
972 #endif /* HB_OPEN_TYPE_PRIVATE_HH */