fontcull-klippa 0.1.1

Subsetting a font file according to provided input. (Vendored fork for fontcull)
Documentation
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
//! serializer
//! ported from Harfbuzz Serializer: <https://github.com/harfbuzz/harfbuzz/blob/5e32b5ca8fe430132b87c0eee6a1c056d37c35eb/src/hb-serialize.hh>
use core::ops::Range;
use std::{
    hash::{Hash, Hasher},
    mem,
};

use fnv::{FnvHashMap, FnvHasher};
use fontcull_write_fonts::types::{FixedSize, Scalar, Uint24};
use hashbrown::HashTable;

/// An error which occurred during the serialization of a table using Serializer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SerializeErrorFlags(u16);

impl std::fmt::Display for SerializeErrorFlags {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Error during serialization, error flags: {:016b}",
            self.0
        )
    }
}

impl SerializeErrorFlags {
    pub const SERIALIZE_ERROR_NONE: Self = Self(0x0000);
    pub const SERIALIZE_ERROR_OTHER: Self = Self(0x0001);
    pub const SERIALIZE_ERROR_OFFSET_OVERFLOW: Self = Self(0x0002);
    pub const SERIALIZE_ERROR_OUT_OF_ROOM: Self = Self(0x0004);
    pub const SERIALIZE_ERROR_INT_OVERFLOW: Self = Self(0x0008);
    pub const SERIALIZE_ERROR_ARRAY_OVERFLOW: Self = Self(0x0010);
    pub const SERIALIZE_ERROR_READ_ERROR: Self = Self(0x0020);
    pub const SERIALIZE_ERROR_EMPTY: Self = Self(0x0040);

