resand 0.3.0

Read and write ARSC and AXML binary files used for Android Resources
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
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
// Everything here is based off of https://android.googlesource.com/platform/frameworks/base/+/master/libs/androidfw/include/androidfw/ResourceTypes.h

use std::{
    fmt::Display,
    io::{Cursor, Read, Seek, SeekFrom, Write},
    path::{Path, PathBuf},
};

use crate::{
    align,
    defs::{HeaderSizeInstance, HeaderSizeStatic, ResChunk, ResTableRef, ResType, ResTypeValue},
    res_value::ResValue,
    stream::{
        NewResultCtx, Readable, ReadableNoOptions, StreamError, StreamResult, VecReadable,
        VecWritable, Writeable, WriteableNoOptions,
    },
    string_pool::{ResStringPoolRef, StringPoolHandler},
    traits::Mergeable,
};

/// A specification of the resources defined by a particular type.
///
/// There should be one of these chunks for each resource type.
///
/// This structure is followed by an array of integers providing the set of configuration change
/// flags (ResTable_config::CONFIG_*) that have multiple resources for that configuration. In
/// addition, the high bi is set if that resource has been made public.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ResTableTypeSpec {
    /// The type identifier this chunk is holding. Type IDs start at 1 (corresponding to the value
    /// of the type bits in a resource identifier). 0 is invalid.
    pub id: u8,

    /// Used to be reserved, if >0 specifies the number of ResTable_type entries for this spec.
    pub types_count: u16,

    pub config_masks: Vec<u32>,
}

impl Readable for ResTableTypeSpec {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let id = u8::read_no_opts(reader).add_context(|| "read id for ResTableTypeSpec")?;
        let res0 = u8::read_no_opts(reader).add_context(|| "read res0 for ResTableTypeSpec")?;

        if res0 != 0 {
            return Err(StreamError::new_string_context(
                format!("invalid res0 {res0}, expected 0"),
                reader.stream_position()?,
                "validate res0 for ResTableTypeSpec",
            ));
        }

        let types_count =
            u16::read_no_opts(reader).add_context(|| "read types_count for ResTableTypeSpec")?;
        let entry_count =
            u32::read_no_opts(reader).add_context(|| "read entry_count for ResTableTypeSpec")?;

        let config_masks = <Vec<u32>>::read_vec(reader, entry_count as usize)
            .add_context(|| "read config_masks for ResTableTypeSpec")?;

        Ok(Self {
            id,
            types_count,
            config_masks,
        })
    }
}

impl Writeable for ResTableTypeSpec {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.id
            .write_no_opts(writer)
            .add_context(|| "write id for ResTableTypeSpec")?;
        let res0: u8 = 0;
        res0.write_no_opts(writer)
            .add_context(|| "write res0 for ResTableTypeSpec")?;

        self.types_count
            .write_no_opts(writer)
            .add_context(|| "write types_count for ResTableTypeSpec")?;
        let entry_count: u32 = self.config_masks.len() as u32;
        entry_count
            .write_no_opts(writer)
            .add_context(|| "write entry_count for ResTableTypeSpec")?;

        self.config_masks
            .write_vec(writer)
            .add_context(|| "write config_masks for ResTableTypeSpec")
    }
}

impl HeaderSizeStatic for ResTableTypeSpec {
    fn header_size() -> usize {
        8
    }
}

#[derive(Debug, PartialEq, Default, Copy, Clone)]
pub struct ResTableTypeFlags {
    pub flags: u8,
}

impl Readable for ResTableTypeFlags {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            flags: u8::read_no_opts(reader).add_context(|| "read flags for ResTableTypeFlags")?,
        })
    }
}

impl Writeable for ResTableTypeFlags {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.flags
            .write_no_opts(writer)
            .add_context(|| "write flags for ResTableTypeFlags")
    }
}

#[derive(Debug, PartialEq, Clone, Default, Hash, Eq, Copy)]
pub struct ResTableConfig {
    pub imsi: Option<u32>,
    pub locale: Option<u32>,
    pub screen_type: Option<u32>,
    pub input: Option<u32>,
    pub screen_size: Option<u32>,
    pub version: Option<u32>,
    pub screen_config: Option<u32>,
    pub screen_size_dp: Option<u32>,
    pub locale_script: Option<FixedString<4>>,
    pub locale_variant: Option<FixedString<8>>,
    pub screen_config_2: Option<u32>,
    pub locale_script_was_computed: Option<bool>,
    pub locale_numbering_system: Option<FixedString<8>>,
}

impl Writeable for ResTableConfig {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let sp = writer.stream_position()?;
        let size: u32 = self.get_size() as u32;
        size.write_no_opts(writer)?;
        if let Some(imsi) = self.imsi {
            imsi.write_no_opts(writer)?;
        }
        if let Some(locale) = self.locale {
            locale.write_no_opts(writer)?;
        }
        if let Some(screen_type) = self.screen_type {
            screen_type.write_no_opts(writer)?;
        }
        if let Some(input) = self.input {
            input.write_no_opts(writer)?;
        }
        if let Some(screen_size) = self.screen_size {
            screen_size.write_no_opts(writer)?;
        }
        if let Some(version) = self.version {
            version.write_no_opts(writer)?;
        }
        if let Some(screen_config) = self.screen_config {
            screen_config.write_no_opts(writer)?;
        }
        if let Some(screen_size_dp) = self.screen_size_dp {
            screen_size_dp.write_no_opts(writer)?;
        }
        if let Some(locale_script) = self.locale_script {
            locale_script.write_no_opts(writer)?;
        }
        if let Some(locale_variant) = self.locale_variant {
            locale_variant.write_no_opts(writer)?;
        }
        if let Some(screen_config_2) = self.screen_config_2 {
            screen_config_2.write_no_opts(writer)?;
        }
        if let Some(locale_script_was_computed) = self.locale_script_was_computed {
            locale_script_was_computed.write_no_opts(writer)?;
        }
        if let Some(locale_numbering_system) = self.locale_numbering_system {
            locale_numbering_system.write_no_opts(writer)?;
        }

        let remaining = writer.stream_position()? - sp;

        if size as u64 > remaining {
            for _ in 0..(size as u64 - remaining) {
                0u8.write_no_opts(writer)?;
            }
        }

        Ok(())
    }
}

impl Readable for ResTableConfig {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let start_offset = reader.stream_position()?;
        let size = u32::read_no_opts(reader)?;

        let imsi = if size >= 8 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let locale = if size >= 12 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let screen_type = if size >= 16 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let input = if size >= 20 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let screen_size = if size >= 24 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let version = if size >= 28 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let screen_config = if size >= 32 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let screen_size_dp = if size >= 36 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let locale_script = if size >= 40 {
            Some(<FixedString<4>>::read_no_opts(reader)?)
        } else {
            None
        };

        let locale_variant = if size >= 48 {
            Some(<FixedString<8>>::read_no_opts(reader)?)
        } else {
            None
        };

        let screen_config_2 = if size >= 52 {
            Some(u32::read_no_opts(reader)?)
        } else {
            None
        };

        let locale_script_was_computed = if size >= 53 {
            Some(bool::read_no_opts(reader)?)
        } else {
            None
        };

        let locale_numbering_system = if size >= 61 {
            Some(<FixedString<8>>::read_no_opts(reader)?)
        } else {
            None
        };

        reader.seek(SeekFrom::Start(start_offset + size as u64))?;

