shared_io_utils 0.0.5

A utility to provide more convenient `Read` `Write` `Seek` `Debug` `Cursor` that could be shared, e.g. `SharedReader`, `SharedWriter`, `SharedReadWrite`, `DishonestReader` for modifying data using closures when being called `read()`, `CombinedReader` combines two readers but you can 'slice' the readers to make it only able to read parts of them, `CursorVecU8` have a better formatting behavior, `SharedCursor` shares a `CursorVecU8`, `MultistreamIO` allows you to switch its streams to read or write, `SharedMultistreamIO` shares the `MultistreamIO`. All of these 'shared' version are used for the 3rd party library to read/write and you can capture the data or modify the data.
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
#![allow(dead_code)]
#![allow(clippy::type_complexity)]

use std::{
    any::type_name,
    cmp::min,
    mem,
    fmt::{self, Debug, Display, Formatter},
    io::{self, Read, Seek, Write, Cursor, SeekFrom},
    rc::Rc,
    cell::RefCell,
    ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeTo, RangeFull}
};

/// * The `Reader` trait, `Read + Seek + Debug`
pub trait Reader: Read + Seek + Debug {}
impl<T> Reader for T where T: Read + Seek + Debug {}

/// * The `Writer` trait, `Write + Seek + Debug`
pub trait Writer: Write + Seek + Debug {}
impl<T> Writer for T where T: Write + Seek + Debug {}

/// * The `ReadWrite` trait, `Read + Write + Seek + Debug`
pub trait ReadWrite: Read + Write + Seek + Debug {}
impl<T> ReadWrite for T where T: Read + Write + Seek + Debug {}

/// * Encapsulated shared `Read + Seek + Debug`
#[derive(Debug)]
pub struct SharedReader<T> (Rc<RefCell<T>>) where T: Read + Seek + Debug;

impl<T> SharedReader<T>
where
    T: Read + Seek + Debug {
    pub fn new(reader: T) -> Self {
        Self(Rc::new(RefCell::new(reader)))
    }
}

impl<T> Read for SharedReader<T>
where
    T: Read + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.borrow_mut().read(buf)
    }
}

impl<T> Seek for SharedReader<T>
where
    T: Read + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.borrow_mut().seek(pos)
    }
}

impl<T> Clone for SharedReader<T>
where
    T: Read + Seek + Debug {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// * Encapsulated shared `Write + Seek + Debug`
#[derive(Debug)]
pub struct SharedWriter<T> (Rc<RefCell<T>>) where T: Write + Seek + Debug;

impl<T> SharedWriter<T>
where
    T: Write + Seek + Debug {
    pub fn new(reader: T) -> Self {
        Self(Rc::new(RefCell::new(reader)))
    }
}

impl<T> Write for SharedWriter<T>
where
    T: Write + Seek + Debug {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.borrow_mut().write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.borrow_mut().flush()
    }
}

impl<T> Seek for SharedWriter<T>
where
    T: Write + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.borrow_mut().seek(pos)
    }
}

impl<T> Clone for SharedWriter<T>
where
    T: Write + Seek + Debug {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// * Encapsulated shared `Read + Write + Seek + Debug`
#[derive(Debug)]
pub struct SharedReadWrite<T> (Rc<RefCell<T>>) where T: Read + Write + Seek + Debug;

impl<T> SharedReadWrite<T>
where
    T: Read + Write + Seek + Debug {
    pub fn new(readwrite: T) -> Self {
        Self(Rc::new(RefCell::new(readwrite)))
    }
}

impl<T> Read for SharedReadWrite<T>
where
    T: Read + Write + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.borrow_mut().read(buf)
    }
}

impl<T> Write for SharedReadWrite<T>
where
    T: Read + Write + Seek + Debug {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.borrow_mut().write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.borrow_mut().flush()
    }
}

impl<T> Seek for SharedReadWrite<T>
where
    T: Read + Write + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.borrow_mut().seek(pos)
    }
}

