1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use truetype::GlyphID;

use crate::layout::Correction;
use crate::Result;

/// An anchor.
#[derive(Clone, Debug)]
pub enum Anchor {
    /// Format 1.
    Format1(Anchor1),
    /// Format 2.
    Format2(Anchor2),
    /// Format 3.
    Format3(Anchor3),
}

table! {
    /// An anchor in format 1.
    #[derive(Copy)]
    pub Anchor1 { // AnchorFormat1
        format (u16), // anchorFormat
        x      (i16), // xCoordinate
        y      (i16), // yCoordinate
    }
}

table! {
    /// An anchor in format 2.
    #[derive(Copy)]
    pub Anchor2 { // AnchorFormat2
        format (u16), // anchorFormat
        x      (i16), // xCoordinate
        y      (i16), // yCoordinate
        index  (u16), // anchorPoint
    }
}

table! {
    @position
    /// An anchor in format 3.
    pub Anchor3 { // AnchorFormat3
        format              (u16), // anchorFormat
        x                   (i16), // xCoordinate
        y                   (i16), // yCoordinate
        x_correction_offset (u16), // xDeviceOffset
        y_correction_offset (u16), // yDeviceOffset

        x_correction (Option<Correction>) |this, tape, position| {
            jump_take_maybe!(tape, position, this.x_correction_offset)
        },

        y_correction (Option<Correction>) |this, tape, position| {
            jump_take_maybe!(tape, position, this.y_correction_offset)
        },
    }
}

table! {
    @define
    /// A base.
    pub Base { // BaseRecord
        anchor_offsets (Vec<u16>), // baseAnchorOffsets

        anchors (Vec<Option<Anchor>>),
    }
}

table! {
    @define
    /// Bases.
    pub Bases { // BaseArray
        count   (u16      ), // baseCount
        records (Vec<Base>), // baseRecords
    }
}

table! {
    @define
    /// A component.
    pub Component { // ComponentRecord
        anchor_offsets (Vec<u16>), // ligatureAnchorOffsets

        anchors (Vec<Option<Anchor>>),
    }
}

table! {
    @define
    /// A connection.
    pub Connection { // EntryExitRecord
        start_anchor_offset (u16), // entryAnchorOffset
        end_anchor_offset   (u16), // exitAnchorOffset

        start_anchor (Option<Anchor>),
        end_anchor   (Option<Anchor>),
    }
}

table! {
    @define
    /// A ligature.
    pub Ligature { // LigatureAttach
        count      (u16           ), // componentCount
        components (Vec<Component>), // componentRecords
    }
}

table! {
    @define
    /// Ligatures.
    pub Ligatures { // LigatureArray
        count   (u16     ), // ligatureCount
        offsets (Vec<u16>), // ligatureAttachOffsets

        records (Vec<Ligature>),
    }
}

table! {
    @define
    /// A mark in format 1.
    pub Mark1 { // MarkRecord
        class_id      (u16), // markClass
        anchor_offset (u16), // markAnchorOffset

        anchor (Anchor),
    }
}

table! {
    @position
    /// Marks in format 1.
    pub Mark1s { // MarkArray
        count (u16), // markCount

        records (Vec<Mark1>) |this, tape, position| { // markRecords
            (0..this.count).map(|_| tape.take_given(position)).collect()
        },
    }
}

table! {
    @define
    /// A mark in format 2.
    pub Mark2 { // Mark2Record
        anchor_offsets (Vec<u16>), // mark2AnchorOffsets

        anchors (Vec<Option<Anchor>>),
    }
}

table! {
    @define
    /// Marks in format 2.
    pub Mark2s { // Mark2Array
        count   (u16       ), // mark2Count
        records (Vec<Mark2>), // mark2Records
    }
}

table! {
    @define
    /// A value pair in format 1.
    pub Pair1 { // PairValueRecord
        glyph2_id (GlyphID       ), // secondGlyph
        value1    (Option<Single>), // valueRecord1
        value2    (Option<Single>), // valueRecord2
    }
}

table! {
    @define
    /// Pairs of values in format 1.
    pub Pair1s { // PairSet
        count   (u16       ), // pairValueCount
        records (Vec<Pair1>), // pairValueRecords
    }
}

table! {
    @define
    /// A value pair in format 2.
    pub Pair2 { // Class2Record
        value1 (Option<Single>), // valueRecord1
        value2 (Option<Single>), // valueRecord2
    }
}

table! {
    @define
    /// Value pairs in format 2.
    pub Pair2s { // Class1Record
        records (Vec<Pair2>), // class2Records
    }
}