    fn contains(&self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl Default for SerializeErrorFlags {
    fn default() -> Self {
        Self::SERIALIZE_ERROR_NONE
    }
}

impl std::ops::BitOrAssign for SerializeErrorFlags {
    /// Adds the set of flags.
    #[inline]
    fn bitor_assign(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

impl std::ops::Not for SerializeErrorFlags {
    type Output = bool;
    #[inline]
    fn not(self) -> bool {
        self == SerializeErrorFlags::SERIALIZE_ERROR_NONE
    }
}

#[derive(Default, Eq, PartialEq, Clone, Copy, Hash, Debug)]
/// Marks where an offset is relative from.
///
/// Offset relative to the current object head (default)/tail or
/// Absolute: from the start of the serialize buffer
pub enum OffsetWhence {
    #[default]
    Head,
    Tail,
    Absolute,
}

type PoolIdx = usize;

// Reference Harfbuzz implementation:
// <https://github.com/harfbuzz/harfbuzz/blob/5e32b5ca8fe430132b87c0eee6a1c056d37c35eb/src/hb-serialize.hh#L69>
#[derive(Default)]
pub(crate) struct Object {
    // head/tail: indices of the output buffer for this object
    head: usize,
    tail: usize,
    // real links are associated with actual offsets
    real_links: Vec<Link>,
    // virtual links not associated with actual offsets,
    // they exist merely to enforce an ordering constraint.
    virtual_links: Vec<Link>,

    // pool index of the object that will be worked on next
    next_obj: Option<PoolIdx>,
}

impl Object {
    fn reset(&mut self) {
        self.real_links.clear();
        self.virtual_links.clear();
    }

    fn add_virtual_link(&mut self, obj_idx: ObjIdx) {
        let link = Link {
            width: LinkWidth::default(),
            is_signed: false,
            whence: OffsetWhence::default(),
            bias: 0,
            position: 0,
            objidx: obj_idx,
        };

        self.virtual_links.push(link);
    }

    pub(crate) fn head(&self) -> usize {
        self.head
    }

    pub(crate) fn tail(&self) -> usize {
        self.tail
    }

    pub(crate) fn real_links(&self) -> FnvHashMap<u32, Link> {
        let mut links_map = FnvHashMap::default();
        for l in &self.real_links {
            let pos = l.position;
            links_map.insert(pos, *l);
        }
        links_map
    }

    pub(crate) fn virtual_links(&self) -> Vec<Link> {
        self.virtual_links.clone()
    }
}

// LinkWidth: 0->virtual_link, 2->offset16, 3->offset24 and 4->offset32
#[derive(Default, Eq, PartialEq, Clone, Copy, Hash, Debug)]
#[repr(u8)]
pub(crate) enum LinkWidth {
    #[default]
    Zero = 0,
    Two = 2,
    Three = 3,
    Four = 4,
}

impl LinkWidth {
    fn new_checked(val: usize) -> Option<LinkWidth> {
        match val {
            0 => Some(LinkWidth::Zero),
            2 => Some(LinkWidth::Two),
            3 => Some(LinkWidth::Three),
            4 => Some(LinkWidth::Four),
            _ => None,
        }
    }
}

pub(crate) type ObjIdx = usize;

#[derive(Default, Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub(crate) struct Link {
    width: LinkWidth,
    is_signed: bool,
    whence: OffsetWhence,
    bias: u32,
    position: u32,
    objidx: ObjIdx,
}

impl Link {
    pub(crate) fn obj_idx(&self) -> ObjIdx {
        self.objidx
    }

    pub(crate) fn link_width(&self) -> LinkWidth {
        self.width
    }

    pub(crate) fn whence(&self) -> OffsetWhence {
        self.whence
    }

    pub(crate) fn bias(&self) -> u32 {
        self.bias
    }

    pub(crate) fn is_signed(&self) -> bool {
        self.is_signed
    }

    #[allow(dead_code)]
    pub(crate) fn partial_equals(&self, other: &Self) -> bool {
        self.width == other.width
            && self.is_signed == other.is_signed
            && self.whence == other.whence
            && self.bias == other.bias
            && self.position == other.position
    }

    pub(crate) fn update_obj_idx(&mut self, new_idx: ObjIdx) {
        self.objidx = new_idx;
    }
}

#[derive(Default)]
pub(crate) struct Snapshot {
    head: usize,
    tail: usize,
    current: Option<PoolIdx>,
    num_real_links: usize,
    num_virtual_links: usize,
    errors: SerializeErrorFlags,
}

/// Constructs a sequential stream of bytes from one or more subsequences of bytes/objects.
///
/// Notably this allows construction of open type tables that make use of offsets (eg. GSUB, GPOS) to form
/// graphs of sub tables. The serializer is capable of automatically placing object data in a topological sorting
/// and resolving offsets given an object graph.
///
/// Port of the harfbuzz serializer:
/// <https://github.com/harfbuzz/harfbuzz/blob/5e32b5ca8fe430132b87c0eee6a1c056d37c35eb/src/hb-serialize.hh#L57>
///
/// For a higher level overview of serializer concepts see:
/// <https://github.com/harfbuzz/harfbuzz/blob/main/docs/serializer.md>
///
/// Note: currently repacking to resolve offset overflows is not yet implemented
/// (context: <https://github.com/harfbuzz/harfbuzz/blob/main/docs/repacker.md>)
#[derive(Default)]
pub struct Serializer {
    start: usize,
    end: usize,
    head: usize,
    tail: usize,
    // TODO: zerocopy, debug_depth
    errors: SerializeErrorFlags,

    data: Vec<u8>,
    object_pool: ObjectPool,
    // index for current Object in the object_pool
    current: Option<PoolIdx>,

    packed: Vec<PoolIdx>,
    packed_map: PoolIdxHashTable,
}

impl Serializer {
    pub fn new(size: usize) -> Self {
        Serializer {
            data: vec![0; size],
            end: size,
            tail: size,
            packed: Vec::new(),
            ..Default::default()
        }
    }

    /// Appends a the byte representation of a single scalar type onto the buffer.
    pub fn embed(&mut self, obj: impl Scalar) -> Result<usize, SerializeErrorFlags> {
        let raw = obj.to_raw();
        let bytes = raw.as_ref();
        let size = bytes.len();

        let ret = self.allocate_size(size, false)?;
        self.data[ret..ret + size].copy_from_slice(bytes);
        Ok(ret)
    }

    /// Appends a copy of a slice of bytes onto the buffer.
    pub fn embed_bytes(&mut self, bytes: &[u8]) -> Result<usize, SerializeErrorFlags> {
        let len = bytes.len();
        let ret = self.allocate_size(len, false)?;
        self.data[ret..ret + len].copy_from_slice(bytes);
        Ok(ret)
    }

    /// Adds count bytes of padding into the serialization buffer.
    pub fn pad(&mut self, count: usize) -> Result<usize, SerializeErrorFlags> {
        self.allocate_size(count, false)
    }

    /// get single Scalar value at certain position
    pub(crate) fn get_value_at<T: Scalar>(&self, pos: usize) -> Option<T> {
        let len = T::RAW_BYTE_LEN;
        let bytes = self.data.get(pos..pos + len)?;
        T::read(bytes)
    }

    pub(crate) fn check_assign<T: TryFrom<usize> + Scalar>(
        &mut self,
        pos: usize,
        obj: usize,
        err_type: SerializeErrorFlags,
    ) -> Result<(), SerializeErrorFlags> {
        let Ok(val) = T::try_from(obj) else {
            return Err(self.set_err(err_type));
        };
        self.copy_assign(pos, val);
        Ok(())
    }

    /// copy from a single Scalar type
    pub(crate) fn copy_assign(&mut self, pos: usize, obj: impl Scalar) {
        let raw = obj.to_raw();
        let bytes = raw.as_ref();
        let size = bytes.len();

        let Some(to) = self.data.get_mut(pos..pos + size) else {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            return;
        };

        to.copy_from_slice(bytes);
    }

    /// copy from bytes
    pub(crate) fn copy_assign_from_bytes(&mut self, pos: usize, from_bytes: &[u8]) {
        let size = from_bytes.len();
        let Some(to) = self.data.get_mut(pos..pos + size) else {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            return;
        };

        to.copy_from_slice(from_bytes);
    }

    pub(crate) fn get_mut_data(&mut self, range: Range<usize>) -> Option<&mut [u8]> {
        self.data.get_mut(range)
    }

    /// Allocate size
    pub(crate) fn allocate_size(
        &mut self,
        size: usize,
        clear: bool,
    ) -> Result<usize, SerializeErrorFlags> {
        if self.in_error() {
            return Err(self.errors);
        }

        if size > u32::MAX as usize || self.tail - self.head < size {
            return Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM));
        }

        if clear {
            self.data
                .get_mut(self.head..self.head + size)
                .unwrap()
                .fill(0);
        }
        let ret = self.head;
        self.head += size;
        Ok(ret)
    }

    pub(crate) fn successful(&self) -> bool {
        !self.errors
    }

    pub(crate) fn in_error(&self) -> bool {
        !!self.errors
    }

    pub(crate) fn ran_out_of_room(&self) -> bool {
        self.errors
            .contains(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM)
    }

    pub(crate) fn offset_overflow(&self) -> bool {
        self.errors
            .contains(SerializeErrorFlags::SERIALIZE_ERROR_OFFSET_OVERFLOW)
    }

    pub(crate) fn only_offset_overflow(&self) -> bool {
        self.errors == SerializeErrorFlags::SERIALIZE_ERROR_OFFSET_OVERFLOW
    }

    pub(crate) fn only_overflow(&self) -> bool {
        self.errors == SerializeErrorFlags::SERIALIZE_ERROR_OFFSET_OVERFLOW
            || self.errors == SerializeErrorFlags::SERIALIZE_ERROR_INT_OVERFLOW
            || self.errors == SerializeErrorFlags::SERIALIZE_ERROR_ARRAY_OVERFLOW
    }

    pub(crate) fn set_err(&mut self, error_type: SerializeErrorFlags) -> SerializeErrorFlags {
        self.errors |= error_type;
        self.errors
    }

    /// Returns any currently set error flags.
    pub fn error(&self) -> SerializeErrorFlags {
        self.errors
    }

    pub(crate) fn reset_size(&mut self, size: usize) {
        self.start = 0;
        self.end = size;
        self.reset();
        self.current = None;
        self.data.resize(size, 0);
    }

    fn reset(&mut self) {
        self.errors = SerializeErrorFlags::SERIALIZE_ERROR_NONE;
        self.head = self.start;
        self.tail = self.end;

        self.fini();
    }

    fn fini(&mut self) {
        for pool_idx in self.packed.iter() {
            self.object_pool.release(*pool_idx);
        }
        self.packed.clear();
        self.packed_map.clear();

        while let Some(current) = self.current.take() {
            self.current = self.object_pool.next_idx(current);
            self.object_pool.release(current);
        }
        self.data.clear();
    }

    pub(crate) fn snapshot(&self) -> Snapshot {
        let mut s = Snapshot {
            head: self.head,
            tail: self.tail,
            current: self.current,
            errors: self.errors,
            ..Default::default()
        };

        if self.current.is_none() {
            return s;
        }
        let Some(cur_obj) = self.object_pool.get_obj(self.current.unwrap()) else {
            return s;
        };

        s.num_real_links = cur_obj.real_links.len();
        s.num_virtual_links = cur_obj.virtual_links.len();
        s
    }

    /// Start a new sub table object which may be pointed to via offset from any object that has already been packed.
    pub fn push(&mut self) -> Result<(), SerializeErrorFlags> {
        if self.in_error() {
            return Err(self.errors);
        }

        let pool_idx = self.object_pool.alloc();
        let Some(obj) = self.object_pool.get_obj_mut(pool_idx) else {
            return Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER));
        };