        Ok(Self {
            imsi,
            locale,
            screen_type,
            input,
            screen_size,
            version,
            screen_config,
            screen_size_dp,
            locale_script,
            locale_variant,
            screen_config_2,
            locale_script_was_computed,
            locale_numbering_system,
        })
    }
}
impl ResTableConfig {
    pub fn get_size(&self) -> usize {
        let mut size = 4;

        if self.imsi.is_none() {
            return size;
        }

        size += 4;

        if self.locale.is_none() {
            return size;
        }

        size += 4;

        if self.screen_type.is_none() {
            return size;
        }

        size += 4;

        if self.input.is_none() {
            return size;
        }

        size += 4;

        if self.screen_size.is_none() {
            return size;
        }

        size += 4;

        if self.version.is_none() {
            return size;
        }

        size += 4;

        if self.screen_config.is_none() {
            return size;
        }

        size += 4;

        if self.screen_size_dp.is_none() {
            return size;
        }

        size += 4;

        if self.locale_script.is_none() {
            return size;
        }

        size += 4;

        if self.locale_variant.is_none() {
            return size;
        }

        size += 8;

        if self.screen_config_2.is_none() {
            return size;
        }

        size += 4;

        if self.locale_script_was_computed.is_none() {
            return size;
        }

        size += 1;

        if self.locale_numbering_system.is_none() {
            return size;
        }

        size += 8;

        size = align(size as u64, 4) as usize;

        size
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub struct FixedString<const N: usize> {
    data: [u8; N],
}

impl<const N: usize> Readable for FixedString<N> {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            data: <[u8; N]>::read_no_opts(reader)
                .add_context(|| format!("reading data for FixedString<{N}>"))?,
        })
    }
}

impl<const N: usize> Writeable for FixedString<N> {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.data
            .write_no_opts(writer)
            .add_context(|| format!("write data for FixedString<{N}>"))
    }
}

impl<const N: usize> Display for FixedString<N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(&self.data))
    }
}

#[derive(Debug)]
pub struct InvalidLength {
    pub expected: usize,
    pub got: usize,
}

impl<const N: usize> TryFrom<String> for FixedString<N> {
    type Error = InvalidLength;
    fn try_from(value: String) -> Result<Self, InvalidLength> {
        let bytes = value.into_bytes();
        if bytes.len() != N {
            return Err(InvalidLength {
                expected: N,
                got: bytes.len(),
            });
        }
        Ok(Self {
            data: bytes.try_into().unwrap(),
        })
    }
}

impl ResTableTypeFlags {
    /// If set, the entry is sparse, and encodes both the entry ID and offset into each entry, and
    /// a binary search is used to find the key. Only availiable on platforms >= O.
    /// Mark anu types that use this with a v26 qualifier to prevent runtime issues on older
    /// platforms.
    pub fn sparse(&self) -> bool {
        (self.flags & 0x01) != 0
    }

    pub fn with_sparse(mut self) -> Self {
        self.flags |= 0x01;
        self
    }

    /// If set, the offsets to the entries are encoded in 16-bit, real_offset = offset * 4u
    /// A 16-bit offset of 0xffffu means a NO_ENTRY
    // TODO: do stuff with this...
    // FIXME: probably causes errors for apks that use this
    pub fn offset_16(&self) -> bool {
        (self.flags & 0x02) != 0
    }
}

/// A collection of resource entries for a particular resource data type.
///
/// If the flag FLAG_SPARSE is not set in `flags`, then this struct is followed by an array of
/// uint32_t defining the resource values, corresponding to the array of the type strings in the
/// ResTable_package::type_strings string block. Each of these hold an index from entries_start; a
/// value of NO_ENTRY means that entry is not defined.
///
/// If the flag FLAG_SPARSE is set in `flags`, then this struct is followed by an array of
/// ResTable_sparseTypeEntry defining only the entries that have values for this type. Each entry
/// is sorted by their entry ID such that a binary search can be performed over the entries. The ID
/// and offset are encoded in a uint32_t. See ResTable_sparseTypeEntry
///
/// There may be multiple of these chunks for a particular resource type, supply different
/// configuration variations for the resource values of that type.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableType {
    /// The type identifier this chunk is holding. Type IDs start at 1 (corresponding the the value
    /// of the type bits in a resource identifier). 0 is invalid.
    pub id: u8,
    pub flags: ResTableTypeFlags,

    /// Configuration this collection of entries is designed for. This must always be last.
    pub config: ResTableConfig,
    pub entries: Vec<(usize, Option<ResTableEntry>)>, // TODO: make this a hashmap bro
}

impl Writeable for ResTableType {
    type Args = ();
    fn write<W: Write + Seek>(mut self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let header_size = self.header_size() + ResChunk::header_size();
        let header_offset = ResChunk::get_header_offset(writer.stream_position()?);

        let sparse = self.flags.sparse();

        self.id
            .write_no_opts(writer)
            .add_context(|| "write id for ResTableType")?;
        self.flags
            .write_no_opts(writer)
            .add_context(|| "write flags for ResTableType")?;

        let reserved: u16 = 0;
        reserved
            .write_no_opts(writer)
            .add_context(|| "write reserved for ResTableType")?;

        let pos = writer.stream_position()?;
        let entry_indicies = calculate_entry_indicies(&self.entries, sparse).map_err(|e| {
            StreamError::new_string_context(e, pos, "calculate entry_indicies for ResTableType")
        })?;

        let entry_count: u32 = entry_indicies.len() as u32;
        entry_count
            .write_no_opts(writer)
            .add_context(|| "write entry_count for ResTableType")?;

        self.entries.sort_by_key(|e| e.0);

        let entries_start: u32 = calc_entries_start(&self.config, entry_indicies.len());
        entries_start
            .write_no_opts(writer)
            .add_context(|| "write entries_start for ResTableType")?;

        self.config
            .write_no_opts(writer)
            .add_context(|| "write config for ResTableType")?;

        writer.seek(SeekFrom::Start(header_offset + header_size as u64))?;
        entry_indicies
            .clone()
            .write_no_opts(writer)
            .add_context(|| "write entry_indicies for ResTableType")?;

        writer.seek(SeekFrom::Start(header_offset + entries_start as u64))?;

        self.entries
            .write(writer, entry_indicies)
            .add_context(|| "write entries for ResTableType")?;

        Ok(())
    }
}

impl Readable for ResTableType {
    type Args = usize;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        let header_offset = ResChunk::get_header_offset(reader.stream_position()?);
        let id = u8::read_no_opts(reader).add_context(|| "read id for ResTableType")?;
        let flags = ResTableTypeFlags::read_no_opts(reader)
            .add_context(|| "read flags for ResTableType")?;

        let reserved =
            u16::read_no_opts(reader).add_context(|| "read reserved for ResTableType")?;

        if reserved != 0 {
            return Err(StreamError::new_string_context(
                format!("invalid reserved value: {reserved}, expected 0"),
                reader.stream_position()?,
                "validate reserved for ResTableType",
            ));
        }
        let entry_count =
            u32::read_no_opts(reader).add_context(|| "read entry_count for ResTableType")?;
        let entries_start =
            u32::read_no_opts(reader).add_context(|| "read entries_start for ResTableType")?;

        let config =
            ResTableConfig::read_no_opts(reader).add_context(|| "read config for ResTableType")?;

        reader.seek(SeekFrom::Start(header_offset + args as u64))?;

        let entry_indicies =
            ResTableTypeEntryIndicies::read(reader, (entry_count as usize, flags.sparse()))
                .add_context(|| "read entry_indicies for ResTableType")?;

        reader.seek(SeekFrom::Start(header_offset + entries_start as u64))?;

        let entries = <Vec<(usize, Option<ResTableEntry>)>>::read(reader, entry_indicies)
            .add_context(|| "read entries for ResTableType")?;

