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
use std::{
    borrow::Cow,
    collections::HashMap,
    io::{Read, Seek, SeekFrom, Write},
    iter::zip,
    string::{FromUtf8Error, FromUtf16Error},
};

use crate::{
    align,
    defs::{HeaderSizeStatic, ResChunk},
    stream::{
        NewResultCtx, Readable, ReadableNoOptions, ResultCtx, StreamError, StreamResult,
        VecReadable, VecWritable, Writeable, WriteableNoOptions,
    },
    traits::Mergeable,
};

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub struct ResStringPoolRef {
    pub index: u32,
}

impl From<u8> for ResStringPoolRef {
    fn from(value: u8) -> Self {
        Self {
            index: value as u32,
        }
    }
}

impl Default for ResStringPoolRef {
    fn default() -> Self {
        Self::null()
    }
}

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

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

impl ResStringPoolRef {
    pub fn resolve(self, strings: &StringPoolHandler) -> Option<&str> {
        strings.resolve(self)
    }

    pub fn null() -> ResStringPoolRef {
        ResStringPoolRef { index: 0xffffffff }
    }
}

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

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

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

impl StringPoolFlags {
    /// If set, the string index is sorted by the string values (based on strcmp16()).
    pub fn sorted(&self) -> bool {
        self.flags & (1 << 0) != 0
    }

    /// String pool is encoded in UTF-8.
    pub fn utf8(&self) -> bool {
        self.flags & (1 << 8) != 0
    }

    /// Create new StringPoolFlags from separate utf8 and sorted boolean flags.
    pub fn new(sorted: bool, utf8: bool) -> Self {
        Self {
            flags: (sorted as u32) | ((utf8 as u32) << 8),
        }
    }

    pub fn set_utf8(&mut self) {
        self.flags |= 1 << 8;
    }

    pub fn set_utf16(&mut self) {
        self.flags &= !(1 << 8);
    }
}

/// A set of strings that can be referenced by others through a ResStringPool_ref.
///
/// Definition for a pool of strings. The data of this chunk is an array of u32 providing indices
/// into the pool, relative to stringsStart. At stringsStart are all of the UTF-8 or UTF-16 strings
/// concatenated together.
///
/// If styleCount is not zero, then immediately following the array of u32 indices into the string
/// table is another array of indices into a style table starting at stylesStart. Each entry in the
/// style table is an arry of ResStringPool_span structures.
#[derive(Debug, PartialEq, Default, Clone)]
pub struct StringPool {
    pub flags: StringPoolFlags,
    pub strings: StringPoolStrings,
    pub styles: Vec<ResStringPoolSpan>,
}