        obj.head = self.head;
        obj.tail = self.tail;
        obj.next_obj = self.current;
        self.current = Some(pool_idx);

        Ok(())
    }

    /// Finalize the currently active object and copy it into the buffer.
    ///
    /// On success returns an index identifying the packed object.
    ///
    /// If share is true and there is an existing packed object which is identical this will not pack the object and
    /// instead return the index of the existing object.
    pub fn pop_pack(&mut self, share: bool) -> Option<ObjIdx> {
        self.current?;

        // Allow cleanup when we've error'd out on int overflows which don't compromise the serializer state
        if self.in_error() && !self.only_overflow() {
            return None;
        }

        let pool_idx = self.current.unwrap();
        // code logic is a bit different from Harfbuzz serializer here
        // because I need to move code around to fix mutable borrow/immutable borrow issue
        let obj = self.object_pool.get_obj_mut(pool_idx)?;

        self.current = obj.next_obj;
        obj.tail = self.head;
        obj.next_obj = None;

        if obj.tail < obj.head {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            return None;
        }

        let len = obj.tail - obj.head;

        // TODO: consider zerocopy
        // Rewind head
        self.head = obj.head;

        if len == 0 {
            if !obj.real_links.is_empty() || !obj.virtual_links.is_empty() {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            }
            return None;
        }

        self.tail -= len;

        let obj_head = obj.head;
        obj.head = self.tail;
        obj.tail = self.tail + len;

        //TODO: consider zerocopy here
        self.data.copy_within(obj_head..obj_head + len, self.tail);

        let mut hash = 0_u64;
        // introduce flags to avoid mutable borrow and immutable borrow issues
        let mut obj_duplicate = None;
        if share {
            hash = hash_one_pool_idx(pool_idx, &self.data, &self.object_pool);
            if let Some(entry) =
                self.packed_map
                    .get_with_hash(pool_idx, hash, &self.data, &self.object_pool)
            {
                obj_duplicate = Some(*entry);
            };
        }

        if let Some(dup_obj_idxes) = obj_duplicate {
            self.merge_virtual_links(pool_idx, dup_obj_idxes);
            self.object_pool.release(pool_idx);

            // rewind tail because we discarded duplicate obj
            self.tail += len;
            return Some(dup_obj_idxes.1);
        }

        self.packed.push(pool_idx);
        let obj_idx = self.packed.len() - 1;

        if share {
            self.packed_map
                .set_with_hash(pool_idx, hash, obj_idx, &self.data, &self.object_pool);
        }
        Some(obj_idx)
    }

    pub(crate) fn pop_discard(&mut self) {
        if self.current.is_none() {
            return;
        }
        // Allow cleanup when we've error'd out on int overflows which don't compromise the serializer state.
        if self.in_error() && !self.only_overflow() {
            return;
        }

        let pool_idx = self.current.unwrap();
        let Some(obj) = self.object_pool.get_obj(pool_idx) else {
            return;
        };
        self.current = obj.next_obj;
        //TODO: consider zerocopy
        self.revert(obj.head, obj.tail);
        self.object_pool.release(pool_idx);
    }

    fn revert(&mut self, snap_head: usize, snap_tail: usize) {
        if self.in_error() || self.head < snap_head || self.tail > snap_tail {
            return;
        }
        self.head = snap_head;
        self.tail = snap_tail;
        self.discard_stale_objects();
    }

    pub(crate) fn revert_snapshot(&mut self, snapshot: Snapshot) {
        // Overflows that happened after the snapshot will be erased by the revert.
        if self.in_error() && !self.only_overflow() {
            return;
        }
        if snapshot.current != self.current {
            return;
        }
        self.errors = snapshot.errors;

        if let Some(current) = self.current {
            let Some(obj) = self.object_pool.get_obj_mut(current) else {
                return;
            };
            obj.real_links.truncate(snapshot.num_real_links);
            obj.virtual_links.truncate(snapshot.num_virtual_links);
        }
        self.revert(snapshot.head, snapshot.tail);
    }

    fn discard_stale_objects(&mut self) {
        if self.in_error() {
            return;
        }

        let len = self.packed.len();
        for i in (0..len).rev() {
            let pool_idx = self.packed[i];
            let Some(obj) = self.object_pool.get_obj(pool_idx) else {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                return;
            };

            if obj.next_obj.is_some() {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                return;
            }

            if obj.head >= self.tail {
                break;
            }

            let hash = hash_one_pool_idx(pool_idx, &self.data, &self.object_pool);
            self.packed_map
                .del(pool_idx, hash, &self.data, &self.object_pool);
            self.object_pool.release(pool_idx);
            self.packed.pop();
        }

        if let Some(pool_idx) = self.packed.last() {
            let Some(obj) = self.object_pool.get_obj(*pool_idx) else {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                return;
            };

            if obj.head != self.tail {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            }
        }
    }

    /// Creates an offset in the current object which will point to the object identified by obj_idx.
    ///
    /// When serialization finishes the appropriate offset value will be written into offset_byte_range,
    /// which is relative to the start of the current object.
    ///
    /// whence controls what the offset value is relative too.
    pub fn add_link(
        &mut self,
        offset_byte_range: Range<usize>,
        obj_idx: ObjIdx,
        whence: OffsetWhence,
        bias: u32,
        is_signed: bool,
    ) -> Result<(), SerializeErrorFlags> {
        if self.in_error() {
            return Err(self.errors);
        }

        let pool_idx = self
            .current
            .ok_or_else(|| self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER))?;
        let Some(current) = self.object_pool.get_obj_mut(pool_idx) else {
            return Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER));
        };

        let Some(link_width) = LinkWidth::new_checked(offset_byte_range.len()) else {
            return Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER));
        };

        if current.head > offset_byte_range.start {
            return Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER));
        }

        let link = Link {
            width: link_width,
            is_signed,
            whence,
            bias,
            position: (offset_byte_range.start - current.head) as u32,
            objidx: obj_idx,
        };
        current.real_links.push(link);
        Ok(())
    }

    /// Adds a link which enforces that the object identified by obj_idx must always come after this
    /// object in the serialized output.
    pub fn add_virtual_link(&mut self, obj_idx: ObjIdx) -> bool {
        if self.current.is_none() {
            return false;
        }

        let pool_idx = self.current.unwrap();
        let Some(current) = self.object_pool.get_obj_mut(pool_idx) else {
            return false;
        };

        current.add_virtual_link(obj_idx);
        true
    }

    fn merge_virtual_links(&mut self, from: PoolIdx, to: (PoolIdx, ObjIdx)) {
        let from_obj = self.object_pool.get_obj_mut(from).unwrap();
        if from_obj.virtual_links.is_empty() {
            return;
        }
        let mut from_vec = mem::take(&mut from_obj.virtual_links);

        // hash value will change after merge, so delete existing old entry in the hash table
        let hash_old = hash_one_pool_idx(to.0, &self.data, &self.object_pool);
        self.packed_map
            .del(to.0, hash_old, &self.data, &self.object_pool);

        let to_obj = self.object_pool.get_obj_mut(to.0).unwrap();
        to_obj.virtual_links.append(&mut from_vec);

        let hash = hash_one_pool_idx(to.0, &self.data, &self.object_pool);
        self.packed_map
            .set_with_hash(to.0, hash, to.1, &self.data, &self.object_pool);
    }

    fn resolve_links(&mut self) {
        if self.in_error() {
            return;
        }

        if self.current.is_some() || self.packed.is_empty() {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            return;
        }

        let mut offset_links = Vec::new();
        for parent_obj_idx in self.packed.iter() {
            let Some(parent_obj) = self.object_pool.get_obj(*parent_obj_idx) else {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                return;
            };

            for link in parent_obj.real_links.iter() {
                let Some(child_pool_idx) = self.packed.get(link.objidx) else {
                    self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                    return;
                };
                let Some(child_obj) = self.object_pool.get_obj(*child_pool_idx) else {
                    self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                    return;
                };

                let offset = match link.whence {
                    OffsetWhence::Head => child_obj.head - parent_obj.head,
                    OffsetWhence::Tail => child_obj.head - parent_obj.tail,
                    OffsetWhence::Absolute => self.head - self.start + child_obj.head - self.tail,
                };

                if offset < link.bias as usize {
                    self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
                    return;
                }

                let offset = offset - link.bias as usize;
                let offset_start_pos = parent_obj.head + link.position as usize;
                offset_links.push((offset_start_pos, link.width, offset));
            }
        }

        for (offset_start_pos, offset_width, offset) in offset_links.iter() {
            self.assign_offset(*offset_start_pos, *offset_width, *offset);
        }
    }

    //TODO: take care of signed offset
    fn assign_offset(&mut self, offset_start_pos: usize, link_width: LinkWidth, offset: usize) {
        let (offset_width, max_offset) = match link_width {
            LinkWidth::Two => (2, u16::MAX as usize),
            LinkWidth::Three => (3, (Uint24::MAX).to_u32() as usize),
            LinkWidth::Four => (4, u32::MAX as usize),
            _ => return,
        };

        if offset > max_offset {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OFFSET_OVERFLOW);
            return;
        }

        let Some(offset_data_bytes) = self
            .data
            .get_mut(offset_start_pos..offset_start_pos + offset_width)
        else {
            self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            return;
        };

        let be_bytes = (offset as u32).to_be_bytes();
        match link_width {
            LinkWidth::Two => offset_data_bytes.copy_from_slice(&be_bytes[2..=3]),
            LinkWidth::Three => offset_data_bytes.copy_from_slice(&be_bytes[1..=3]),
            LinkWidth::Four => offset_data_bytes.copy_from_slice(&be_bytes),
            _ => (),
        }
    }

    /// Create and return a copy of the serialization buffer.
    ///
    /// end_serialize() should be called prior to this to perform offset resolution.
    pub fn copy_bytes(mut self) -> Vec<u8> {
        if !self.successful() {
            return Vec::new();
        }
        let len = (self.head - self.start) + (self.end - self.tail);
        if len == 0 {
            return Vec::new();
        }

        self.data.copy_within(self.tail..self.end, self.head);
        self.data.truncate(len);
        self.data
    }

    pub(crate) fn length(&self) -> usize {
        if self.current.is_none() {
            return 0;
        }
        let Some(cur_obj) = self.object_pool.get_obj(self.current.unwrap()) else {
            return 0;
        };
        self.head - cur_obj.head
    }

    pub(crate) fn head(&self) -> usize {
        self.head
    }

    pub(crate) fn tail(&self) -> usize {
        self.tail
    }

    pub(crate) fn allocated(&self) -> usize {
        self.data.len()
    }

    /// Starts the serialization of an object graph.
    pub fn start_serialize(&mut self) -> Result<(), SerializeErrorFlags> {
        if self.current.is_some() {
            Err(self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER))?
        }

        self.push()
    }

    /// Ends the serialization of an object graph and resolves all offsets.
    pub fn end_serialize(&mut self) {
        if self.current.is_none() {
            return;
        }

        // Offset overflows that occur before link resolution cannot be handled by repacking, so set a more general error.
        if self.in_error() {
            if self.offset_overflow() {
                self.set_err(SerializeErrorFlags::SERIALIZE_ERROR_OTHER);
            }
            return;
        }

        if self.packed.is_empty() {
            return;
        }

        self.pop_pack(false);
        self.resolve_links();
    }

    pub(crate) fn packed_obj_idxs(&self) -> &[PoolIdx] {
        &self.packed
    }

    pub(crate) fn get_obj(&self, pool_idx: PoolIdx) -> Option<&Object> {
        self.object_pool.get_obj(pool_idx)
    }

    pub(crate) fn data(&self) -> Vec<u8> {
        self.data.clone()
    }
}