        Ok(Self {
            id,
            flags,
            config,
            entries,
        })
    }
}

impl Writeable for Vec<(usize, Option<ResTableEntry>)> {
    type Args = ResTableTypeEntryIndicies;
    fn write<W: Write + Seek>(self, writer: &mut W, args: Self::Args) -> StreamResult<()> {
        let sp = writer.stream_position()?;
        match args {
            ResTableTypeEntryIndicies::NoSparse(items) => {
                for (i, ind) in items.into_iter().enumerate() {
                    if ind == 0xffffffff {
                        continue;
                    }
                    let mut found = false;
                    writer.seek(SeekFrom::Start(sp + ind as u64))?;
                    for item in &self {
                        if item.0 == i {
                            if let Some(ref item) = item.1 {
                                item.clone().write_no_opts(writer)?;
                            }
                            found = true;
                            break;
                        }
                    }
                    if !found {
                        return Err(StreamError::new_string_context(
                            format!("could not find entry with id: {i}"),
                            writer.stream_position()?,
                            "writing sparse entries",
                        ));
                    }
                }
            }
            ResTableTypeEntryIndicies::Sparse(items) => {
                for val in items {
                    let new_pos = sp + (val.offset as u64) * 4;
                    writer.seek(SeekFrom::Start(new_pos))?;
                    let mut found = false;
                    for item in &self {
                        if item.0 == val.idx as usize {
                            if let Some(ref item) = item.1 {
                                item.clone().write_no_opts(writer)?;
                                found = true;
                                break;
                            } else {
                                return Err(StreamError::new_string_context(
                                    InvalidEntry::InvalidEntry,
                                    writer.stream_position()?,
                                    format!("entry cannot be None in sparse mode!"),
                                ));
                            }
                        }
                    }
                    if !found {
                        return Err(StreamError::new_string_context(
                            format!("could not find entry with id: {}", val.idx),
                            writer.stream_position()?,
                            "writing sparse entries",
                        ));
                    }
                }
            }
        }

        Ok(())
    }
}

impl HeaderSizeInstance for ResTableType {
    fn header_size(&self) -> usize {
        1 + 1 + 2 + 4 + 4 + self.config.get_size()
    }
}

impl ResTableType {
    pub fn get_entry(&self, id: usize) -> Option<&ResTableEntry> {
        for entry in &self.entries {
            if entry.0 == id {
                return entry.1.as_ref();
            }
        }
        None
    }

    pub fn get_entry_mut(&mut self, id: usize) -> Option<&mut ResTableEntry> {
        if !self.flags.sparse() {
            let entry = self.entries.get_mut(id)?;

            if entry.0 != id {
                return None;
            }

            entry.1.as_mut()
        } else {
            for entry in self.entries.iter_mut() {
                if entry.0 == id {
                    return entry.1.as_mut();
                }
            }
            None
        }
    }
}

#[derive(Debug)]
pub enum InvalidEntry {
    InvalidID { expected_id: usize, got_id: usize },
    InvalidEntry,
}

impl Display for InvalidEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidID {
                expected_id,
                got_id,
            } => write!(
                f,
                "invalid entry, expected entry id {expected_id}, got {got_id}"
            ),
            Self::InvalidEntry => write!(f, "invalid entry, entry cannot be None"),
        }
    }
}

fn calculate_entry_indicies(
    entries: &Vec<(usize, Option<ResTableEntry>)>,
    sparse: bool,
) -> Result<ResTableTypeEntryIndicies, InvalidEntry> {
    let mut pos: usize = 0;

    Ok(match sparse {
        true => {
            let mut indicies: Vec<ResTableSparseTypeEntry> = Vec::new();
            for (id, entry) in entries {
                if entry.is_none() {
                    return Err(InvalidEntry::InvalidEntry);
                }
                let size = (entry.as_ref())
                    .ok_or(InvalidEntry::InvalidEntry)?
                    .get_size();
                indicies.push(ResTableSparseTypeEntry {
                    idx: (*id) as u16,
                    offset: pos as u16,
                });

                pos += size / 4;
            }
            ResTableTypeEntryIndicies::Sparse(indicies)
        }
        false => {
            let mut indicies: Vec<u32> = Vec::new();
            let max_index = entries.iter().map(|v| v.0).max();
            if let Some(max) = max_index {
                for ind in 0..=max {
                    let mut found = false;
                    for (id, entry) in entries.iter() {
                        if *id == ind {
                            if let Some(entry) = entry {
                                indicies.push(pos as u32);
                                pos += entry.get_size();
                            } else {
                                indicies.push(0xffffffff);
                            }
                            found = true;
                            break;
                        }
                    }
                    if !found {
                        indicies.push(0xffffffff);
                    }
                }
            }
            ResTableTypeEntryIndicies::NoSparse(indicies)
        }
    })
}

impl Readable for Vec<(usize, Option<ResTableEntry>)> {
    type Args = ResTableTypeEntryIndicies;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        let start_pos = reader.stream_position()?;
        match args {
            ResTableTypeEntryIndicies::NoSparse(indcs) => {
                let mut data: Vec<(usize, Option<ResTableEntry>)> = Vec::with_capacity(indcs.len());
                for (i, offset) in indcs.into_iter().enumerate() {
                    if offset == 0xffffffff {
                        data.push((i, None));
                    } else {
                        reader.seek(SeekFrom::Start(start_pos + offset as u64))?;
                        data.push((
                            i,
                            Some(ResTableEntry::read_no_opts(reader).add_context(
                                || "read entry for ResTableTypeEntryIndicies::NoSparse",
                            )?),
                        ));
                    }
                }

                Ok(data)
            }
            ResTableTypeEntryIndicies::Sparse(sp) => {
                let mut data: Vec<(usize, Option<ResTableEntry>)> = Vec::with_capacity(sp.len());

                for v in sp {
                    reader.seek(SeekFrom::Start(start_pos + (v.offset as u64) * 4))?;
                    data.push((
                        v.idx as usize,
                        Some(
                            ResTableEntry::read_no_opts(reader).add_context(
                                || "read entry for ResTableTypeEntryIndicies::Sparse",
                            )?,
                        ),
                    ));
                }

                Ok(data)
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct ResTableEntryFlags(u16);

impl Readable for ResTableEntryFlags {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self(
            u16::read_no_opts(reader).add_context(|| "read flags for ResTableEntryFlags")?,
        ))
    }
}

impl Writeable for ResTableEntryFlags {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.0
            .write_no_opts(writer)
            .add_context(|| "write flags for ResTableEntryFlags")
    }
}

impl ResTableEntryFlags {
    /// If set, this is a compex entry, holding a set of name/value mappings. It is followed by an
    /// array of ResTableMap structures.
    pub fn complex(&self) -> bool {
        self.0 & 0x1 != 0
    }

    /// If set, this resource has been declared public, so libraries are allowed to reference it.
    pub fn public(&self) -> bool {
        self.0 & 0x2 != 0
    }

    /// If set, this is a weak resource and may be overriden by strong resources of the same
    /// name/types. This is only useful during linking with other resource tables.
    pub fn weak(&self) -> bool {
        self.0 & 0x4 != 0
    }

    /// If set, this is a compact entry with data type and value directly encoded in the entry, see
    /// ResTable_entry::compact
    pub fn compact(&self) -> bool {
        self.0 & 0x8 != 0
    }
}