table! {
    @define
    /// A single value.
    pub Single { // ValueRecord
        x_placement                   (Option<i16>), // xPlacement
        y_placement                   (Option<i16>), // yPlacement
        x_advance                     (Option<i16>), // xAdvance
        y_advance                     (Option<i16>), // yAdvance
        x_placement_correction_offset (Option<u16>), // xPlaDeviceOffset
        y_placement_correction_offset (Option<u16>), // yPlaDeviceOffset
        x_advance_correction_offset   (Option<u16>), // xAdvDeviceOffset
        y_advance_correction_offset   (Option<u16>), // yAdvDeviceOffset

        x_placement_correction (Option<Correction>),
        y_placement_correction (Option<Correction>),
        x_advance_correction   (Option<Correction>),
        y_advance_correction   (Option<Correction>),
    }
}

flags! {
    /// Adjustment flags.
    pub Flags(u16) { // ValueFormat
        0b0000_0000_0000_0001 => has_x_placement,
        0b0000_0000_0000_0010 => has_y_placement,
        0b0000_0000_0000_0100 => has_x_advance,
        0b0000_0000_0000_1000 => has_y_advance,
        0b0000_0000_0001_0000 => has_x_placement_correction,
        0b0000_0000_0010_0000 => has_y_placement_correction,
        0b0000_0000_0100_0000 => has_x_advance_correction,
        0b0000_0000_1000_0000 => has_y_advance_correction,
        0b1111_1111_0000_0000 => is_invalid,
    }
}

impl Default for Anchor {
    #[inline]
    fn default() -> Self {
        Anchor::Format1(Anchor1::default())
    }
}

impl crate::value::Read for Anchor {
    fn read<T: crate::tape::Read>(tape: &mut T) -> Result<Self> {
        Ok(match tape.peek::<u16>()? {
            1 => Anchor::Format1(tape.take()?),
            2 => Anchor::Format2(tape.take()?),
            3 => Anchor::Format3(tape.take()?),
            value => raise!("found an unknown format of the anchor table ({value})"),
        })
    }
}

impl crate::walue::Read<'static> for Base {
    type Parameter = (u64, u16);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, mark_class_count): Self::Parameter,
    ) -> Result<Self> {
        let anchor_offsets: Vec<u16> = tape.take_given(mark_class_count as usize)?;
        let anchors =
            tape.stay(|tape| jump_take_maybe!(tape, position, mark_class_count, anchor_offsets))?;
        Ok(Self {
            anchor_offsets,
            anchors,
        })
    }
}

impl crate::walue::Read<'static> for Bases {
    type Parameter = u16;

    fn read<T: crate::tape::Read>(tape: &mut T, mark_class_count: Self::Parameter) -> Result<Self> {
        let position = tape.position()?;
        let count = tape.take()?;
        let records = (0..count)
            .map(|_| tape.take_given((position, mark_class_count)))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { count, records })
    }
}

impl crate::walue::Read<'static> for Component {
    type Parameter = (u64, u16);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, mark_class_count): Self::Parameter,
    ) -> Result<Self> {
        let anchor_offsets: Vec<u16> = tape.take_given(mark_class_count as usize)?;
        let anchors =
            tape.stay(|tape| jump_take_maybe!(tape, position, mark_class_count, anchor_offsets))?;
        Ok(Self {
            anchor_offsets,
            anchors,
        })
    }
}

impl crate::walue::Read<'static> for Ligature {
    type Parameter = u16;

    fn read<T: crate::tape::Read>(tape: &mut T, mark_class_count: Self::Parameter) -> Result<Self> {
        let position = tape.position()?;
        let count = tape.take()?;
        let components = (0..count)
            .map(|_| tape.take_given((position, mark_class_count)))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { count, components })
    }
}

impl crate::walue::Read<'static> for Ligatures {
    type Parameter = u16;

    fn read<T: crate::tape::Read>(tape: &mut T, mark_class_count: Self::Parameter) -> Result<Self> {
        let position = tape.position()?;
        let count = tape.take()?;
        let offsets: Vec<u16> = tape.take_given(count as usize)?;
        let records =
            tape.stay(|tape| jump_take_given!(tape, position, count, offsets, mark_class_count))?;
        Ok(Self {
            count,
            offsets,
            records,
        })
    }
}

impl crate::walue::Read<'static> for Mark1 {
    type Parameter = u64;

    fn read<T: crate::tape::Read>(tape: &mut T, position: Self::Parameter) -> Result<Self> {
        let class_id = tape.take()?;
        let anchor_offset = tape.take()?;
        #[cfg(not(feature = "ignore-incomplete-marks"))]
        let anchor = tape.stay(|tape| jump_take!(tape, position, anchor_offset))?;
        #[cfg(feature = "ignore-incomplete-marks")]
        let anchor = tape
            .stay(|tape| jump_take_maybe!(tape, position, anchor_offset))?
            .unwrap_or_default();
        Ok(Self {
            class_id,
            anchor_offset,
            anchor,
        })
    }
}