#[derive(Default)]
struct ObjectWrap {
    pub obj: Object,
    pub next: Option<PoolIdx>,
}

// reference Harfbuzz implementation:
//<https://github.com/harfbuzz/harfbuzz/blob/5e32b5ca8fe430132b87c0eee6a1c056d37c35eb/src/hb-pool.hh>
#[derive(Default)]
struct ObjectPool {
    chunks: Vec<ObjectWrap>,
    next: Option<PoolIdx>,
}

impl ObjectPool {
    const ALLOC_CHUNKS_LEN: usize = 64;
    pub fn alloc(&mut self) -> PoolIdx {
        let len = self.chunks.len();
        if self.next.is_none() {
            let new_len = len + Self::ALLOC_CHUNKS_LEN;
            self.chunks.resize_with(new_len, Default::default);

            for (idx, obj) in self
                .chunks
                .get_mut(len..new_len - 1)
                .unwrap()
                .iter_mut()
                .enumerate()
            {
                obj.next = Some(len + idx + 1);
            }

            self.chunks.last_mut().unwrap().next = None;
            self.next = Some(len);
        }

        let pool_idx = self.next.unwrap();
        self.next = self.chunks[pool_idx].next;

        pool_idx
    }

    pub fn release(&mut self, pool_idx: PoolIdx) {
        let Some(obj_wrap) = self.chunks.get_mut(pool_idx) else {
            return;
        };

        obj_wrap.obj.reset();
        obj_wrap.next = self.next;
        self.next = Some(pool_idx);
    }