/// This is the beginning of information about an entry in the resource table. It holds the
/// reference to the name of this entry, and is immediately followed by one of:
///
/// - A ResValue structure, if FLAG_COMPLEX is -not- set.
/// - An array of ResTableMap structures, if FLAG_COMPLEX is set.
/// - If FLAG_COMPACT is set, this entry is a compact entry for simple values only
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableEntry {
    /// Number of bytes in this structure
    pub flags: ResTableEntryFlags,

    pub data: ResTableEntryValue,
}

impl Readable for ResTableEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let _header_size =
            u16::read_no_opts(reader).add_context(|| "read header_size for ResTableEntry")?;
        let flags = ResTableEntryFlags::read_no_opts(reader)
            .add_context(|| "read flags for ResTableEntry")?;

        let data = ResTableEntryValue::read(reader, flags)
            .add_context(|| "read data for ResTableEntryValue")?;

        Ok(Self { flags, data })
    }
}

impl Writeable for ResTableEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let header_size: u16 = self.header_size() as u16;
        header_size
            .write_no_opts(writer)
            .add_context(|| "write header_size for ResTableEntry")?;

        self.flags
            .write_no_opts(writer)
            .add_context(|| "write flags for ResTableEntry")?;

        self.data
            .write_no_opts(writer)
            .add_context(|| "write data for ResTableEntry")
    }
}

impl HeaderSizeInstance for ResTableEntry {
    fn header_size(&self) -> usize {
        4 + self.data.header_size()
    }
}

impl ResTableEntry {
    pub fn get_size(&self) -> usize {
        4 + self.data.get_size()
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum ResTableEntryValue {
    ResValue(ResTableResValueEntry),
    Map(ResTableMapEntry),
    Compact(u32), // TODO: handle this better
}

impl HeaderSizeInstance for ResTableEntryValue {
    fn header_size(&self) -> usize {
        match self {
            ResTableEntryValue::Compact(_) => 0,
            ResTableEntryValue::ResValue(_) => 4,
            ResTableEntryValue::Map(_) => 12,
        }
    }
}

impl ResTableEntryValue {
    pub fn is_compact(&self) -> bool {
        matches!(self, ResTableEntryValue::Compact(_))
    }

    pub fn is_complex(&self) -> bool {
        matches!(self, ResTableEntryValue::Map(_))
    }

    pub fn get_size(&self) -> usize {
        match self {
            ResTableEntryValue::ResValue(r) => r.get_size(),
            ResTableEntryValue::Map(m) => m.get_size(),
            ResTableEntryValue::Compact(_) => 0x4,
        }
    }
}

/// Extended form of a ResTable_entry for map entries, defining a parent map resource from which to
/// inherit values.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableMapEntry {
    /// Reference into ResTable_package::key_strings identifying this entry.
    pub key: ResStringPoolRef,
    /// Resource identifier of the parent mapping, or 0 if there is none.
    /// This is always treated as a TYPE_DYNAMIC_REFERENCE.
    pub parent: ResTableRef,

    pub map: Vec<ResTableMap>,
}

impl Readable for ResTableMapEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let key = ResStringPoolRef::read_no_opts(reader)
            .add_context(|| "read key for ResTableMapEntry")?;
        let parent =
            ResTableRef::read_no_opts(reader).add_context(|| "read parent for ResTableMapEntry")?;
        let count = u32::read_no_opts(reader).add_context(|| "read count for ResTableMapEntry")?;
        let map = <Vec<ResTableMap>>::read_vec(reader, count as usize)
            .add_context(|| "read map for ResTableMapEntry")?;

        Ok(Self { key, parent, map })
    }
}

impl Writeable for ResTableMapEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.key
            .write_no_opts(writer)
            .add_context(|| "write key for ResTableMapEntry")?;
        self.parent
            .write_no_opts(writer)
            .add_context(|| "write parent for ResTableMapEntry")?;
        let count: u32 = self.map.len() as u32;
        count
            .write_no_opts(writer)
            .add_context(|| "write count for ResTableMapEntry")?;
        self.map
            .write_vec(writer)
            .add_context(|| "write map for ResTableMapEntry")
    }
}

impl ResTableMapEntry {
    pub fn get_size(&self) -> usize {
        4 + 4 + 4 + self.map.len() * (4 + 8)
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ResTableResValueEntry {
    /// Reference into ResTable_package::key_strings identifying this entry.
    pub key: ResStringPoolRef,
    pub data: ResValue,
}

impl Readable for ResTableResValueEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            key: ResStringPoolRef::read_no_opts(reader)
                .add_context(|| "read key for ResTableResValueEntry")?,
            data: ResValue::read_no_opts(reader)
                .add_context(|| "read data for ResTableValueEntry")?,
        })
    }
}

impl Writeable for ResTableResValueEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.key
            .write_no_opts(writer)
            .add_context(|| "write key for ResTableResValueEntry")?;
        self.data
            .write_no_opts(writer)
            .add_context(|| "write data for ResTableResValueEntry")
    }
}

impl ResTableResValueEntry {
    pub fn get_size(&self) -> usize {
        4 + 8
    }
}

/// A single name/value mapping that is part of a complex resource entry.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ResTableMap {
    /// The resource identifier defining this mapping's name. For attribute resources, 'name' can
    /// be one of the following special resource types to supply meta-data about the attribute; for
    /// all other resource types it must be an attribute resource.
    pub name: ResTableRef,

    /// This mapping's value
    pub value: ResValue,
}

impl Readable for ResTableMap {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            name: ResTableRef::read_no_opts(reader).add_context(|| "read name for ResTableMap")?,
            value: ResValue::read_no_opts(reader).add_context(|| "read value for ResTableMap")?,
        })
    }
}

impl Writeable for ResTableMap {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.name
            .write_no_opts(writer)
            .add_context(|| "write name for ResTableMap")?;
        self.value
            .write_no_opts(writer)
            .add_context(|| "write value for ResTableMap")
    }
}

impl Readable for ResTableEntryValue {
    type Args = ResTableEntryFlags;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        if args.compact() {
            Ok(ResTableEntryValue::Compact(
                u32::read_no_opts(reader)
                    .add_context(|| "read entries for ResTableEntryValue::Compact")?,
            ))
        } else if args.complex() {
            Ok(ResTableEntryValue::Map(
                ResTableMapEntry::read_no_opts(reader)
                    .add_context(|| "read entries for ResTableEntryValue::Map")?,
            ))
        } else {
            Ok(ResTableEntryValue::ResValue(
                ResTableResValueEntry::read_no_opts(reader)
                    .add_context(|| "read entries for ResTableEntryValue::ResValue")?,
            ))
        }
    }
}

impl Writeable for ResTableEntryValue {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        match self {
            Self::ResValue(v) => v
                .write_no_opts(writer)
                .add_context(|| "write value for ResTableEntryValue::ResValue"),
            Self::Map(v) => v
                .write_no_opts(writer)
                .add_context(|| "write value for ResTableEntryValue::Map"),
            Self::Compact(v) => v
                .write_no_opts(writer)
                .add_context(|| "write value for ResTableEntryValue::Compact"),
        }
    }
}

fn calc_entries_start(config: &ResTableConfig, total_entries: usize) -> u32 {
    8 + 1 + 1 + 2 + 4 + 4 + config.get_size() as u32 + (total_entries as u32 * 4)
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResTableSparseTypeEntry {
    pub idx: u16,
    pub offset: u16,
}

impl Readable for ResTableSparseTypeEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            idx: u16::read_no_opts(reader)
                .add_context(|| "read idx for ResTableSparseTypeEntry")?,
            offset: u16::read_no_opts(reader)
                .add_context(|| "read offset for ResTableSparseTypeEntry")?,
        })
    }
}