impl<T> Clone for SharedReadWrite<T>
where
    T: Read + Write + Seek + Debug {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// * Dishonest reader, a reader that reads data but modifies it.
pub struct DishonestReader<T>
where
    T: Read + Seek + Debug {
    reader: T,
    on_read: Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>,
    on_seek: Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>,
    cache: Vec<u8>,
}

impl<T> DishonestReader<T>
where
    T: Read + Seek + Debug {
    pub fn new(
        reader: T,
        on_read: Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>,
        on_seek: Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>,
    ) -> Self {
        Self {
            reader,
            on_read,
            on_seek,
            cache: Vec::new(),
        }
    }
}

impl<T> Read for DishonestReader<T>
where
    T: Read + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let write_buf_and_cache = |data: &[u8], buf: &mut [u8], cache: &mut Vec<u8>| -> usize {
            let len = min(data.len(), buf.len());
            buf[..len].copy_from_slice(&data[..len]);
            if len < data.len() {
                *cache = data[len..].to_vec();
            } else {
                *cache = Vec::new();
            }
            len
        };
        if self.cache.is_empty() {
            match (self.on_read)(&mut self.reader, buf.len()) {
                Ok(data) => Ok(write_buf_and_cache(&data, buf, &mut self.cache)),
                Err(e) => Err(e),
            }
        } else {
            let to_write = self.cache.clone();
            Ok(write_buf_and_cache(&to_write, buf, &mut self.cache))
        }
    }
}

impl<T> Seek for DishonestReader<T>
where
    T: Read + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        (self.on_seek)(&mut self.reader, pos)
    }
}

impl<T> Debug for DishonestReader<T>
where
    T: Read + Seek + Debug {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let typename = type_name::<T>();
        f.debug_struct(&format!("DishonestReader<{typename}>"))
        .field("reader", &self.reader)
        .field("on_read", &format_args!("Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>"))
        .field("on_seek", &format_args!("Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>"))
        .field("cache", &format_args!("[u8; {}]", self.cache.len()))
        .finish()
    }
}

/// * A Reader that combines two readers into one with the ability to `Read` and `Seek` and `Debug`
#[derive(Debug)]
pub struct CombinedReader<R1, R2>
where
    R1: Reader,
    R2: Reader {
    first: R1,
    first_data_offset: u64,
    first_data_length: u64,
    second: R2,
    second_data_offset: u64,
    second_data_length: u64,
    stream_pos: u64,
    total_length: u64,
}

impl<R1, R2> CombinedReader<R1, R2>
where
    R1: Reader,
    R2: Reader {
    pub fn new(
        first: R1,
        first_data_offset: u64,
        first_data_length: u64,
        second: R2,
        second_data_offset: u64,
        second_data_length: u64,
    ) -> Self {
        Self {
            first,
            first_data_offset,
            first_data_length,
            second,
            second_data_offset,
            second_data_length,
            stream_pos: 0,
            total_length: first_data_length + second_data_length,
        }
    }

    fn default_read<R>(reader: &mut R, buf: &mut [u8], reader_position: u64, reader_offset: u64, reader_length: u64) -> io::Result<usize>
    where
        R: Reader {
        let bytes_to_read = min((reader_length - reader_position) as usize, buf.len());
        reader.seek(SeekFrom::Start(reader_offset + reader_position))?;
        reader.read(&mut buf[..bytes_to_read])
    }
}

impl<R1, R2> Read for CombinedReader<R1, R2>
where
    R1: Reader,
    R2: Reader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.stream_pos < self.first_data_length {
            let reader = &mut self.first;
            let reader_position = self.stream_pos;
            let reader_offset = self.first_data_offset;
            let reader_length = self.first_data_length;
            let n = Self::default_read(reader, buf, reader_position, reader_offset, reader_length)?;
            self.stream_pos += n as u64;
            Ok(n)
        } else if self.stream_pos < self.total_length {
            let reader = &mut self.second;
            let reader_position = self.stream_pos - self.first_data_length;
            let reader_offset = self.second_data_offset;
            let reader_length = self.second_data_length;
            let n = Self::default_read(reader, buf, reader_position, reader_offset, reader_length)?;
            self.stream_pos += n as u64;
            Ok(n)
        } else {
            return Ok(0)
        }
    }
}