impl Mergeable for StringPool {
    type Returns = ();
    fn merge(&mut self, other: Self) {
        self.styles.extend_from_slice(&other.styles);
        for string in other.into_strings() {
            self.push_string(string);
        }
    }
}

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

        let string_count: u32 = self.strings.len() as u32;
        string_count
            .write_no_opts(writer)
            .add_context(|| "write string_count for StringPool")?;

        let style_count: u32 = self.styles.len() as u32;
        style_count
            .write_no_opts(writer)
            .add_context(|| "write style_count for StringPool")?;

        self.adjust_utf8();

        self.flags.write_no_opts(writer)?;

        let strings_start = calc_strings_start(
            header_offset,
            writer.stream_position()?,
            string_count,
            style_count,
        );
        strings_start
            .write_no_opts(writer)
            .add_context(|| "write strings_start for StringPool")?;

        let styles_start = calc_styles_start(
            header_offset,
            strings_start,
            &self.strings,
            style_count == 0,
        );
        styles_start
            .write_no_opts(writer)
            .add_context(|| "write styles_start for StringPool")?;

        // FIXME: don't really like this clones

        let string_indicies = calc_string_indices(&self.strings);
        string_indicies
            .clone()
            .write_vec(writer)
            .add_context(|| "write string_indicies for StringPool")?;

        let style_indicies = calc_style_indices(style_count);
        style_indicies
            .clone()
            .write_vec(writer)
            .add_context(|| "write style_indicies for StringPool")?;

        let is_str_utf8 = matches!(self.strings, StringPoolStrings::UTF8(_));

        if self.flags.utf8() != is_str_utf8 {
            return Err(StreamError::new_string_context(
                "self.flags.utf8() != self.strings.utf8()",
                writer.stream_position()?,
                "writing strings for StringPool",
            ));
        }

        self.strings
            .write(writer, string_indicies)
            .add_context(|| "write strings for StringPool")?;

        let current_pos = writer.stream_position()?;
        let aligned_pos = align(current_pos, 4);
        if aligned_pos > current_pos {
            let new_data = vec![0u8; (aligned_pos - current_pos) as usize];
            new_data
                .write_vec(writer)
                .add_context(|| "write pre-style padding for StringPool")?;
        }

        self.styles
            .write(writer, style_indicies)
            .add_context(|| "write styles for StringPool")?;

        let current_pos = writer.stream_position()?;
        let new_pos = align(current_pos, 4);
        if new_pos > current_pos {
            let new_data = vec![0u8; (new_pos - current_pos) as usize];
            new_data
                .write_vec(writer)
                .add_context(|| "write padding for StringPool")?;
        }

        Ok(())
    }
}

impl StringPool {
    pub fn adjust_utf8(&mut self) {
        match self.strings {
            StringPoolStrings::UTF8(_) => self.flags.set_utf8(),
            StringPoolStrings::UTF16(_) => self.flags.set_utf16(),
        }
    }
}

impl Readable for StringPool {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let header_offset = ResChunk::get_header_offset(reader.stream_position()?);
        let string_count =
            u32::read_no_opts(reader).add_context(|| "read string_count for StringPool")?;
        let style_count =
            u32::read_no_opts(reader).add_context(|| "read style count for StringPool")?;
        let flags =
            StringPoolFlags::read_no_opts(reader).add_context(|| "read flags for StringPool")?;

        let strings_start =
            u32::read_no_opts(reader).add_context(|| "read strings_start for StringPool")?;
        let styles_start =
            u32::read_no_opts(reader).add_context(|| "read styles_start for StringPool")?;

        let string_indicies = <Vec<u32>>::read_vec(reader, string_count as usize)
            .add_context(|| "read string_indicies for StringPool")?;
        let style_indicies = <Vec<u32>>::read_vec(reader, style_count as usize)
            .add_context(|| "read style_indicies for StringPool")?;

        reader
            .seek(SeekFrom::Start(header_offset + strings_start as u64))
            .stream_context(|| {
                format!(
                    "seek to strings position: header_offset: {header_offset}, strings_start: {strings_start} for StringPool"
                )
            })?;

        let strings = StringPoolStrings::read(reader, (flags.utf8(), string_indicies))
            .add_context(|| "read strings for StringPool")?;

        reader
            .seek(SeekFrom::Start(header_offset + styles_start as u64))
            .stream_context(|| {
                format!(
                    "seek to styles position: header_offset: {header_offset}, styles_start: {styles_start} for StringPool"
                )
            })?;

        let styles = <Vec<ResStringPoolSpan>>::read(reader, style_indicies)
            .add_context(|| "read styles for StringPool")?;

        Ok(Self {
            flags,
            strings,
            styles,
        })
    }
}

impl Readable for Vec<ResStringPoolSpan> {
    type Args = Vec<u32>;
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        let start_pos = reader.stream_position()?;
        let mut styles = Vec::with_capacity(args.len());

        for index in args {
            reader
                .seek(SeekFrom::Start(start_pos + index as u64))
                .stream_context(|| {
                    format!(
                        "seek to style position: start_pos: {start_pos}, index: {index} for Vec<ResStringPoolSpan>"
                    )
                })?;
            styles.push(
                ResStringPoolSpan::read_no_opts(reader)
                    .add_context(|| "read ResStringPoolSpan for Vec<ResStringPoolSpan>")?,
            );
        }