impl Writeable for ResTableSparseTypeEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.idx
            .write_no_opts(writer)
            .add_context(|| "write idx for ResTableSparseTypeEntry")?;
        self.offset
            .write_no_opts(writer)
            .add_context(|| "write offset for ResTableSparseTypeEntry")
    }
}

impl ResTableSparseTypeEntry {
    pub fn get_size() -> usize {
        2 + 2
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ResTableTypeEntryIndicies {
    NoSparse(Vec<u32>),
    Sparse(Vec<ResTableSparseTypeEntry>),
}

impl Writeable for ResTableTypeEntryIndicies {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        match self {
            Self::Sparse(e) => e
                .write_vec(writer)
                .add_context(|| "write entries for ResTableTypeEntryIndicies::Sparse"),
            Self::NoSparse(e) => e
                .write_vec(writer)
                .add_context(|| "write entries for ResTableTypeEntryIndicies::NoSparse"),
        }
    }
}

impl Readable for ResTableTypeEntryIndicies {
    type Args = (usize, bool);
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        if args.1 {
            Ok(ResTableTypeEntryIndicies::Sparse(
                <Vec<ResTableSparseTypeEntry>>::read_vec(reader, args.0)
                    .add_context(|| "read entries for ResTableTypeEntryIndicies::Sparse")?,
            ))
        } else {
            Ok(ResTableTypeEntryIndicies::NoSparse(
                <Vec<u32>>::read_vec(reader, args.0)
                    .add_context(|| "read entries for RestableTypeEntryIndicies::NoSparse")?,
            ))
        }
    }
}

impl ResTableTypeEntryIndicies {
    pub fn is_sparse(&self) -> bool {
        match self {
            ResTableTypeEntryIndicies::Sparse(_) => true,
            ResTableTypeEntryIndicies::NoSparse(_) => false,
        }
    }

    pub fn len(&self) -> usize {
        match self {
            ResTableTypeEntryIndicies::NoSparse(ent) => ent.len(),
            ResTableTypeEntryIndicies::Sparse(ent) => ent.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A collection of resource data types within a package. Followed by one or more ResTable_type and
/// ResTable_typeSpec structures containing the entry values for each resource type.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTablePackage {
    /// If this is a base package, its ID. Package IDs start at 1 (corresponding to the value of
    /// the package bits in a resource identifier). 0 means this is not a base package.
    pub id: u32,

    /// Actual name of this package, null terminated
    pub name: String,

    /// Last index into type_strings that is for public use by others.
    pub last_public_type: u32,

    /// Last index into key_strings that is for public use by others.
    pub last_public_key: u32,
    pub type_id_offset: u32,
    pub string_pool_type: StringPoolHandler,
    pub string_pool_key: StringPoolHandler,
    pub chunks: Vec<ResChunk>,
}

macro_rules! mut_ref_remove {
    ($mut:ident, $ref:ident, $remove:ident, $type:ty, $variant:ident) => {
        pub fn $mut(&mut self) -> Option<&mut $type> {
            self.chunks.iter_mut().find_map(|v| {
                if let ResTypeValue::$variant(ref mut lib) = v.data {
                    Some(lib)
                } else {
                    None
                }
            })
        }
        pub fn $ref(&self) -> Option<&$type> {
            self.chunks.iter().find_map(|v| {
                if let ResTypeValue::$variant(ref lib) = v.data {
                    Some(lib)
                } else {
                    None
                }
            })
        }
        pub fn $remove(&mut self) -> Option<$type> {
            let pos = self
                .chunks
                .iter()
                .position(|v| matches!(v.data, ResTypeValue::$variant(_)))?;

            if let ResTypeValue::$variant(lib) = self.chunks.remove(pos).data {
                Some(lib)
            } else {
                None
            }
        }
    };
}

macro_rules! mut_ref_removes {
    ($mut:ident, $ref:ident, $remove:ident, $remove_all:ident, $type:ty, $variant:ident) => {
        pub fn $mut(&mut self) -> Vec<&mut $type> {
            self.chunks
                .iter_mut()
                .filter_map(|v| {
                    if let ResTypeValue::$variant(ref mut lib) = v.data {
                        Some(lib)
                    } else {
                        None
                    }
                })
                .collect()
        }
        pub fn $ref(&self) -> Vec<&$type> {
            self.chunks
                .iter()
                .filter_map(|v| {
                    if let ResTypeValue::$variant(ref lib) = v.data {
                        Some(lib)
                    } else {
                        None
                    }
                })
                .collect()
        }
        pub fn $remove(&mut self, id: u8) -> Option<$type> {
            let pos = self.chunks.iter().position(|v| {
                if let ResTypeValue::$variant(o) = &v.data {
                    o.id == id
                } else {
                    false
                }
            })?;

            if let ResTypeValue::$variant(lib) = self.chunks.remove(pos).data {
                Some(lib)
            } else {
                None
            }
        }
        pub fn $remove_all(&mut self) -> Vec<$type> {
            let poses = self
                .chunks
                .iter()
                .enumerate()
                .filter_map(|(i, v)| {
                    if let ResTypeValue::$variant(_) = &v.data {
                        Some(i)
                    } else {
                        None
                    }
                })
                .collect::<Vec<usize>>();

            let mut data = Vec::new();

            for pos in poses.iter().rev() {
                if let ResTypeValue::$variant(lib) = self.chunks.remove(*pos).data {
                    data.push(lib);
                }
            }

            data
        }
    };
}

impl ResTablePackage {
    mut_ref_remove!(
        library_mut,
        library_ref,
        remove_library,
        ResTableLib,
        TableLibrary
    );
    mut_ref_remove!(
        type_spec_mut,
        type_spec_ref,
        remove_type_spec,
        ResTableTypeSpec,
        TableSpec
    );

    mut_ref_removes!(
        table_type_mut,
        table_type_ref,
        remove_table_type,
        remove_table_types,
        ResTableType,
        TableType
    );
}

impl Mergeable for ResTablePackage {
    type Returns = ();
    fn merge(&mut self, mut other: Self) {
        let slib = self.library_mut();
        if let Some(slib) = slib {
            let olib = other.remove_library();
            if let Some(olib) = olib {
                slib.entries.extend(olib.entries);
            }
        }
        let s = self.type_spec_mut();
        if let Some(s) = s {
            let o = other.remove_type_spec();
            if let Some(o) = o {
                s.config_masks.extend(o.config_masks);
            }
        }

        self.string_pool_key.merge(other.string_pool_key);
    }
}

impl Readable for ResTablePackage {
    type Args = usize;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        let header_offset = ResChunk::get_header_offset(reader.stream_position()?);

        let id = u32::read_no_opts(reader).add_context(|| "read id for ResTablePackage")?;
        let name = read_utf16_fixed_null_string(reader, 128)
            .add_context(|| "read name for ResTablePackage")?;
        let type_strings =
            u32::read_no_opts(reader).add_context(|| "read type_strings for ResTablePackage")?;
        let last_public_type = u32::read_no_opts(reader)
            .add_context(|| "read last_public_type for ResTablePackage")?;

        let key_strings =
            u32::read_no_opts(reader).add_context(|| "read key_strings for ResTablePackage")?;
        let last_public_key =
            u32::read_no_opts(reader).add_context(|| "read last_public_key for ResTablePackage")?;

        let type_id_offset =
            u32::read_no_opts(reader).add_context(|| "read type_id_offset for ResTablePackage")?;

        reader.seek(SeekFrom::Start(header_offset + type_strings as u64))?;
        let string_pool_type = parse_string_pool(reader)
            .add_context(|| "read string_pool_type for ResTablePackage")?;

        reader.seek(SeekFrom::Start(header_offset + key_strings as u64))?;
        let string_pool_key =
            parse_string_pool(reader).add_context(|| "read string_pool_key for ResTablePackage")?;

        let size = args as u64 - (reader.stream_position()? - header_offset);

        let chunks = <Vec<ResChunk>>::read(reader, size)
            .add_context(|| "read chunks for ResTablePackage")?;

        Ok(Self {
            id,
            name,
            last_public_type,
            last_public_key,
            type_id_offset,
            string_pool_type,
            string_pool_key,
            chunks,
        })
    }
}

impl HeaderSizeStatic for ResTablePackage {
    fn header_size() -> usize {
        280
    }
}

impl ResTablePackage {
    pub fn resolve_ref(&self, reference: ResTableRef) -> Option<&ResTableEntry> {
        for chunk in &self.chunks {
            if let ResTypeValue::TableType(table_type) = &chunk.data {
                if table_type.id != reference.type_index {
                    continue;
                }
                return table_type.get_entry(reference.entry_index as usize);
            }
        }

        None
    }
    pub fn resolve_ref_mut(&mut self, reference: ResTableRef) -> Option<&mut ResTableEntry> {
        for chunk in self.chunks.iter_mut() {
            if let ResTypeValue::TableType(table_type) = &mut chunk.data {
                if table_type.id != reference.type_index {
                    continue;
                }
                return table_type.get_entry_mut(reference.entry_index as usize);
            }
        }

        None
    }
}

impl Writeable for ResTablePackage {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let header_offset = ResChunk::get_header_offset(writer.stream_position()?);
        self.id
            .write_no_opts(writer)
            .add_context(|| "write id for ResTablePackage")?;