    pub fn get_obj_mut(&mut self, pool_idx: PoolIdx) -> Option<&mut Object> {
        self.chunks.get_mut(pool_idx).map(|o| &mut o.obj)
    }

    pub fn get_obj(&self, pool_idx: PoolIdx) -> Option<&Object> {
        self.chunks.get(pool_idx).map(|o| &o.obj)
    }

    fn next_idx(&self, pool_idx: PoolIdx) -> Option<PoolIdx> {
        self.get_obj(pool_idx)?.next_obj
    }
}

// Hash an Object: Virtual links aren't considered for equality since they don't affect the functionality of the object.
fn hash_one_pool_idx(pool_idx: PoolIdx, data: &[u8], obj_pool: &ObjectPool) -> u64 {
    let mut hasher = FnvHasher::default();
    let Some(obj) = obj_pool.get_obj(pool_idx) else {
        return hasher.finish();
    };
    // hash data bytes
    // Only hash at most 128 bytes for Object. Byte objects differ in their early bytes anyway.
    // reference: <https://github.com/harfbuzz/harfbuzz/blob/622e9c33c39e9c2a6491763841d6d6ad715f6abf/src/hb-serialize.hh#L136>
    let byte_len = 128.min(obj.tail - obj.head);
    let data_bytes = data.get(obj.head..obj.head + byte_len);
    data_bytes.hash(&mut hasher);
    // hash real_links
    obj.real_links.hash(&mut hasher);

    hasher.finish()
}

// Virtual links aren't considered for equality since they don't affect the functionality of the object.
fn cmp_pool_idx(idx_a: PoolIdx, idx_b: PoolIdx, data: &[u8], obj_pool: &ObjectPool) -> bool {
    if idx_a == idx_b {
        return true;
    }

    match (obj_pool.get_obj(idx_a), obj_pool.get_obj(idx_b)) {
        (Some(_), None) => false,
        (None, Some(_)) => false,
        (None, None) => true,
        (Some(obj_a), Some(obj_b)) => {
            data.get(obj_a.head..obj_a.tail) == data.get(obj_b.head..obj_b.tail)
                && obj_a.real_links == obj_b.real_links
        }
    }
}

#[derive(Default)]
struct PoolIdxHashTable {
    hash_table: HashTable<(PoolIdx, ObjIdx)>,
}

impl PoolIdxHashTable {
    fn get_with_hash(
        &self,
        pool_idx: PoolIdx,
        hash: u64,
        data: &[u8],
        obj_pool: &ObjectPool,
    ) -> Option<&(PoolIdx, ObjIdx)> {
        self.hash_table.find(hash, |val: &(PoolIdx, ObjIdx)| {
            cmp_pool_idx(pool_idx, val.0, data, obj_pool)
        })
    }

    fn set_with_hash(
        &mut self,
        pool_idx: PoolIdx,
        hash: u64,
        obj_idx: ObjIdx,
        data: &[u8],
        obj_pool: &ObjectPool,
    ) {
        let hasher = |val: &(PoolIdx, ObjIdx)| hash_one_pool_idx(val.0, data, obj_pool);

        self.hash_table
            .insert_unique(hash, (pool_idx, obj_idx), hasher);
    }

    fn del(&mut self, pool_idx: PoolIdx, hash: u64, data: &[u8], obj_pool: &ObjectPool) {
        let Ok(entry) = self.hash_table.find_entry(hash, |val: &(PoolIdx, ObjIdx)| {
            cmp_pool_idx(pool_idx, val.0, data, obj_pool)
        }) else {
            return;
        };
        entry.remove();
    }