        Ok(styles)
    }
}

impl Writeable for Vec<ResStringPoolSpan> {
    type Args = Vec<u32>;
    fn write<W: Write + Seek>(self, writer: &mut W, args: Self::Args) -> StreamResult<()> {
        let start_pos = writer.stream_position()?;

        for (offset, style) in zip(args, self) {
            writer.seek(SeekFrom::Start(start_pos + offset as u64))?;
            style
                .write_no_opts(writer)
                .add_context(|| "write ResStringPoolSpan for Vec<ResStringPoolSpan>")?;
            ResStringPoolSpan::end_marker()
                .write_no_opts(writer)
                .add_context(
                    || "write terminating ResStringPoolSpan marker for Vec<ResStringPoolSpan>",
                )?;
        }

        Ok(())
    }
}

impl From<StringPool> for ResChunk {
    fn from(value: StringPool) -> Self {
        Self {
            data: crate::defs::ResTypeValue::StringPool(value),
        }
    }
}

impl HeaderSizeStatic for StringPool {
    fn header_size() -> usize {
        20
    }
}

fn calc_strings_start(header_pos: u64, current_pos: u64, total_str: u32, total_style: u32) -> u32 {
    let from_current = 4 + // stringsStart
    4 + // stylesStart
    (4 * total_str) + // string_indices
    (4 * total_style); // style_indices

    let abs_pos = current_pos + (from_current as u64);

    let aligned_pos = align(abs_pos, 4);

    (aligned_pos - header_pos) as u32
}

fn calc_string_indices(strings: &StringPoolStrings) -> Vec<u32> {
    let mut indices: Vec<u32> = Vec::new();

    let mut current: u32 = 0;

    match strings {
        StringPoolStrings::UTF8(s) => {
            for str in s {
                indices.push(current);
                current += str.total_bytes() as u32;
            }
        }
        StringPoolStrings::UTF16(s) => {
            for str in s {
                indices.push(current);
                current += str.total_bytes() as u32;
            }
        }
    };

    indices
}

fn calc_style_indices(total_style: u32) -> Vec<u32> {
    let mut indices: Vec<u32> = Vec::new();

    let mut current: u32 = 0;

    for _ in 0..total_style {
        indices.push(current);
        current += ResStringPoolSpan::total_bytes() as u32;
    }

    indices
}

fn calc_styles_start(
    header_pos: u64,
    strings_start: u32,
    strings: &StringPoolStrings,
    no_styles: bool,
) -> u32 {
    if no_styles {
        return 0;
    }
    let abs_pos = header_pos + (strings_start as u64) + (strings.total_bytes() as u64);

    let aligned_pos = align(abs_pos, 4);

    (aligned_pos - header_pos) as u32
}

#[derive(Debug)]
pub enum StringDecodeError {
    UTF8(FromUtf8Error),
    UTF16(FromUtf16Error),
}

impl From<FromUtf8Error> for StringDecodeError {
    fn from(value: FromUtf8Error) -> Self {
        Self::UTF8(value)
    }
}

impl From<FromUtf16Error> for StringDecodeError {
    fn from(value: FromUtf16Error) -> Self {
        Self::UTF16(value)
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct StringPoolHandler {
    pub string_pool: StringPool,
    string_map: HashMap<String, ResStringPoolRef>,
}

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

        *self = StringPoolHandler::new(self.string_pool.clone());
    }
}

impl StringPoolHandler {
    pub fn resolve(&self, reference: ResStringPoolRef) -> Option<&str> {
        self.string_pool.resolve(reference)
    }

    pub fn write(&mut self, string: String, id: ResStringPoolRef) {
        self.string_map.insert(string.clone(), id);

        self.string_pool.write_string(string, id);
    }