        write_utf16_fixed_null_string(writer, &self.name, 128)
            .add_context(|| "write name for ResTablePackage")?;

        let type_strings_pos_pos = writer.stream_position()?;

        writer.seek_relative(4)?;

        self.last_public_type
            .write_no_opts(writer)
            .add_context(|| "write last_public_type for ResTablePackage")?;

        let key_strings_pos_pos = writer.stream_position()?;

        writer.seek_relative(4)?;

        self.last_public_key
            .write_no_opts(writer)
            .add_context(|| "write last_public_key for ResTablePackage")?;

        self.type_id_offset
            .write_no_opts(writer)
            .add_context(|| "write type_id_offset for ResTablePackage")?;

        // go back to write type_strings pos

        let type_string_pos = writer.stream_position()?;

        writer.seek(std::io::SeekFrom::Start(type_strings_pos_pos))?;

        let type_strings_pos2: u32 = (type_string_pos - header_offset) as u32;

        type_strings_pos2
            .write_no_opts(writer)
            .add_context(|| "write type_strings_pos for ResTablePackage")?;

        // go forward and write type_strings

        writer.seek(std::io::SeekFrom::Start(type_string_pos))?;

        write_string_pool(writer, self.string_pool_type)
            .add_context(|| "write string_pool_type for ResTablePackage")?;

        let key_string_pos = writer.stream_position()?;

        // go back and write key_strings pos

        writer.seek(std::io::SeekFrom::Start(key_strings_pos_pos))?;

        let key_strings_pos2: u32 = (key_string_pos - header_offset) as u32;

        key_strings_pos2
            .write_no_opts(writer)
            .add_context(|| "write key_strings_pos for ResTablePackage")?;

        // go forward and write key_strings

        writer.seek(std::io::SeekFrom::Start(key_string_pos))?;

        write_string_pool(writer, self.string_pool_key)
            .add_context(|| "write string_pool_key for ResTablePackage")?;

        self.chunks
            .write_vec(writer)
            .add_context(|| "write chunks for ResTablePackage")?;

        Ok(())
    }
}

#[derive(Debug)]
pub struct InvalidStringPoolResType;

impl Display for InvalidStringPoolResType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "expected string pool got something else")
    }
}

fn parse_string_pool<R: Read + Seek>(reader: &mut R) -> StreamResult<StringPoolHandler> {
    let start = reader.stream_position()?;
    let chunk =
        ResChunk::read_no_opts(reader).add_context(|| "read chunk for parse_string_pool")?;

    if let ResTypeValue::StringPool(sp) = chunk.data {
        return Ok(sp.into());
    }

    let res_type: ResType = (&chunk.data).into();

    Err(StreamError::new_string_context(
        format!("invalid res type: {res_type}, expected StringPool"),
        start,
        "validate chunk for parse_string_pool",
    ))
}

fn write_string_pool<W: Write + Seek>(
    writer: &mut W,
    string_pool: StringPoolHandler,
) -> StreamResult<()> {
    let chunk = ResChunk {
        data: ResTypeValue::StringPool(string_pool.string_pool),
    };
    chunk
        .write_no_opts(writer)
        .add_context(|| "write string pool chunk for write_string_pool")
}

fn read_utf16_fixed_null_string<R: Read + Seek>(
    reader: &mut R,
    length: usize,
) -> StreamResult<String> {
    let mut data: Vec<u16> = Vec::new();
    let start = reader.stream_position()?;
    let end = start + (length as u64) * 2;
    for _ in 0..length {
        let val = <u16>::read_no_opts(reader)
            .add_context(|| "read utf16 char for read_utf16_fixed_null_string")?;
        if val == 0 {
            reader.seek(std::io::SeekFrom::Start(end))?;
            break;
        }
        data.push(val);
    }

    String::from_utf16(data.as_slice()).map_err(|e| {
        StreamError::new_string_context(e, start, "decode utf16 for read_utf16_fixed_null_string")
    })
}

#[derive(Debug)]
pub struct PackageNameError(usize);

impl Display for PackageNameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "package name was too long, expected a length of less than 128, got a length of {}",
            self.0
        )
    }
}

fn write_utf16_fixed_null_string<W: Write + Seek>(
    writer: &mut W,
    string: &str,
    length: usize,
) -> StreamResult<()> {
    let mut data: Vec<u16> = string.encode_utf16().collect();
    if data.len() >= length {
        return Err(StreamError::new_string_context(
            format!("invalid data length {}, expected {}", data.len(), length),
            writer.stream_position()?,
            "validate data length for write_utf16_fixed_null_string",
        ));
    }
    data.resize(length, 0);
    data.write_vec(writer)
        .add_context(|| "write encoded utf16 data for write_utf16_fixed_null_string")?;

    Ok(())
}

/// **************
/// RESOURCE TABLE
/// **************
///
/// Header for a resource table. Its data contains a series of additional chunks:
///
/// - A ResStringPool_header containg all table values. This string pool contains all of the string
///   values in the entire resource table (not the names of entries or type identifiers however).
/// - One or more ResTable_package chunks.
///
/// Specific entries within a resource table can be uniquely identified with a single integer as
/// defined by the ResTable_ref structure.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTable {
    pub string_pool: StringPoolHandler,
    pub packages: Packages,
}
impl ResTable {
    pub fn resolve(&self, reference: ResTableRef) -> Option<&ResTableEntry> {
        self.packages.resolve(reference)
    }
}

impl Readable for ResTable {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let package_count =
            u32::read_no_opts(reader).add_context(|| "read package_count for ResTable")?;

        let string_pool =
            parse_string_pool(reader).add_context(|| "read string_pool for ResTable")?;
        let packages = Packages::read(reader, package_count as usize)
            .add_context(|| "read packages for ResTable")?;

        Ok(Self {
            string_pool,
            packages,
        })
    }
}