    fn clear(&mut self) {
        self.hash_table.clear();
    }
}

#[cfg(test)]
mod test {
    use fontcull_write_fonts::types::{Offset16, Offset32, UfWord, Uint24};

    use super::*;

    // test Serializer::embed() works for different Scalar types
    #[test]
    fn test_serializer_embed() {
        let mut s = Serializer::new(2);
        let gid = 1_u32;
        //fail when out of room
        assert_eq!(
            s.embed(gid),
            Err(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM)
        );

        let mut s = Serializer::new(16384);
        assert_eq!(s.embed(gid), Ok(0));

        //check that head is advancing accordingly
        let offset = Offset16::new(20);
        assert_eq!(s.embed(offset), Ok(4));

        let n = Uint24::new(30);
        assert_eq!(s.embed(n), Ok(6));

        let w = UfWord::new(40);
        assert_eq!(s.embed(w), Ok(9));
        assert_eq!(s.head, 11);
        assert_eq!(s.start, 0);
        assert_eq!(s.tail, 16384);
        assert_eq!(s.end, 16384);

        let out = s.copy_bytes();
        assert_eq!(out, [0, 0, 0, 1, 0, 20, 0, 0, 30, 0, 40]);
    }

    #[test]
    fn test_serializer_embed_bytes() {
        let mut s = Serializer::new(2);
        let bytes = vec![1_u8, 2, 3, 4, 5];
        //fail when out of room
        assert_eq!(
            s.embed_bytes(&bytes),
            Err(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM)
        );

        let mut s = Serializer::new(10);
        assert_eq!(s.embed_bytes(&bytes), Ok(0));

        //check that head is advancing accordingly
        assert_eq!(s.head, 5);
        assert_eq!(s.start, 0);
        assert_eq!(s.tail, 10);
        assert_eq!(s.end, 10);

        let out = s.copy_bytes();
        assert_eq!(out, [1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_push() {
        let mut s = Serializer::new(2);
        assert_eq!(s.push(), Ok(()));
        assert_eq!(
            s.embed(1_u32),
            Err(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM)
        );
        assert_eq!(
            s.push(),
            Err(SerializeErrorFlags::SERIALIZE_ERROR_OUT_OF_ROOM)
        );
    }

    #[test]
    fn test_object_pool() {
        let mut p = ObjectPool::default();

        let i = p.alloc();
        assert_eq!(i, 0);
        let i = p.alloc();
        assert_eq!(i, 1);
        let i = p.alloc();
        assert_eq!(i, 2);
        let i = p.alloc();
        assert_eq!(i, 3);

        p.release(1);
        let i = p.alloc();
        assert_eq!(i, 1);

        p.release(3);
        let i = p.alloc();
        assert_eq!(i, 3);

        let i = p.alloc();
        assert_eq!(i, 4);

        let o = p.get_obj(0).unwrap();
        assert_eq!(o.head, 0);
        assert_eq!(o.tail, 0);
        assert!(o.real_links.is_empty());
        assert!(o.virtual_links.is_empty());
        assert_eq!(o.next_obj, None);

        //test alloc more than 64 chunks, which would grow the internal vector
        for i in 0..64 {
            let idx = p.alloc();
            assert_eq!(idx, 5 + i);
        }
    }

    #[test]
    fn test_hash_table() {
        let mut obj_pool = ObjectPool::default();
        let data: Vec<u8> = vec![
            0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0,
        ];
        let obj_0 = obj_pool.alloc();
        assert_eq!(obj_0, 0);
        let obj_1 = obj_pool.alloc();
        assert_eq!(obj_1, 1);
        let obj_2 = obj_pool.alloc();
        assert_eq!(obj_2, 2);
        let obj_3 = obj_pool.alloc();
        assert_eq!(obj_3, 3);

        //obj_0, obj_1 and obj_3 point to the same bytes
        {
            let obj_0 = obj_pool.get_obj_mut(0).unwrap();
            obj_0.head = 0;
            obj_0.tail = 5;
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 21,
                objidx: 2,
            };
            obj_0.real_links.push(link);
        }

        {
            // obj_1 has the same real_links with obj_0
            let obj_1 = obj_pool.get_obj_mut(1).unwrap();
            obj_1.head = 5;
            obj_1.tail = 10;
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 21,
                objidx: 2,
            };
            obj_1.real_links.push(link);
        }

        {
            let obj_2 = obj_pool.get_obj_mut(2).unwrap();
            obj_2.head = 10;
            obj_2.tail = 15;
        }

        {
            // obj_3 doesn't have real_links
            let obj_3 = obj_pool.get_obj_mut(3).unwrap();
            obj_3.head = 15;
            obj_3.tail = 20;
        }

        assert!(cmp_pool_idx(0, 1, &data, &obj_pool));
        assert!(!cmp_pool_idx(0, 2, &data, &obj_pool));
        assert!(!cmp_pool_idx(0, 3, &data, &obj_pool));
        assert!(!cmp_pool_idx(1, 3, &data, &obj_pool));

        let mut hash_table = PoolIdxHashTable::default();
        let hash_0 = hash_one_pool_idx(0, &data, &obj_pool);
        let hash_1 = hash_one_pool_idx(1, &data, &obj_pool);
        assert_eq!(hash_0, hash_1);
        let hash_2 = hash_one_pool_idx(2, &data, &obj_pool);
        let hash_3 = hash_one_pool_idx(3, &data, &obj_pool);
        assert_ne!(hash_0, hash_2);
        assert_ne!(hash_0, hash_3);
        assert_ne!(hash_2, hash_3);

        hash_table.set_with_hash(0, hash_0, 0, &data, &obj_pool);
        assert_eq!(
            hash_table.get_with_hash(1, hash_1, &data, &obj_pool),
            Some(&(0, 0))
        );
        assert_eq!(hash_table.get_with_hash(2, hash_2, &data, &obj_pool), None);
        assert_eq!(hash_table.get_with_hash(3, hash_3, &data, &obj_pool), None);

        hash_table.set_with_hash(2, hash_2, 2, &data, &obj_pool);
        assert_eq!(
            hash_table.get_with_hash(2, hash_2, &data, &obj_pool),
            Some(&(2, 2))
        );

        hash_table.set_with_hash(3, hash_3, 3, &data, &obj_pool);
        assert_eq!(
            hash_table.get_with_hash(3, hash_3, &data, &obj_pool),
            Some(&(3, 3))
        );

        // update obj_3 to have the same real links as obj_0
        {
            let obj_3 = obj_pool.get_obj_mut(3).unwrap();
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 21,
                objidx: 2,
            };
            obj_3.real_links.push(link);
        }

        let hash_3_new = hash_one_pool_idx(3, &data, &obj_pool);
        assert_ne!(hash_3, hash_3_new);
        // old entries found with old hash
        assert_eq!(
            hash_table.get_with_hash(3, hash_3, &data, &obj_pool),
            Some(&(3, 3))
        );

        // test del
        hash_table.del(3, hash_3, &data, &obj_pool);
        assert_eq!(hash_table.get_with_hash(3, hash_3, &data, &obj_pool), None);

        // duplicate obj_0 entry found with new hash
        assert_eq!(
            hash_table.get_with_hash(3, hash_3_new, &data, &obj_pool),
            Some(&(0, 0))
        );
    }