impl<R1, R2> Seek for CombinedReader<R1, R2>
where
    R1: Reader,
    R2: Reader {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.stream_pos = min(match pos {
            SeekFrom::Start(position) => position,
            relative => {
                let ipos = match relative {
                    SeekFrom::End(offset) => self.total_length as i64 + offset,
                    SeekFrom::Current(offset) => self.stream_pos as i64 + offset,
                    _absolute => unreachable!(),
                };
                if ipos < 0 {
                    return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Seek position out of bounds: {ipos}")))
                }
                ipos as u64
            }
        }, self.total_length);
        Ok(self.stream_pos)
    }
}

/// * A better `Cursor<Vec<u8>>` which has a friendlier `Debug` trait implementation
#[derive(Clone)]
pub struct CursorVecU8(Cursor<Vec<u8>>);

impl CursorVecU8 {
    pub fn new(data: Vec<u8>) -> Self {
        Self(Cursor::new(data))
    }

    pub fn into_inner(self) -> Vec<u8> {
        self.0.into_inner()
    }

    pub fn len(&self) -> usize {
        self.0.get_ref().len()
    }

    pub fn set_len(&mut self, len: usize) {
        self.0.get_mut().resize(len, 0);
        if self.0.position() > len as u64 {
            self.0.set_position(len as u64);
        }
    }

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

    pub fn clear(&mut self) {
        self.0.get_mut().clear();
        self.0.set_position(0);
    }
}

impl Default for CursorVecU8 {
    fn default() -> Self {
        Self(Cursor::new(Vec::new()))
    }
}

impl From<Cursor<Vec<u8>>> for CursorVecU8 {
    fn from(cursor: Cursor<Vec<u8>>) -> Self {
        Self(cursor)
    }
}

impl From<CursorVecU8> for Cursor<Vec<u8>> {
    fn from(val: CursorVecU8) -> Self {
        val.0
    }
}

impl Deref for CursorVecU8 {
    type Target = Cursor<Vec<u8>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for CursorVecU8 {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Read for CursorVecU8 {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl Write for CursorVecU8 {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl Seek for CursorVecU8 {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.seek(pos)
    }
}

impl Debug for CursorVecU8 {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("Cursor")
        .field("inner", &format_args!("[u8; {}]", self.0.get_ref().len()))
        .field("pos", &self.0.position())
        .finish()
    }
}

impl Display for CursorVecU8 {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        <Self as Debug>::fmt(self, f)
    }
}

impl Index<usize> for CursorVecU8 {
    type Output = u8;
    fn index(&self, index: usize) -> &u8 {
        &self.0.get_ref()[index]
    }
}

impl IndexMut<usize> for CursorVecU8 {
    fn index_mut(&mut self, index: usize) -> &mut u8 {
        &mut self.0.get_mut()[index]
    }
}

impl Index<Range<usize>> for CursorVecU8 {
    type Output = [u8];
    fn index(&self, range: Range<usize>) -> &[u8] {
        &self.0.get_ref()[range]
    }
}

impl IndexMut<Range<usize>> for CursorVecU8 {
    fn index_mut(&mut self, range: Range<usize>) -> &mut [u8] {
        &mut self.0.get_mut()[range]
    }
}

impl Index<RangeFrom<usize>> for CursorVecU8 {
    type Output = [u8];
    fn index(&self, range: RangeFrom<usize>) -> &[u8] {
        &self.0.get_ref()[range]
    }
}

impl IndexMut<RangeFrom<usize>> for CursorVecU8 {
    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut [u8] {
        &mut self.0.get_mut()[range]
    }
}

impl Index<RangeTo<usize>> for CursorVecU8 {
    type Output = [u8];
    fn index(&self, range: RangeTo<usize>) -> &[u8] {
        &self.0.get_ref()[range]
    }
}

impl IndexMut<RangeTo<usize>> for CursorVecU8 {
    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut [u8] {
        &mut self.0.get_mut()[range]
    }
}

impl Index<RangeFull> for CursorVecU8 {
    type Output = [u8];
    fn index(&self, _range: RangeFull) -> &[u8] {
        &self.0.get_ref()[..]
    }
}

impl IndexMut<RangeFull> for CursorVecU8 {
    fn index_mut(&mut self, _range: RangeFull) -> &mut [u8] {
        &mut self.0.get_mut()[..]
    }
}

/// * The shared `Cursor`.
/// * Because it's shared, when the 3rd library owned it, we still can access to it..
#[derive(Debug)]
pub struct SharedCursor (Rc<RefCell<CursorVecU8>>);

impl SharedCursor {
    pub fn new() -> Self {
        Self::default()
    }