impl Writeable for ResTable {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let package_count: u32 = self.packages.packages.len() as u32;
        package_count
            .write_no_opts(writer)
            .add_context(|| "write package_count for ResTable")?;
        write_string_pool(writer, self.string_pool)
            .add_context(|| "write string_pool for ResTable")?;
        self.packages
            .write_no_opts(writer)
            .add_context(|| "write packages for ResTable")
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Packages {
    packages: Vec<ResChunk>,
}

impl Mergeable for Packages {
    type Returns = ();
    fn merge(&mut self, other: Self) {
        for opackage in other.into_packages() {
            let spackage = self.get_by_id_mut(opackage.id);
            if let Some(spackage) = spackage {
                spackage.merge(opackage);
            } else {
                self.add_package(opackage);
            }
        }
    }
}

impl Readable for Packages {
    type Args = usize;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            packages: <Vec<ResChunk>>::read_vec(reader, args)
                .add_context(|| "read packages for Packages")?,
        })
    }
}

impl Writeable for Packages {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.packages
            .write_vec(writer)
            .add_context(|| "write packages for Packages")
    }
}

impl Packages {
    pub fn new(packages: Vec<ResTablePackage>) -> Self {
        Self {
            packages: packages
                .into_iter()
                .map(|v| ResChunk {
                    data: ResTypeValue::TablePackage(v),
                })
                .collect(),
        }
    }
    pub fn get(&self, index: usize) -> Option<&ResTablePackage> {
        let item = self.packages.get(index)?;

        if let ResTypeValue::TablePackage(pkg) = &item.data {
            return Some(pkg);
        }
        None
    }

    pub fn get_mut(&mut self, index: usize) -> Option<&mut ResTablePackage> {
        let item = self.packages.get_mut(index)?;

        if let ResTypeValue::TablePackage(pkg) = &mut item.data {
            return Some(pkg);
        }
        None
    }

    pub fn into_packages(self) -> Vec<ResTablePackage> {
        self.packages
            .into_iter()
            .filter_map(|v| {
                if let ResTypeValue::TablePackage(pkg) = v.data {
                    Some(pkg)
                } else {
                    None
                }
            })
            .collect()
    }
    pub fn as_packages(&self) -> Vec<&ResTablePackage> {
        self.packages
            .iter()
            .filter_map(|v| {
                if let ResTypeValue::TablePackage(ref pkg) = v.data {
                    Some(pkg)
                } else {
                    None
                }
            })
            .collect()
    }

    pub fn get_by_id_mut(&mut self, id: u32) -> Option<&mut ResTablePackage> {
        for package in &mut self.packages {
            if let ResTypeValue::TablePackage(pkg) = &mut package.data {
                if pkg.id == id {
                    return Some(pkg);
                }
            }
        }
        None
    }

    pub fn add_package(&mut self, package: ResTablePackage) {
        self.packages.push(ResChunk {
            data: ResTypeValue::TablePackage(package),
        });
    }
    pub fn get_by_id(&self, id: u32) -> Option<&ResTablePackage> {
        for package in &self.packages {
            if let ResTypeValue::TablePackage(pkg) = &package.data {
                if pkg.id == id {
                    return Some(pkg);
                }
            }
        }
        None
    }

    pub fn first(&self) -> Option<&ResTablePackage> {
        self.get(0)
    }

    pub fn first_mut(&mut self) -> Option<&mut ResTablePackage> {
        self.get_mut(0)
    }

    pub fn resolve(&self, reference: ResTableRef) -> Option<&ResTableEntry> {
        self.get_by_id(reference.package_index as u32)?
            .resolve_ref(reference)
    }
}

impl HeaderSizeStatic for ResTable {
    fn header_size() -> usize {
        4
    }
}

#[derive(Debug)]
pub enum ResTableReadError {
    ReadFile(std::io::Error, PathBuf),
    Parse(StreamError),
}

impl Display for ResTableReadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                ResTableReadError::ReadFile(error, path_buf) => format!(
                    "failed to read file: {} due to {error}",
                    path_buf.to_string_lossy()
                ),
                ResTableReadError::Parse(stream_error) => stream_error.to_string(),
            }
        )
    }
}

impl ResTable {
    pub fn from_path(path: &Path) -> Result<Self, ResTableReadError> {
        Self::read_all(
            &mut std::fs::File::open(path)
                .map_err(|e| ResTableReadError::ReadFile(e, path.to_path_buf()))?,
        )
        .map_err(|e| ResTableReadError::Parse(e))
    }
    pub fn read_all<R: Seek + Read>(reader: &mut R) -> StreamResult<Self> {
        let pos = reader.stream_position()?;
        let header = ResChunk::read_no_opts(reader).add_context(|| "read chunk for ResTable")?;

        if let ResTypeValue::Table(table) = header.data {
            return Ok(table);
        }

        let res_type: ResType = (&header.data).into();

        Err(StreamError::new_string_context(
            format!("invalid res_type: {res_type}, expected ResTable"),
            pos,
            "validate read chunk for ResTable",
        ))
    }

    pub fn write_all<W: Seek + Write>(self, writer: &mut W) -> StreamResult<()> {
        let header = ResChunk {
            data: ResTypeValue::Table(self),
        };

        header
            .write_no_opts(writer)
            .add_context(|| "write chunk for ResTable")
    }
}

#[derive(Debug)]
pub struct WriteARSCError(pub std::io::Error);

impl Display for WriteARSCError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl From<std::io::Error> for WriteARSCError {
    fn from(value: std::io::Error) -> Self {
        Self(value)
    }
}

impl TryFrom<&[u8]> for ResTable {
    type Error = StreamError;
    fn try_from(value: &[u8]) -> Result<Self, StreamError> {
        let mut stream = Cursor::new(value);

        let val = ResTable::read_all(&mut stream)?;

        Ok(val)
    }
}

impl TryFrom<Vec<u8>> for ResTable {
    type Error = StreamError;
    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        Self::read_all(&mut Cursor::new(value))
    }
}

impl TryFrom<ResTable> for Vec<u8> {
    type Error = StreamError;
    fn try_from(value: ResTable) -> Result<Self, StreamError> {
        let mut stream = Cursor::new(Vec::new());

        value.write_all(&mut stream)?;

        Ok(stream.into_inner())
    }
}

/// A package-id to package name mapping for any shared libraries used in this resource table. The
/// package-id's encoded in this resource table may be different that the id's assigned at runtime.
/// We must be able to translate the package-id's based on the package name.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableLib {
    pub entries: Vec<ResTableLibEntry>,
}

impl Readable for ResTableLib {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let count = u32::read_no_opts(reader).add_context(|| "read count for ResTableLib")?;
        let entries = <Vec<ResTableLibEntry>>::read_vec(reader, count as usize)
            .add_context(|| "read entries for ResTableLib")?;

        Ok(Self { entries })
    }
}

impl Writeable for ResTableLib {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let count: u32 = self.entries.len() as u32;
        count
            .write_no_opts(writer)
            .add_context(|| "write count for ResTableLib")?;

        self.entries
            .write_vec(writer)
            .add_context(|| "write entries for ResTableLib")
    }
}

impl HeaderSizeStatic for ResTableLib {
    fn header_size() -> usize {
        4
    }
}

/// A shared library package-id to package name entry.
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableLibEntry {
    /// The package-id of this shared library was assigned at build time.
    /// We use a u32 to keep the structure aligned on a u32 boundary.
    pub package_id: u32,

    /// The package name of the shared library, \0 terminated
    pub package_name: String,
}