    pub fn allocate(&mut self, string: Cow<'_, str>) -> ResStringPoolRef {
        let exists = self.string_map.get(string.as_ref());
        match exists {
            Some(index) => *index,
            None => {
                let owned_string = string.into_owned();
                let index = self.string_pool.push_string(owned_string.clone());
                self.string_map.insert(owned_string, index);

                index
            }
        }
    }

    pub fn new_empty() -> Self {
        Self::default()
    }

    pub fn new(string_pool: StringPool) -> Self {
        let mut strings: HashMap<String, ResStringPoolRef> =
            HashMap::with_capacity(string_pool.strings.len());

        // these to_string calls are ok since this new should only be called once
        for (i, string) in string_pool.get_strings().enumerate() {
            strings.insert(string.to_string(), ResStringPoolRef { index: i as u32 });
        }

        Self {
            string_pool,
            string_map: strings,
        }
    }
}

impl From<StringPool> for StringPoolHandler {
    fn from(value: StringPool) -> Self {
        Self::new(value)
    }
}

impl From<StringPoolHandler> for StringPool {
    fn from(value: StringPoolHandler) -> Self {
        value.string_pool
    }
}

impl StringPool {
    pub fn resolve(&self, reference: ResStringPoolRef) -> Option<&str> {
        if reference.index == 0xffffffff {
            return None;
        }
        match &self.strings {
            StringPoolStrings::UTF8(utf8) => utf8
                .get(reference.index as usize)
                .map(|v| v.string.as_str()),
            StringPoolStrings::UTF16(utf16) => utf16
                .get(reference.index as usize)
                .map(|v| v.string.as_str()),
        }
    }
    pub fn get_strings(&self) -> Box<dyn Iterator<Item = &str> + '_> {
        match &self.strings {
            StringPoolStrings::UTF8(utf8) => Box::new(utf8.iter().map(|v| v.string.as_str())),
            StringPoolStrings::UTF16(utf16) => Box::new(utf16.iter().map(|v| v.string.as_str())),
        }
    }

    pub fn into_strings(self) -> Box<dyn Iterator<Item = String>> {
        match self.strings {
            StringPoolStrings::UTF8(utf8) => Box::new(utf8.into_iter().map(|v| v.string)),
            StringPoolStrings::UTF16(utf16) => Box::new(utf16.into_iter().map(|v| v.string)),
        }
    }

    pub fn write_string(&mut self, string: String, ind: ResStringPoolRef) {
        match self.strings {
            StringPoolStrings::UTF8(ref mut utf8) => {
                if ind.index as usize >= utf8.len() {
                    utf8.resize(
                        (ind.index + 1) as usize,
                        StringPoolString8 {
                            string: String::new(),
                        },
                    );
                }

                let Some(str) = utf8.get_mut(ind.index as usize) else {
                    return;
                };

                *str = StringPoolString8 { string: string };
            }
            StringPoolStrings::UTF16(ref mut utf16) => {
                if ind.index as usize >= utf16.len() {
                    utf16.resize(
                        (ind.index + 1) as usize,
                        StringPoolString16 {
                            string: String::new(),
                        },
                    );
                }

                let Some(str) = utf16.get_mut(ind.index as usize) else {
                    return;
                };

                *str = StringPoolString16 { string: string };
            }
        }
    }

    pub fn push_string(&mut self, string: String) -> ResStringPoolRef {
        match self.strings {
            StringPoolStrings::UTF16(ref mut utf16) => {
                utf16.push(StringPoolString16 { string });
                ResStringPoolRef {
                    index: (utf16.len() - 1) as u32,
                }
            }
            StringPoolStrings::UTF8(ref mut utf8) => {
                utf8.push(StringPoolString8 { string });
                ResStringPoolRef {
                    index: (utf8.len() - 1) as u32,
                }
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum StringPoolStrings {
    UTF8(Vec<StringPoolString8>),
    UTF16(Vec<StringPoolString16>),
}

impl Default for StringPoolStrings {
    fn default() -> Self {
        Self::UTF16(Vec::new())
    }
}

impl Readable for StringPoolStrings {
    type Args = (bool, Vec<u32>);
    fn read<R: Read + Seek>(reader: &mut R, args: Self::Args) -> StreamResult<Self> {
        match args.0 {
            true => {
                let start_pos = reader.stream_position()?;
                let mut strings = Vec::with_capacity(args.1.len());
                for index in args.1 {
                    reader.seek(SeekFrom::Start(start_pos + index as u64))?;
                    strings.push(
                        StringPoolString8::read_no_opts(reader)
                            .add_context(|| "read string for StringPoolStrings::UTF8")?,
                    );
                }
                Ok(StringPoolStrings::UTF8(strings))
            }
            false => {
                let start_pos = reader.stream_position()?;
                let mut strings = Vec::with_capacity(args.1.len());
                for index in args.1 {
                    reader.seek(SeekFrom::Start(start_pos + index as u64))?;
                    strings.push(
                        StringPoolString16::read_no_opts(reader)
                            .add_context(|| "read string for StringPoolStrings::UTF16")?,
                    );
                }
                Ok(StringPoolStrings::UTF16(strings))
            }
        }
    }
}

impl Writeable for StringPoolStrings {
    type Args = Vec<u32>;
    fn write<W: Write + Seek>(self, writer: &mut W, args: Self::Args) -> StreamResult<()> {
        let pos = writer.stream_position()?;
        match self {
            Self::UTF8(strings) => {
                for (offset, string) in zip(args, strings) {
                    writer.seek(SeekFrom::Start(pos + offset as u64))?;
                    string
                        .write_no_opts(writer)
                        .add_context(|| "write string for StringPoolStrings::UTF8")?;
                }
            }
            Self::UTF16(strings) => {
                for (offset, string) in zip(args, strings) {
                    writer.seek(SeekFrom::Start(pos + offset as u64))?;
                    string
                        .write_no_opts(writer)
                        .add_context(|| "write string for StringPoolStrings::UTF16")?;
                }
            }
        };
        Ok(())
    }
}

impl StringPoolStrings {
    pub fn len(&self) -> usize {
        match self {
            StringPoolStrings::UTF8(s) => s.len(),
            StringPoolStrings::UTF16(s) => s.len(),
        }
    }

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

    pub fn total_bytes(&self) -> usize {
        match self {
            StringPoolStrings::UTF8(s) => s.iter().map(StringPoolString8::total_bytes).sum(),
            StringPoolStrings::UTF16(s) => s.iter().map(StringPoolString16::total_bytes).sum(),
        }
    }
}
/// Strings in UTF-16 format have length indicated by a length encoded in the stored data. It is
/// either 1 or 2 characters of length data. This allows a maximum length of 0x7fffffff (2147483647
/// bytes).
///
/// If the high bit is set, then there are two characters or 4 bytes of length data encoded. In
/// that case, drop the high bit of the first character and add it together with the next
/// character.
#[derive(Debug, PartialEq, Clone)]
pub struct StringPoolString16 {
    pub string: String,
}

impl Writeable for StringPoolString16 {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let utf16_len = self.string.encode_utf16().count();
        let (length1, length2) = calc_length16(utf16_len);

        length1
            .write_no_opts(writer)
            .add_context(|| "write length1 for StringPoolString16")?;
        if let Some(length2) = length2 {
            length2.write_no_opts(writer)?;
        }

        write_utf16_str(writer, &self.string)
            .add_context(|| "write utf16 string for StringPoolString16")?;

        let null: u16 = 0;
        null.write_no_opts(writer)
            .add_context(|| "write null bytes for StringPoolString16")
    }
}

impl Readable for StringPoolString16 {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let length1 =
            u16::read_no_opts(reader).add_context(|| "read length1 for StringPoolString16")?;
        let length2 = if length1 & 0x8000 != 0 {
            Some(u16::read_no_opts(reader).add_context(|| "read length2 for StringPoolString16")?)
        } else {
            None
        };

        let string = read_utf16_str(reader, new_length16(length1, length2))
            .add_context(|| "read utf16 string for StringPoolString16")?;

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

        if null != 0 {
            return Err(StreamError::new_string_context(
                format!("invalid null value {null}, expected 0x0000"),
                reader.stream_position()?,
                "validate null bytes for StringPoolString16",
            ));
        }

        Ok(Self { string })
    }
}

impl StringPoolString16 {
    fn total_bytes(&self) -> usize {
        let utf16_len = self.string.encode_utf16().count();
        let large = utf16_len >= 0x8000;

        let size = 2 + utf16_len * 2 + 2;

        match large {
            true => size + 2,
            false => size,
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct StringTooLong {
    pub length: usize,
    pub max_length: usize,
}

fn get_string_length(str: &str) -> usize {
    str.encode_utf16().count()
}

/// Strings in UTF-8 format have their length indicated by a length encoded in the stored data. It
/// is either 1 or 2 characters of length data. This allows a maximum length of 0x7fff (32767 bytes).
///
/// If the high bit is set, then there are two characters or 2 bytes of length data encoded. In
/// that case, drop the high bit of the first character and add it together with the next
/// character.
#[derive(Debug, PartialEq, Clone)]
pub struct StringPoolString8 {
    pub string: String,
}

impl Writeable for StringPoolString8 {
    type Args = ();
    fn write<W: Write + Seek>(self, writer: &mut W, _args: Self::Args) -> StreamResult<()> {
        let str_len = get_string_length(&self.string);
        let (strlength_1, strlength_2) = calc_length8(str_len);

        strlength_1
            .write_no_opts(writer)
            .add_context(|| "write strlength_1 for StringPoolString8")?;
        if let Some(strlength_2) = strlength_2 {
            strlength_2
                .write_no_opts(writer)
                .add_context(|| "write strlength_2 for StringPoolString8")?;
        }

        let (bytelength_1, bytelength_2) = calc_length8(self.string.len());

        bytelength_1
            .write_no_opts(writer)
            .add_context(|| "write bytelength_1 for StringPoolString8")?;
        if let Some(bytelength_2) = bytelength_2 {
            bytelength_2
                .write_no_opts(writer)
                .add_context(|| "write bytelength_2 for StringPoolString8")?;
        }

        write_utf8_str(writer, self.string)
            .add_context(|| "write utf8 string for StringPoolString8")?;

        let null: u8 = 0;
        null.write_no_opts(writer)
            .add_context(|| "write null byte for StringPoolString8")
    }
}

impl Readable for StringPoolString8 {
    type Args = ();
    fn read<R: Read + Seek>(reader: &mut R, _args: Self::Args) -> StreamResult<Self> {
        let strlength_1 =
            u8::read_no_opts(reader).add_context(|| "read strlength_1 for StringPoolString8")?;
        let strlength_2 = if strlength_1 & 0x80 != 0 {
            Some(
                u8::read_no_opts(reader)
                    .add_context(|| "read strlength_2 for StringPoolString8")?,
            )
        } else {
            None
        };

        let bytelength_1 =
            u8::read_no_opts(reader).add_context(|| "read bytelength_1 for StringPoolString8")?;
        let bytelength_2 = if bytelength_1 & 0x80 != 0 {
            Some(
                u8::read_no_opts(reader)
                    .add_context(|| "read bytelength_2 for StringPoolString8")?,
            )
        } else {
            None
        };

        let string = read_utf8_str(reader, new_length8(bytelength_1, bytelength_2))
            .add_context(|| "read utf8 string for StringPoolString8")?;

        // Some apps ship malformed UTF-8 payloads in string pools.
        // Android can still consume these resources, so avoid failing hard here.
        let _ = new_length8(strlength_1, strlength_2);

        let null =
            u8::read_no_opts(reader).add_context(|| "read null byte for StringPoolString8")?;

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

        Ok(Self { string })
    }
}

impl StringPoolString8 {
    pub fn total_bytes(&self) -> usize {
        let strlen_big = get_string_length(&self.string) >= 0x80;
        let bytes = self.string.as_bytes();

        let bytelen_big = bytes.len() >= 0x80;

        let mut size = 1 + 1 + bytes.len() + 1;

        if strlen_big {
            size += 1;
        }
        if bytelen_big {
            size += 1;
        }
        size
    }
}

pub fn read_utf8_str<R: Read + Seek>(reader: &mut R, size: u32) -> StreamResult<String> {
    let data: Vec<u8> = <_>::read_vec(reader, size as usize)
        .add_context(|| "read encoded utf8 data for read_utf8_str")?;

    Ok(String::from_utf8_lossy(&data).into_owned())
}

pub fn write_utf8_str<W: Write + Seek>(writer: &mut W, string: String) -> StreamResult<()> {
    let data = string.into_bytes();
    data.write_vec(writer)
        .add_context(|| "write utf8 encoded bytes for write_utf8_str")
}

pub fn calc_length8(length: usize) -> (u8, Option<u8>) {
    match length >= 0x80 {
        true => (
            ((length >> 8) | (1 << 7)) as u8,
            Some((length & 0xff) as u8),
        ),
        false => (length as u8, None),
    }
}

pub fn new_length8(l1: u8, l2: Option<u8>) -> u32 {
    match l2 {
        None => l1 as u32,
        Some(le2) => (((l1 as u32) & 0x7f) << 8) | (le2 as u32),
    }
}

pub fn read_utf16_str<R: Read + Seek>(reader: &mut R, size: u32) -> StreamResult<String> {
    let data: Vec<u16> = <_>::read_vec(reader, size as usize)
        .add_context(|| "read raw encoded utf16 data for read_utf16_str")?;

    let mut out = String::new();
    for codepoint in char::decode_utf16(data.into_iter()) {
        match codepoint {
            Ok(ch) => out.push(ch),
            Err(_) => out.push(char::REPLACEMENT_CHARACTER),
        }
    }

    Ok(out)
}

pub fn write_utf16_str<W: Write + Seek>(writer: &mut W, string: &str) -> StreamResult<()> {
    let data: Vec<u16> = string.encode_utf16().collect();
    data.write_vec(writer)
        .add_context(|| "write utf16 encoded string")?;

    Ok(())
}

pub fn calc_length16(length: usize) -> (u16, Option<u16>) {
    match length >= 0x8000 {
        true => (
            ((length >> 16) | (1 << 15)) as u16,
            Some((length & 0xffff) as u16),
        ),
        false => (length as u16, None),
    }
}

pub fn new_length16(l1: u16, l2: Option<u16>) -> u32 {
    match l2 {
        None => l1 as u32,
        Some(le2) => (((l1 as u32) & 0x7fff) << 16) | (le2 as u32),
    }
}

/// This structure defines a span of style information associated with a string in the pool.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct ResStringPoolSpan {
    /// This is the name of the span -- that is, the name of the XML tag that defined it. The
    /// special value END (0xffffffff) indicates the end of an array of spans.
    pub name: ResStringPoolRef,
    /// The first character in the string that this span applies to.
    pub first_char: u32,
    /// The last character in the string that this span applies to.
    pub last_char: u32,
}

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

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

impl ResStringPoolSpan {
    pub fn total_bytes() -> usize {
        (4 + 4 + 4) * 2
    }

    fn end_marker() -> Self {
        Self {
            name: ResStringPoolRef::null(),
            first_char: 0xffffffff,
            last_char: 0xffffffff,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::{
        ResStringPoolRef, ResStringPoolSpan, StringPool, StringPoolFlags, StringPoolString8,
        StringPoolString16, StringPoolStrings,
    };
    use crate::{
        align,
        stream::{ReadableNoOptions, Writeable, WriteableNoOptions},
    };

    #[test]
    fn utf8_total_bytes_matches_written_bytes_for_multibyte_text() {
        let value = StringPoolString8 {
            string: "é".repeat(100),
        };

        let expected = value.total_bytes();
        let mut cursor = Cursor::new(Vec::<u8>::new());
        value
            .write_no_opts(&mut cursor)
            .expect("write utf8 string pool entry");

        assert_eq!(cursor.into_inner().len(), expected);
    }

    #[test]
    fn utf16_total_bytes_matches_written_bytes_for_multibyte_text() {
        let value = StringPoolString16 {
            string: "你好".repeat(100),
        };

        let expected = value.total_bytes();
        let mut cursor = Cursor::new(Vec::<u8>::new());
        value
            .write_no_opts(&mut cursor)
            .expect("write utf16 string pool entry");

        assert_eq!(cursor.into_inner().len(), expected);
    }

    #[test]
    fn string_pool_strings_total_bytes_is_sum_of_all_entries() {
        let strings = StringPoolStrings::UTF8(vec![
            StringPoolString8 {
                string: "hello".to_string(),
            },
            StringPoolString8 {
                string: "世界".to_string(),
            },
        ]);

        let entries_total: usize = match &strings {
            StringPoolStrings::UTF8(v) => v.iter().map(StringPoolString8::total_bytes).sum(),
            StringPoolStrings::UTF16(v) => v.iter().map(StringPoolString16::total_bytes).sum(),
        };

        assert_eq!(strings.total_bytes(), entries_total);
    }

    #[test]
    fn styles_are_terminated_with_end_marker_when_written() {
        let styles = vec![ResStringPoolSpan {
            name: ResStringPoolRef { index: 7 },
            first_char: 1,
            last_char: 3,
        }];

        let mut cursor = Cursor::new(Vec::<u8>::new());
        styles
            .write(&mut cursor, vec![0])
            .expect("write style with end marker");

        let bytes = cursor.into_inner();
        assert_eq!(bytes.len(), ResStringPoolSpan::total_bytes());

        let end = &bytes[12..24];
        assert_eq!(end, &[0xff; 12]);
    }

    #[test]
    fn styles_start_points_to_aligned_style_data() {
        let pool = StringPool {
            flags: StringPoolFlags::new(false, true),
            strings: StringPoolStrings::UTF8(vec![StringPoolString8 {
                string: "alpha".to_string(),
            }]),
            styles: vec![ResStringPoolSpan {
                name: ResStringPoolRef { index: 0 },
                first_char: 0,
                last_char: 4,
            }],
        };

        let strings_total = pool.strings.total_bytes() as u32;

        let mut cursor = Cursor::new(Vec::<u8>::new());
        pool.clone()
            .write_no_opts(&mut cursor)
            .expect("write string pool");
        let bytes = cursor.into_inner();

        let mut header_cursor = Cursor::new(bytes.as_slice());
        let string_count = u32::read_no_opts(&mut header_cursor).expect("read string_count");
        let style_count = u32::read_no_opts(&mut header_cursor).expect("read style_count");
        assert_eq!(string_count, 1);
        assert_eq!(style_count, 1);

        let _flags = u32::read_no_opts(&mut header_cursor).expect("read flags");
        let strings_start = u32::read_no_opts(&mut header_cursor).expect("read strings_start");
        let styles_start = u32::read_no_opts(&mut header_cursor).expect("read styles_start");

        let expected_styles_start = align((strings_start + strings_total) as u64, 4) as u32;
        assert_eq!(styles_start, expected_styles_start);

        let style_offsets_base = 20 + 4 * string_count as usize;
        let first_style_offset = u32::from_le_bytes(
            bytes[style_offsets_base..style_offsets_base + 4]
                .try_into()
                .expect("style index slice"),
        ) as usize;

        let end_marker_start = styles_start as usize + first_style_offset + 12;
        let end_marker = &bytes[end_marker_start..end_marker_start + 12];
        assert_eq!(end_marker, &[0xff; 12]);
    }
}