impl crate::walue::Read<'static> for Mark2 {
    type Parameter = (u64, u16);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, mark_class_count): Self::Parameter,
    ) -> Result<Self> {
        let anchor_offsets: Vec<u16> = tape.take_given(mark_class_count as usize)?;
        let anchors =
            tape.stay(|tape| jump_take_maybe!(tape, position, mark_class_count, anchor_offsets))?;
        Ok(Self {
            anchor_offsets,
            anchors,
        })
    }
}

impl crate::walue::Read<'static> for Mark2s {
    type Parameter = u16;

    fn read<T: crate::tape::Read>(tape: &mut T, mark_class_count: Self::Parameter) -> Result<Self> {
        let position = tape.position()?;
        let count = tape.take()?;
        let records = (0..count)
            .map(|_| tape.take_given((position, mark_class_count)))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { count, records })
    }
}

impl crate::walue::Read<'static> for Pair1 {
    type Parameter = (u64, Flags, Flags);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, value1_flags, value2_flags): Self::Parameter,
    ) -> Result<Self> {
        Ok(Self {
            glyph2_id: tape.take()?,
            value1: if value1_flags.0 > 0 {
                Some(tape.take_given((position, value1_flags))?)
            } else {
                None
            },
            value2: if value2_flags.0 > 0 {
                Some(tape.take_given((position, value2_flags))?)
            } else {
                None
            },
        })
    }
}

impl crate::walue::Read<'static> for Pair1s {
    type Parameter = (Flags, Flags);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (value1_flags, value2_flags): Self::Parameter,
    ) -> Result<Self> {
        let position = tape.position()?;
        let count = tape.take()?;
        let records = (0..count)
            .map(|_| tape.take_given((position, value1_flags, value2_flags)))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { count, records })
    }
}

impl crate::walue::Read<'static> for Pair2 {
    type Parameter = (u64, Flags, Flags);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, value1_flags, value2_flags): Self::Parameter,
    ) -> Result<Self> {
        Ok(Self {
            value1: if value1_flags.0 > 0 {
                Some(tape.take_given((position, value1_flags))?)
            } else {
                None
            },
            value2: if value2_flags.0 > 0 {
                Some(tape.take_given((position, value2_flags))?)
            } else {
                None
            },
        })
    }
}

impl crate::walue::Read<'static> for Pair2s {
    type Parameter = (u64, u16, Flags, Flags);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, class2_count, value1_flags, value2_flags): Self::Parameter,
    ) -> Result<Self> {
        let records = (0..class2_count)
            .map(|_| tape.take_given((position, value1_flags, value2_flags)))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { records })
    }
}

impl crate::walue::Read<'static> for Connection {
    type Parameter = u64;

    fn read<T: crate::tape::Read>(tape: &mut T, position: u64) -> Result<Self> {
        let start_anchor_offset = tape.take()?;
        let end_anchor_offset = tape.take()?;
        let (start_anchor, end_anchor) = tape.stay(|tape| {
            Ok((
                jump_take_maybe!(@unwrap tape, position, start_anchor_offset),
                jump_take_maybe!(@unwrap tape, position, end_anchor_offset),
            ))
        })?;
        Ok(Self {
            start_anchor_offset,
            end_anchor_offset,
            start_anchor,
            end_anchor,
        })
    }
}

impl crate::walue::Read<'static> for Single {
    type Parameter = (u64, Flags);

    fn read<T: crate::tape::Read>(
        tape: &mut T,
        (position, flags): Self::Parameter,
    ) -> Result<Self> {
        macro_rules! take(
            ($flag:ident) => (if flags.$flag() { Some(tape.take()?) } else { None });
        );
        let x_placement = take!(has_x_placement);
        let y_placement = take!(has_y_placement);
        let x_advance = take!(has_x_advance);
        let y_advance = take!(has_y_advance);
        let x_placement_correction_offset = take!(has_x_placement_correction);
        let y_placement_correction_offset = take!(has_y_placement_correction);
        let x_advance_correction_offset = take!(has_x_advance_correction);
        let y_advance_correction_offset = take!(has_y_advance_correction);
        let (
            x_placement_correction,
            y_placement_correction,
            x_advance_correction,
            y_advance_correction,
        ) = tape.stay(|tape| {
            macro_rules! take(
                ($offset:ident) => (match $offset {
                    Some(offset) => jump_take_maybe!(@unwrap tape, position, offset),
                    _ => None,
                });
            );
            Ok((
                take!(x_placement_correction_offset),
                take!(y_placement_correction_offset),
                take!(x_advance_correction_offset),
                take!(y_advance_correction_offset),
            ))
        })?;
        Ok(Self {
            x_placement,
            y_placement,
            x_advance,
            y_advance,
            x_placement_correction_offset,
            y_placement_correction_offset,
            x_advance_correction_offset,
            y_advance_correction_offset,
            x_placement_correction,
            y_placement_correction,
            x_advance_correction,
            y_advance_correction,
        })
    }
}