impl Readable for ResTableLibEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            package_id: u32::read_no_opts(reader)
                .add_context(|| "read package_id for ResTableLibEntry")?,
            package_name: read_utf16_fixed_null_string(reader, 128)
                .add_context(|| "read package_name for ResTableLibEntry")?,
        })
    }
}

impl Writeable for ResTableLibEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.package_id
            .write_no_opts(writer)
            .add_context(|| "write package_id for ResTableLibEntry")?;
        write_utf16_fixed_null_string(writer, &self.package_name, 128)
            .add_context(|| "write package_name for ResTableLibEntry")
    }
}

/// A map that allows rewriting staged (non-finalized) resource ids to their finalized counterparts
#[derive(Debug, PartialEq, Clone)]
pub struct ResTableStagedAlias {
    pub entries: Vec<ResTableStagedAliasEntry>,
}

impl Readable for ResTableStagedAlias {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let count =
            u32::read_no_opts(reader).add_context(|| "read count for ResTableStagedAlias")?;

        let entries = <Vec<ResTableStagedAliasEntry>>::read_vec(reader, count as usize)
            .add_context(|| "read entries for ResTableStagedAlias")?;

        Ok(Self { entries })
    }
}

impl Writeable for ResTableStagedAlias {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let count: u32 = self.entries.len() as u32;
        count
            .write_no_opts(writer)
            .add_context(|| "write count for ResTableStagedAlias")?;

        self.entries
            .write_vec(writer)
            .add_context(|| "write entries for ResTableStagedAlias")
    }
}

impl HeaderSizeStatic for ResTableStagedAlias {
    fn header_size() -> usize {
        4
    }
}

/// Maps the staged (non-finalized) resource id to its finalized resource id.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ResTableStagedAliasEntry {
    /// The compile-time staged resource id to rewrite.
    pub staged_res_id: u32,

    /// The compile-time finalized resource id to which the staged resource id should be rewritten.
    pub finalized_res_id: u32,
}

impl Readable for ResTableStagedAliasEntry {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            staged_res_id: u32::read_no_opts(reader)
                .add_context(|| "read staged_res_id for ResTableStagedAliasEntry")?,
            finalized_res_id: u32::read_no_opts(reader)
                .add_context(|| "read finalized_res_id for ResTableStagedAliasEntry")?,
        })
    }
}

impl Writeable for ResTableStagedAliasEntry {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.staged_res_id
            .write_no_opts(writer)
            .add_context(|| "write staged_res_id for ResTableStagedAliasEntry")?;
        self.finalized_res_id
            .write_no_opts(writer)
            .add_context(|| "write finalized_res_id for ResTableStagedAliasEntry")
    }
}

/// Specifies the set of resources that are explicitly allowed to be overlaid by RROs.
#[derive(Debug, Clone, PartialEq)]
pub struct ResTableOverlayable {
    /// The name of the overlayable set of resources that overlays target.
    pub name: String,

    /// The component responsible for enabling and disabling overlays targeting this chunk.
    pub actor: String,
}

impl Readable for ResTableOverlayable {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            name: read_utf16_fixed_null_string(reader, 256)
                .add_context(|| "read name for ResTableOverlayable")?,
            actor: read_utf16_fixed_null_string(reader, 256)
                .add_context(|| "read actor for ResTableOverlayable")?,
        })
    }
}

impl Writeable for ResTableOverlayable {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        write_utf16_fixed_null_string(writer, &self.name, 256)
            .add_context(|| "write name for ResTableOverlayable")?;
        write_utf16_fixed_null_string(writer, &self.actor, 256)
            .add_context(|| "write actor for ResTableOverlayable")
    }
}

impl HeaderSizeStatic for ResTableOverlayable {
    fn header_size() -> usize {
        1024
    }
}

/// Flags for a bitmask for all possible overlayable policy options.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct PolicyFlags {
    pub flags: u32,
}

impl Readable for PolicyFlags {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        Ok(Self {
            flags: u32::read_no_opts(reader).add_context(|| "read flags for PolicyFlags")?,
        })
    }
}

impl Writeable for PolicyFlags {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.flags
            .write_no_opts(writer)
            .add_context(|| "write flags for PolicyFlags")
    }
}

impl PolicyFlags {
    /// Any overlay can overlay these resources.
    pub fn public(&self) -> bool {
        self.flags & 1 != 0
    }
    /// The overlay must reside of the system partition or must have existed on the system
    /// partition before an upgrade to overlay these resources.
    pub fn system_partition(&self) -> bool {
        self.flags & 2 != 0
    }
    /// The overlay must reside of the vendor parition or must have existed on the vendor partition
    /// before an upgrade to overlay these resources.
    pub fn vendor_partition(&self) -> bool {
        self.flags & 4 != 0
    }
    /// The overlay must reside of the product partition or must have existed on the product
    /// partition before an upgrade to overlay these resources.
    pub fn product_partition(&self) -> bool {
        self.flags & 8 != 0
    }
    /// The overlay must be signed with the same signature as the package containing the target
    /// resource.
    pub fn signature(&self) -> bool {
        self.flags & 0x10 != 0
    }
    /// The overlay must reside of the odm partition or must have existed on the odm partition
    /// before an upgrade to overlay these resources.
    pub fn odm_parition(&self) -> bool {
        self.flags & 0x20 != 0
    }
    /// The overlay must reside of the oem partition or must have existed on the oem partition
    /// before an upgrade to overlay these resources.
    pub fn oem_partition(&self) -> bool {
        self.flags & 0x40 != 0
    }
    /// The overlay must be signed with the same signature as the actor declared for the target
    /// resource.
    pub fn actor_signature(&self) -> bool {
        self.flags & 0x80 != 0
    }
    /// The overlay must be signed with the same signature as the reference package declared in the
    /// SystemConfig
    pub fn config_signature(&self) -> bool {
        self.flags & 0x100 != 0
    }
}

/// Holds a list of resource ids that are protected from being overlaid by a set of policies. If
/// the overlay fulfils at least one of the policies, then the overlay can overlay the list of
/// resources.
#[derive(Debug, Clone, PartialEq)]
pub struct ResTableOverlayablePolicy {
    pub policy_flags: PolicyFlags,
    pub entries: Vec<ResTableRef>,
}

impl HeaderSizeStatic for ResTableOverlayablePolicy {
    fn header_size() -> usize {
        8
    }
}

impl Readable for ResTableOverlayablePolicy {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let policy_flags = PolicyFlags::read_no_opts(reader)
            .add_context(|| "read policy_flags for ResTableOverlayablePolicy")?;
        let entry_count = u32::read_no_opts(reader)
            .add_context(|| "read entry_count for ResTableOverlayablePolicy")?;

        let entries = <Vec<ResTableRef>>::read_vec(reader, entry_count as usize)
            .add_context(|| "read entries for ResTableOverlayablePolicy")?;

        Ok(Self {
            policy_flags,
            entries,
        })
    }
}

impl Writeable for ResTableOverlayablePolicy {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        self.policy_flags
            .write_no_opts(writer)
            .add_context(|| "write policy flags for ResTableOverlayablePolicy")?;
        let entry_count: u32 = self.entries.len() as u32;
        entry_count
            .write_no_opts(writer)
            .add_context(|| "write entry_count for ResTableOverlayablePolicy")?;
        self.entries
            .write_vec(writer)
            .add_context(|| "write entries for ResTableOverlayablePolicy")
    }
}

impl Mergeable for ResTable {
    type Returns = ();
    fn merge(&mut self, other: Self) {
        self.string_pool.merge(other.string_pool);
        self.packages.merge(other.packages);
    }
}