    /// * Get the inner data size
    pub fn len(&self) -> usize {
        self.0.borrow().get_ref().len()
    }

    /// * Check if the inner data is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// * Get the inner data as `Vec<u8>`
    pub fn get_vec(&self) -> Vec<u8> {
        self.0.borrow().get_ref().to_vec()
    }

    /// * Discard current inner data, replace it with new data, and set the read/write position to the end of the data
    pub fn set_vec(&mut self, data: &[u8], rw_pos: u64) {
        let mut new_cursor = CursorVecU8::new(data.to_vec());
        new_cursor.set_position(rw_pos);
        *self.0.borrow_mut() = new_cursor;
    }

    /// * Discard the inner data, set the read/write position to 0
    pub fn clear(&mut self) {
        *self.0.borrow_mut() = CursorVecU8::default();
    }
}

impl Default for SharedCursor {
    fn default() -> Self {
        Self(Rc::new(RefCell::new(CursorVecU8::default())))
    }
}

impl Read for SharedCursor {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.borrow_mut().read(buf)
    }
}

impl Write for SharedCursor {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.borrow_mut().write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.borrow_mut().flush()
    }
}

impl Seek for SharedCursor {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.borrow_mut().seek(pos)
    }
}

impl Clone for SharedCursor {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// * The `StreamType<R, W, RW>` is for the `MultistreamIO<R, W, RW>` to manage multiple IO objects.
/// * A stream can be a reader, writer, reader + writer, or cursor.
/// * By using the `MultistreamIO<R, W, RW>` you can control the 3rd party library to write data into different streams and manipulate them.
#[derive(Debug)]
pub enum StreamType<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    /// * The `Read + Seek + Debug`
    Reader(R),

    /// * The `Write + Seek + Debug`
    Writer(W),

    /// * The `Read + Write + Seek + Debug`, better use it with the `tempfile()`
    ReadWrite(RW),

    /// * The `Read + Write + Seek + Debug` cursor.
    CursorU8(CursorVecU8)
}

impl<R, W, RW> StreamType<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {

    pub fn as_reader(&mut self) -> &mut R {
        let name_r = type_name::<R>();
        let name_w = type_name::<W>();
        let name_rw = type_name::<RW>();
        match self {
            Self::Reader(reader) => reader,
            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
        }
    }

    pub fn as_writer(&mut self) -> &mut W {
        let name_r = type_name::<R>();
        let name_w = type_name::<W>();
        let name_rw = type_name::<RW>();
        match self {
            Self::Writer(writer) => writer,
            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
        }
    }

    pub fn as_readwrite(&mut self) -> &mut RW {
        let name_r = type_name::<R>();
        let name_w = type_name::<W>();
        let name_rw = type_name::<RW>();
        match self {
            Self::ReadWrite(readwrite) => readwrite,
            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
        }
    }

    pub fn as_cursor(&mut self) -> &mut CursorVecU8 {
        let name_r = type_name::<R>();
        let name_w = type_name::<W>();
        let name_rw = type_name::<RW>();
        match self {
            Self::CursorU8(cursor) => cursor,
            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
        }
    }

    /// * Take the cursor data, leaving an empty cursor here.
    pub fn take_cursor_data(&mut self) -> Vec<u8> {
        let name_r = type_name::<R>();
        let name_w = type_name::<W>();
        let name_rw = type_name::<RW>();
        match self {
            Self::CursorU8(cursor) => {
                mem::take(cursor).into_inner()
            }
            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
        }
    }
}