    #[test]
    fn test_push_and_pop_pack() {
        let mut s = Serializer::new(100);
        let n = Uint24::new(80);
        assert_eq!(s.embed(n), Ok(0));
        assert_eq!(s.head, 3);
        assert_eq!(s.current, None);

        {
            //single pop_pack()
            assert_eq!(s.push(), Ok(()));
            //an object is allocated during push
            assert_eq!(s.current, Some(0));
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);
            assert_eq!(s.tail, 100);
            assert_eq!(s.pop_pack(true), Some(0));
            assert_eq!(s.packed_map.hash_table.len(), 1);
            assert_eq!(s.packed.len(), 1);
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 97);
        }

        {
            //test de-duplicate
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(1));
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);
            assert_eq!(s.pop_pack(true), Some(0));
            assert_eq!(s.packed_map.hash_table.len(), 1);
            // share=true, duplicate object won't be added into packed vector
            assert_eq!(s.packed.len(), 1);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 97);

            assert_eq!(s.push(), Ok(()));
            // check that we released the previous duplicate object
            assert_eq!(s.current, Some(1));
            let n = UfWord::new(10);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 5);
            assert_eq!(s.pop_pack(true), Some(1));
            assert_eq!(s.packed_map.hash_table.len(), 2);
            assert_eq!(s.packed.len(), 2);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            //check that tail is updated
            assert_eq!(s.tail, 95);
        }

        {
            //test pop_pack(false) when duplicate objects exist
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(2));
            let n = Uint24::new(80);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);
            assert_eq!(s.pop_pack(false), Some(2));
            // when share=false, we don't set this object in hash table, so the len of hash table is the same
            assert_eq!(s.packed_map.hash_table.len(), 2);
            // share=true, duplicate object will be added into the packed vector
            assert_eq!(s.packed.len(), 3);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 92);
        }

        {
            // test de-duplicate with virtual links
            // virtual links don't affect equality and merge virtual links works
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(3));
            let n = Uint24::new(123);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);

            //add virtual links
            let obj = s.object_pool.get_obj_mut(3).unwrap();
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 0,
                objidx: 0,
            };
            obj.virtual_links.push(link);
            assert_eq!(s.pop_pack(true), Some(3));
            assert_eq!(s.packed_map.hash_table.len(), 3);
            assert_eq!(s.packed.len(), 4);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 89);

            // another obj which differs only in virtual links
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(4));
            let n = Uint24::new(123);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);

            //add virtual links
            let obj = s.object_pool.get_obj_mut(4).unwrap();
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 0,
                objidx: 1,
            };
            obj.virtual_links.push(link);
            // check that virtual links doesn't affect euqality
            assert_eq!(s.pop_pack(true), Some(3));
            assert_eq!(s.packed_map.hash_table.len(), 3);
            assert_eq!(s.packed.len(), 4);
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 89);
            // check that duplicate obj is released, virtual links are emptied
            assert!(s.object_pool.get_obj(4).unwrap().virtual_links.is_empty());
            // check that merge_virtual_links works
            let obj = s.object_pool.get_obj_mut(3).unwrap();
            assert_eq!(obj.virtual_links.len(), 2);
            assert_eq!(obj.virtual_links[0].objidx, 0);
            assert_eq!(obj.virtual_links[1].objidx, 1);
        }

        {
            // test de-duplicate with real links
            // real links should be included in hash and equality computation
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(4));
            let n = Uint24::new(321);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);

            //add real links
            let obj = s.object_pool.get_obj_mut(4).unwrap();
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 10,
                objidx: 2,
            };
            obj.real_links.push(link);
            assert_eq!(s.pop_pack(true), Some(4));
            assert_eq!(s.packed_map.hash_table.len(), 4);
            assert_eq!(s.packed.len(), 5);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 86);

            // another obj which differs only in real links
            assert_eq!(s.push(), Ok(()));
            assert_eq!(s.current, Some(5));
            let n = Uint24::new(321);
            assert_eq!(s.embed(n), Ok(3));
            assert_eq!(s.head, 6);

            //add real links
            let obj = s.object_pool.get_obj_mut(5).unwrap();
            let link = Link {
                width: LinkWidth::Two,
                is_signed: false,
                whence: OffsetWhence::Head,
                bias: 0,
                position: 20,
                objidx: 3,
            };
            obj.real_links.push(link);
            // pop_pack with a different obj_idx
            assert_eq!(s.pop_pack(true), Some(5));
            // obj is added into both hash_table and packed vector
            assert_eq!(s.packed_map.hash_table.len(), 5);
            assert_eq!(s.packed.len(), 6);
            //check to make sure head is rewinded
            assert_eq!(s.head, 3);
            assert_eq!(s.tail, 83);
        }
    }

    #[test]
    fn test_push_and_pop_discard() {
        let mut s = Serializer::new(100);
        let n = Uint24::new(80);
        assert_eq!(s.embed(n), Ok(0));
        assert_eq!(s.head, 3);
        assert_eq!(s.current, None);

        //single pop_pack()
        assert_eq!(s.push(), Ok(()));
        //an object is allocated during push
        assert_eq!(s.current, Some(0));
        assert_eq!(s.embed(n), Ok(3));
        assert_eq!(s.head, 6);
        assert_eq!(s.tail, 100);
        assert_eq!(s.pop_pack(true), Some(0));
        assert_eq!(s.packed.len(), 1);
        assert_eq!(s.head, 3);
        assert_eq!(s.tail, 97);

        //pop_discard()
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(1));
        assert_eq!(s.embed(n), Ok(3));
        assert_eq!(s.head, 6);
        assert_eq!(s.tail, 97);
        s.pop_discard();
        //check that head is rewinded
        assert_eq!(s.head, 3);
        assert_eq!(s.tail, 97);
        //discarded obj is not added into packed vector
        assert_eq!(s.packed.len(), 1);
        //check that discard object is reused by new push()
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(1));
    }

    #[test]
    fn test_add_link_resolve_links() {
        let mut s = Serializer::new(100);
        let header: u32 = 1;
        //parent header
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.embed(header), Ok(0));
        //first offset field
        let offset_1 = Offset16::new(0);
        assert_eq!(s.embed(offset_1), Ok(4));
        //second offset field
        let offset_2 = Offset32::new(0);
        assert_eq!(s.embed(offset_2), Ok(6));
        assert_eq!(s.head, 10);
        assert_eq!(s.current, Some(0));

        //pack first child
        let n = Uint24::new(123);
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(1));
        assert_eq!(s.embed(n), Ok(10));
        assert_eq!(s.head, 13);
        assert_eq!(s.tail, 100);
        //pop_pack this child
        assert_eq!(s.pop_pack(true), Some(0));
        assert_eq!(s.packed.len(), 1);
        assert_eq!(s.head, 10);
        assert_eq!(s.tail, 97);
        //add_link to offset_1
        assert_eq!(s.add_link(4..6, 0, OffsetWhence::Head, 0, false), Ok(()));

        //pack another child
        let n = Uint24::new(234);
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(2));
        assert_eq!(s.embed(n), Ok(10));
        assert_eq!(s.head, 13);
        assert_eq!(s.tail, 97);
        //pop_pack this child
        assert_eq!(s.pop_pack(true), Some(1));
        assert_eq!(s.packed.len(), 2);
        assert_eq!(s.head, 10);
        assert_eq!(s.tail, 94);
        //add_link to offset_1
        assert_eq!(s.add_link(6..10, 1, OffsetWhence::Head, 0, false), Ok(()));

        //pop_pack parent header
        assert_eq!(s.pop_pack(false), Some(2));
        assert_eq!(s.head, 0);
        assert_eq!(s.tail, 84);
        assert_eq!(s.packed.len(), 3);
        s.resolve_links();
        assert_eq!(
            s.data.get(84..100).unwrap(),
            [0, 0, 0, 1, 0, 13, 0, 0, 0, 10, 0, 0, 234, 0, 0, 123]
        );
    }

    #[test]
    fn test_length() {
        let mut s = Serializer::new(100);
        let n = Uint24::new(80);
        assert_eq!(s.embed(n), Ok(0));
        assert_eq!(s.head, 3);
        assert_eq!(s.tail, 100);
        assert_eq!(s.current, None);

        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(0));
        assert_eq!(s.head, 3);
        //embed 2 Uint24 numbers
        assert_eq!(s.embed(n), Ok(3));
        assert_eq!(s.embed(n), Ok(6));
        // check length() = 6
        assert_eq!(s.length(), 6);
    }

    #[test]
    fn test_snapshot_and_revert() {
        let mut s = Serializer::new(100);
        //test when current is None
        let snapshot = s.snapshot();
        let n = Uint24::new(80);
        assert_eq!(s.embed(n), Ok(0));
        assert_eq!(s.head, 3);
        assert_eq!(s.tail, 100);
        assert_eq!(s.current, None);

        s.revert_snapshot(snapshot);
        assert!(!s.in_error());
        assert_eq!(s.head, 0);
        assert_eq!(s.tail, 100);
        assert_eq!(s.current, None);

        //snapshot and revert after single push(), current is not None
        assert_eq!(s.push(), Ok(()));
        let snapshot = s.snapshot();
        assert_eq!(s.current, Some(0));
        assert_eq!(s.embed(n), Ok(0));
        assert_eq!(s.head, 3);
        assert_eq!(s.tail, 100);

        s.revert_snapshot(snapshot);
        assert!(!s.in_error());
        assert_eq!(s.head, 0);
        assert_eq!(s.tail, 100);

        //test after a couple of push/pop_pack
        let snapshot = s.snapshot();
        assert_eq!(s.current, Some(0));
        assert_eq!(s.head, 0);
        assert_eq!(s.tail, 100);

        assert_eq!(s.embed(n), Ok(0));
        //another push, now current = 1
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(1));

        assert_eq!(s.embed(n), Ok(3));
        assert_eq!(s.pop_pack(true), Some(0));
        assert_eq!(s.add_link(0..3, 0, OffsetWhence::Head, 0, false), Ok(()));
        //check that after pop_pack, now current is back to 0, and real_links length =1;
        assert_eq!(s.current, Some(0));
        assert_eq!(s.object_pool.get_obj(0).unwrap().real_links.len(), 1);

        s.revert_snapshot(snapshot);
        assert!(!s.in_error());
        assert_eq!(s.head, 0);
        assert_eq!(s.tail, 100);
        assert_eq!(s.current, Some(0));
        // check that real_links is truncated
        assert_eq!(s.object_pool.get_obj(0).unwrap().real_links.len(), 0);
        // another push to check that obj_idx=1 is released in previous revert_snapshot
        assert_eq!(s.push(), Ok(()));
        assert_eq!(s.current, Some(1));
    }
}