impl<R, W, RW> Read for StreamType<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Reader(reader) => {
                reader.read(buf)
            }
            Self::ReadWrite(readwrite) => {
                readwrite.read(buf)
            }
            Self::CursorU8(cursor) => {
                cursor.read(buf)
            }
            Self::Writer(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Writer()` can't read.")),
        }
    }
}

impl<R, W, RW> Write for StreamType<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Self::Writer(writer) => {
                writer.write(buf)
            }
            Self::ReadWrite(readwrite) => {
                readwrite.write(buf)
            }
            Self::CursorU8(cursor) => {
                cursor.write(buf)
            }
            Self::Reader(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Reader()` can't write.")),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Writer(writer) => {
                writer.flush()
            }
            Self::ReadWrite(readwrite) => {
                readwrite.flush()
            }
            Self::CursorU8(cursor) => {
                cursor.flush()
            }
            Self::Reader(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Reader()` can't flush.")),
        }
    }
}

impl<R, W, RW> Seek for StreamType<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        match self {
            Self::Reader(reader) => {
                reader.seek(pos)
            }
            Self::Writer(writer) => {
                writer.seek(pos)
            }
            Self::ReadWrite(readwrite) => {
                readwrite.seek(pos)
            }
            Self::CursorU8(cursor) => {
                cursor.seek(pos)
            }
        }
    }
}

/// * The `MultistreamIO<R, W, RW>` is for managing multiple IO objects.
/// * This thing itself implements `Read + Write + Seek + Debug`, when these traits methods are called, the selected stream is manipulated.
/// * by using this, you can control the 3rd party library to read or write data from/into different stream objects, and you can manipulate these data or streams.
#[derive(Debug)]
pub struct MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    pub streams: Vec<StreamType<R, W, RW>>,
    pub cur_stream: usize,
}

impl<R, W, RW> Default for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn default() -> Self {
        Self {
            streams: Vec::new(),
            cur_stream: 0,
        }
    }
}

impl<R, W, RW> MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {

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

    /// * Get the current selected stream object
    pub fn get_cur_stream(&self) -> &StreamType<R, W, RW> {
        &self.streams[self.cur_stream]
    }

    /// * Get the current selected stream object as mutable
    pub fn get_cur_stream_mut(&mut self) -> &mut StreamType<R, W, RW> {
        &mut self.streams[self.cur_stream]
    }

    /// * Get a stream object using an index
    pub fn get_stream(&self, index: usize) -> &StreamType<R, W, RW> {
        &self.streams[index]
    }

    /// * Get a mutable stream object using an index
    pub fn get_stream_mut(&mut self, index: usize) -> &mut StreamType<R, W, RW> {
        &mut self.streams[index]
    }

    /// * Add a new stream
    pub fn push_stream(&mut self, stream: StreamType<R, W, RW>) {
        self.streams.push(stream);
    }

    /// * Pop out the last stream
    pub fn pop_stream(&mut self) -> Option<StreamType<R, W, RW>> {
        self.streams.pop()
    }

    /// * Set the current stream index
    pub fn set_stream(&mut self, index: usize) {
        self.cur_stream = index;
    }

    /// * The number of streams in total
    pub fn len(&self) -> usize {
        self.streams.len()
    }

    /// * Is there no stream objects?
    pub fn is_empty(&self) -> bool {
        self.streams.is_empty()
    }
}

impl<R, W, RW> Read for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.get_cur_stream_mut().read(buf)
    }
}

impl<R, W, RW> Write for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.get_cur_stream_mut().write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.get_cur_stream_mut().flush()
    }
}

impl<R, W, RW> Seek for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.get_cur_stream_mut().seek(pos)
    }
}

impl<R, W, RW> Index<usize> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Output = StreamType<R, W, RW>;

    fn index(&self, index: usize) -> &Self::Output {
        &self.streams[index]
    }
}

impl<R, W, RW> IndexMut<usize> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.streams[index]
    }
}

impl<R, W, RW> Index<Range<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Output = [StreamType<R, W, RW>];

    fn index(&self, range: Range<usize>) -> &Self::Output {
        &self.streams[range]
    }
}

impl<R, W, RW> IndexMut<Range<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
        &mut self.streams[range]
    }
}

impl<R, W, RW> Index<RangeFrom<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Output = [StreamType<R, W, RW>];

    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        &self.streams[range]
    }
}

impl<R, W, RW> IndexMut<RangeFrom<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
        &mut self.streams[range]
    }
}

impl<R, W, RW> Index<RangeTo<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Output = [StreamType<R, W, RW>];

    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
        &self.streams[range]
    }
}

impl<R, W, RW> IndexMut<RangeTo<usize>> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
        &mut self.streams[range]
    }
}

impl<R, W, RW> Index<RangeFull> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Output = [StreamType<R, W, RW>];

    fn index(&self, _range: RangeFull) -> &Self::Output {
        &self.streams[..]
    }
}

impl<R, W, RW> IndexMut<RangeFull> for MultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn index_mut(&mut self, _range: RangeFull) -> &mut Self::Output {
        &mut self.streams[..]
    }
}

/// * The shared version of the `MultistreamIO`.
/// * Because it's shared, when the 3rd library owned it, we still can access to it, e.g. switch it to a cursor stream to capture some data.
#[derive(Debug)]
pub struct SharedMultistreamIO<R, W, RW> (Rc<RefCell<MultistreamIO<R, W, RW>>>)
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug;

impl<R, W, RW> SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    pub fn new(writer_with_cursor: MultistreamIO<R, W, RW>) -> Self {
        Self(Rc::new(RefCell::new(writer_with_cursor)))
    }
}

impl<R, W, RW> Deref for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    type Target = MultistreamIO<R, W, RW>;

    fn deref(&self) -> &Self::Target {
        unsafe { &*(self.0.as_ptr() as *const MultistreamIO<R, W, RW>) }
    }
}

impl<R, W, RW> DerefMut for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.0.as_ptr() }
    }
}

impl<R, W, RW> Read for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.borrow_mut().read(buf)
    }
}

impl<R, W, RW> Write for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.borrow_mut().write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.borrow_mut().flush()
    }
}

impl<R, W, RW> Seek for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.0.borrow_mut().seek(pos)
    }
}

impl<R, W, RW> Clone for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<R, W, RW> Default for SharedMultistreamIO<R, W, RW>
where
    R: Read + Seek + Debug,
    W: Write + Seek + Debug,
    RW: Read + Write + Seek + Debug {
    fn default() -> Self {
        Self(Rc::new(RefCell::new(MultistreamIO::new())))
    }
}

/// * Go to an offset without using seek. It's achieved by using dummy reads.
pub fn goto_offset_without_seek<T>(
    mut reader: T,
    cur_pos: &mut u64,
    position: u64,
) -> io::Result<u64>
where
    T: Read,
{
    const SKIP_SIZE: u64 = 1024;
    let mut skip_buf = [0u8; SKIP_SIZE as usize];
    while *cur_pos + SKIP_SIZE <= position {
        reader.read_exact(&mut skip_buf)?;
        *cur_pos += SKIP_SIZE;
    }
    if *cur_pos < position {
        let mut skip_buf = vec![0u8; (position - *cur_pos) as usize];
        reader.read_exact(&mut skip_buf)?;
        *cur_pos = position;
    }
    if *cur_pos > position {
        Err(io::Error::new(
            io::ErrorKind::NotSeekable,
            format!(
                "The current position {cur_pos} has already exceeded the target position {position}"
            ),
        ))
    } else {
        Ok(*cur_pos)
    }
}

/// * Copy data from a reader to a writer from the current position.
pub fn copy<R, W>(reader: &mut R, writer: &mut W, bytes_to_copy: u64) -> io::Result<()>
where
    R: Read,
    W: Write,
{
    const BUFFER_SIZE: u64 = 1024;
    let mut buf = vec![0u8; BUFFER_SIZE as usize];
    let mut to_copy = bytes_to_copy;
    while to_copy >= BUFFER_SIZE {
        reader.read_exact(&mut buf)?;
        writer.write_all(&buf)?;
        to_copy -= BUFFER_SIZE;
    }
    if to_copy > 0 {
        buf.resize(to_copy as usize, 0);
        reader.read_exact(&mut buf)?;
        writer.write_all(&buf)?;
    }
    Ok(())
}

/// * This is for read/write strings from/to file with specific encoding and size, or read/write as NUL-terminated strings.
pub mod string_io {
    use savagestr::{SavageStringCodecs, StringCodecMaps};
    use std::io::{self, Read, Write};

    /// * Read some bytes, and return the bytes, without you to create a local `vec![0u8; size]` and scratch your head with the messy codes
    pub fn read_bytes<T: Read>(r: &mut T, size: usize) -> io::Result<Vec<u8>> {
        let mut buf = vec![0u8; size];
        r.read_exact(&mut buf)?;
        Ok(buf)
    }

    /// * Read a fixed-size string and decode it using the `StringCodecMaps`
    pub fn read_str<T: Read>(
        r: &mut T,
        size: usize,
        text_encoding: &StringCodecMaps,
    ) -> io::Result<String> {
        let mut buf = vec![0u8; size];
        r.read_exact(&mut buf)?;
        Ok(text_encoding
            .decode(&buf)
            .trim_matches(char::from(0))
            .to_string())
    }

    /// * Read a fixed-size string and decode it using the `StringCodecMaps` while you can specify the code page.
    pub fn read_str_by_code_page<T: Read>(
        r: &mut T,
        size: usize,
        text_encoding: &StringCodecMaps,
        code_page: u32,
    ) -> io::Result<String> {
        let mut buf = vec![0u8; size];
        r.read_exact(&mut buf)?;
        Ok(text_encoding
            .decode_bytes_by_code_page(&buf, code_page)
            .trim_matches(char::from(0))
            .to_string())
    }

    /// * Read a NUL terminated string by raw, not decode it.
    pub fn read_sz_raw<T: Read>(r: &mut T) -> io::Result<Vec<u8>> {
        let mut buf = Vec::<u8>::new();
        loop {
            let b = [0u8; 1];
            r.read_exact(&mut buf)?;
            let b = b[0];
            if b != 0 {
                buf.push(b);
            } else {
                break;
            }
        }
        Ok(buf)
    }

    /// * Read a NUL terminated string and decode it.
    pub fn read_sz<T: Read>(
        r: &mut T,
        text_encoding: &StringCodecMaps,
    ) -> io::Result<String> {
        Ok(text_encoding
            .decode(&read_sz_raw(r)?)
            .trim_matches(char::from(0))
            .to_string())
    }

    /// * Read a NUL terminated string and decode it with the specified code page.
    pub fn read_sz_by_code_page<T: Read>(
        r: &mut T,
        text_encoding: &StringCodecMaps,
        code_page: u32,
    ) -> io::Result<String> {
        Ok(text_encoding
            .decode_bytes_by_code_page(&read_sz_raw(r)?, code_page)
            .trim_matches(char::from(0))
            .to_string())
    }

    /// * Write a fixed-size encoded string.
    pub fn write_str_sized<T: Write + ?Sized>(
        w: &mut T,
        data: &str,
        size: usize,
        text_encoding: &StringCodecMaps,
    ) -> io::Result<()> {
        let mut data = text_encoding.encode(data);
        data.resize(size, 0);
        w.write_all(&data)?;
        Ok(())
    }

    /// * Write an encoded string.
    pub fn write_str<T: Write + ?Sized>(
        w: &mut T,
        data: &str,
        text_encoding: &StringCodecMaps,
    ) -> io::Result<()> {
        let data = text_encoding.encode(data);
        w.write_all(&data)?;
        Ok(())
    }

    /// * Write an encoded string encoded with the specified code page.
    pub fn write_str_by_code_page<T: Write + ?Sized>(
        w: &mut T,
        data: &str,
        text_encoding: &StringCodecMaps,
        code_page: u32,
    ) -> io::Result<()> {
        let data = text_encoding.encode_strings_by_code_page(data, code_page);
        w.write_all(&data)?;
        Ok(())
    }
}