io_utils/
io_utils.rs

1#![allow(dead_code)]
2#![allow(clippy::type_complexity)]
3
4use std::{
5    any::type_name,
6    cmp::min,
7    mem,
8    fmt::{self, Debug, Display, Formatter},
9    io::{self, Read, Seek, Write, Cursor, SeekFrom},
10    rc::Rc,
11    cell::RefCell,
12    ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeTo, RangeFull}
13};
14
15/// * The `Reader` trait, `Read + Seek + Debug`
16pub trait Reader: Read + Seek + Debug {}
17impl<T> Reader for T where T: Read + Seek + Debug {}
18
19/// * The `Writer` trait, `Write + Seek + Debug`
20pub trait Writer: Write + Seek + Debug {}
21impl<T> Writer for T where T: Write + Seek + Debug {}
22
23/// * The `ReadWrite` trait, `Read + Write + Seek + Debug`
24pub trait ReadWrite: Read + Write + Seek + Debug {}
25impl<T> ReadWrite for T where T: Read + Write + Seek + Debug {}
26
27/// * Encapsulated shared `Read + Seek + Debug`
28#[derive(Debug)]
29pub struct SharedReader<T> (Rc<RefCell<T>>) where T: Read + Seek + Debug;
30
31impl<T> SharedReader<T>
32where
33    T: Read + Seek + Debug {
34    pub fn new(reader: T) -> Self {
35        Self(Rc::new(RefCell::new(reader)))
36    }
37}
38
39impl<T> Read for SharedReader<T>
40where
41    T: Read + Seek + Debug {
42    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
43        self.0.borrow_mut().read(buf)
44    }
45}
46
47impl<T> Seek for SharedReader<T>
48where
49    T: Read + Seek + Debug {
50    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
51        self.0.borrow_mut().seek(pos)
52    }
53}
54
55impl<T> Clone for SharedReader<T>
56where
57    T: Read + Seek + Debug {
58    fn clone(&self) -> Self {
59        Self(self.0.clone())
60    }
61}
62
63/// * Encapsulated shared `Write + Seek + Debug`
64#[derive(Debug)]
65pub struct SharedWriter<T> (Rc<RefCell<T>>) where T: Write + Seek + Debug;
66
67impl<T> SharedWriter<T>
68where
69    T: Write + Seek + Debug {
70    pub fn new(reader: T) -> Self {
71        Self(Rc::new(RefCell::new(reader)))
72    }
73}
74
75impl<T> Write for SharedWriter<T>
76where
77    T: Write + Seek + Debug {
78    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
79        self.0.borrow_mut().write(buf)
80    }
81    fn flush(&mut self) -> io::Result<()> {
82        self.0.borrow_mut().flush()
83    }
84}
85
86impl<T> Seek for SharedWriter<T>
87where
88    T: Write + Seek + Debug {
89    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
90        self.0.borrow_mut().seek(pos)
91    }
92}
93
94impl<T> Clone for SharedWriter<T>
95where
96    T: Write + Seek + Debug {
97    fn clone(&self) -> Self {
98        Self(self.0.clone())
99    }
100}
101
102/// * Encapsulated shared `Read + Write + Seek + Debug`
103#[derive(Debug)]
104pub struct SharedReadWrite<T> (Rc<RefCell<T>>) where T: Read + Write + Seek + Debug;
105
106impl<T> SharedReadWrite<T>
107where
108    T: Read + Write + Seek + Debug {
109    pub fn new(readwrite: T) -> Self {
110        Self(Rc::new(RefCell::new(readwrite)))
111    }
112}
113
114impl<T> Read for SharedReadWrite<T>
115where
116    T: Read + Write + Seek + Debug {
117    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
118        self.0.borrow_mut().read(buf)
119    }
120}
121
122impl<T> Write for SharedReadWrite<T>
123where
124    T: Read + Write + Seek + Debug {
125    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
126        self.0.borrow_mut().write(buf)
127    }
128    fn flush(&mut self) -> io::Result<()> {
129        self.0.borrow_mut().flush()
130    }
131}
132
133impl<T> Seek for SharedReadWrite<T>
134where
135    T: Read + Write + Seek + Debug {
136    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
137        self.0.borrow_mut().seek(pos)
138    }
139}
140
141impl<T> Clone for SharedReadWrite<T>
142where
143    T: Read + Write + Seek + Debug {
144    fn clone(&self) -> Self {
145        Self(self.0.clone())
146    }
147}
148
149/// * Dishonest reader, a reader that reads data but modifies it.
150pub struct DishonestReader<T>
151where
152    T: Read + Seek + Debug {
153    reader: T,
154    on_read: Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>,
155    on_seek: Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>,
156    cache: Vec<u8>,
157}
158
159impl<T> DishonestReader<T>
160where
161    T: Read + Seek + Debug {
162    pub fn new(
163        reader: T,
164        on_read: Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>,
165        on_seek: Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>,
166    ) -> Self {
167        Self {
168            reader,
169            on_read,
170            on_seek,
171            cache: Vec::new(),
172        }
173    }
174}
175
176impl<T> Read for DishonestReader<T>
177where
178    T: Read + Seek + Debug {
179    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
180        let write_buf_and_cache = |data: &[u8], buf: &mut [u8], cache: &mut Vec<u8>| -> usize {
181            let len = min(data.len(), buf.len());
182            buf[..len].copy_from_slice(&data[..len]);
183            if len < data.len() {
184                *cache = data[len..].to_vec();
185            } else {
186                *cache = Vec::new();
187            }
188            len
189        };
190        if self.cache.is_empty() {
191            match (self.on_read)(&mut self.reader, buf.len()) {
192                Ok(data) => Ok(write_buf_and_cache(&data, buf, &mut self.cache)),
193                Err(e) => Err(e),
194            }
195        } else {
196            let to_write = self.cache.clone();
197            Ok(write_buf_and_cache(&to_write, buf, &mut self.cache))
198        }
199    }
200}
201
202impl<T> Seek for DishonestReader<T>
203where
204    T: Read + Seek + Debug {
205    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
206        (self.on_seek)(&mut self.reader, pos)
207    }
208}
209
210impl<T> Debug for DishonestReader<T>
211where
212    T: Read + Seek + Debug {
213    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
214        let typename = type_name::<T>();
215        f.debug_struct(&format!("DishonestReader<{typename}>"))
216        .field("reader", &self.reader)
217        .field("on_read", &format_args!("Box<dyn FnMut(&mut T, usize) -> io::Result<Vec<u8>>>"))
218        .field("on_seek", &format_args!("Box<dyn FnMut(&mut T, SeekFrom) -> io::Result<u64>>"))
219        .field("cache", &format_args!("[u8; {}]", self.cache.len()))
220        .finish()
221    }
222}
223
224/// * A Reader that combines two readers into one with the ability to `Read` and `Seek` and `Debug`
225#[derive(Debug)]
226pub struct CombinedReader<R1, R2>
227where
228    R1: Reader,
229    R2: Reader {
230    first: R1,
231    first_data_offset: u64,
232    first_data_length: u64,
233    second: R2,
234    second_data_offset: u64,
235    second_data_length: u64,
236    stream_pos: u64,
237    total_length: u64,
238}
239
240impl<R1, R2> CombinedReader<R1, R2>
241where
242    R1: Reader,
243    R2: Reader {
244    pub fn new(
245        first: R1,
246        first_data_offset: u64,
247        first_data_length: u64,
248        second: R2,
249        second_data_offset: u64,
250        second_data_length: u64,
251    ) -> Self {
252        Self {
253            first,
254            first_data_offset,
255            first_data_length,
256            second,
257            second_data_offset,
258            second_data_length,
259            stream_pos: 0,
260            total_length: first_data_length + second_data_length,
261        }
262    }
263
264    fn default_read<R>(reader: &mut R, buf: &mut [u8], reader_position: u64, reader_offset: u64, reader_length: u64) -> io::Result<usize>
265    where
266        R: Reader {
267        let bytes_to_read = min((reader_length - reader_position) as usize, buf.len());
268        reader.seek(SeekFrom::Start(reader_offset + reader_position))?;
269        reader.read(&mut buf[..bytes_to_read])
270    }
271}
272
273impl<R1, R2> Read for CombinedReader<R1, R2>
274where
275    R1: Reader,
276    R2: Reader {
277    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
278        if self.stream_pos < self.first_data_length {
279            let reader = &mut self.first;
280            let reader_position = self.stream_pos;
281            let reader_offset = self.first_data_offset;
282            let reader_length = self.first_data_length;
283            let n = Self::default_read(reader, buf, reader_position, reader_offset, reader_length)?;
284            self.stream_pos += n as u64;
285            Ok(n)
286        } else if self.stream_pos < self.total_length {
287            let reader = &mut self.second;
288            let reader_position = self.stream_pos - self.first_data_length;
289            let reader_offset = self.second_data_offset;
290            let reader_length = self.second_data_length;
291            let n = Self::default_read(reader, buf, reader_position, reader_offset, reader_length)?;
292            self.stream_pos += n as u64;
293            Ok(n)
294        } else {
295            return Ok(0)
296        }
297    }
298}
299
300impl<R1, R2> Seek for CombinedReader<R1, R2>
301where
302    R1: Reader,
303    R2: Reader {
304    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
305        self.stream_pos = min(match pos {
306            SeekFrom::Start(position) => position,
307            relative => {
308                let ipos = match relative {
309                    SeekFrom::End(offset) => self.total_length as i64 + offset,
310                    SeekFrom::Current(offset) => self.stream_pos as i64 + offset,
311                    _absolute => unreachable!(),
312                };
313                if ipos < 0 {
314                    return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Seek position out of bounds: {ipos}")))
315                }
316                ipos as u64
317            }
318        }, self.total_length);
319        Ok(self.stream_pos)
320    }
321}
322
323/// * A better `Cursor<Vec<u8>>` which has a friendlier `Debug` trait implementation
324#[derive(Clone)]
325pub struct CursorVecU8(Cursor<Vec<u8>>);
326
327impl CursorVecU8 {
328    pub fn new(data: Vec<u8>) -> Self {
329        Self(Cursor::new(data))
330    }
331
332    pub fn into_inner(self) -> Vec<u8> {
333        self.0.into_inner()
334    }
335
336    pub fn len(&self) -> usize {
337        self.0.get_ref().len()
338    }
339
340    pub fn is_empty(&self) -> bool {
341        self.0.get_ref().is_empty()
342    }
343
344    pub fn clear(&mut self) {
345        self.0.get_mut().clear();
346        self.0.set_position(0);
347    }
348}
349
350impl Default for CursorVecU8 {
351    fn default() -> Self {
352        Self(Cursor::new(Vec::new()))
353    }
354}
355
356impl From<Cursor<Vec<u8>>> for CursorVecU8 {
357    fn from(cursor: Cursor<Vec<u8>>) -> Self {
358        Self(cursor)
359    }
360}
361
362impl From<CursorVecU8> for Cursor<Vec<u8>> {
363    fn from(val: CursorVecU8) -> Self {
364        val.0
365    }
366}
367
368impl Deref for CursorVecU8 {
369    type Target = Cursor<Vec<u8>>;
370
371    fn deref(&self) -> &Self::Target {
372        &self.0
373    }
374}
375
376impl DerefMut for CursorVecU8 {
377    fn deref_mut(&mut self) -> &mut Self::Target {
378        &mut self.0
379    }
380}
381
382impl Read for CursorVecU8 {
383    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
384        self.0.read(buf)
385    }
386}
387
388impl Write for CursorVecU8 {
389    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
390        self.0.write(buf)
391    }
392    fn flush(&mut self) -> io::Result<()> {
393        self.0.flush()
394    }
395}
396
397impl Seek for CursorVecU8 {
398    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
399        self.0.seek(pos)
400    }
401}
402
403impl Debug for CursorVecU8 {
404    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
405        f.debug_struct("Cursor")
406        .field("inner", &format_args!("[u8; {}]", self.0.get_ref().len()))
407        .field("pos", &self.0.position())
408        .finish()
409    }
410}
411
412impl Display for CursorVecU8 {
413    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
414        <Self as Debug>::fmt(self, f)
415    }
416}
417
418impl Index<usize> for CursorVecU8 {
419    type Output = u8;
420    fn index(&self, index: usize) -> &u8 {
421        &self.0.get_ref()[index]
422    }
423}
424
425impl IndexMut<usize> for CursorVecU8 {
426    fn index_mut(&mut self, index: usize) -> &mut u8 {
427        &mut self.0.get_mut()[index]
428    }
429}
430
431impl Index<Range<usize>> for CursorVecU8 {
432    type Output = [u8];
433    fn index(&self, range: Range<usize>) -> &[u8] {
434        &self.0.get_ref()[range]
435    }
436}
437
438impl IndexMut<Range<usize>> for CursorVecU8 {
439    fn index_mut(&mut self, range: Range<usize>) -> &mut [u8] {
440        &mut self.0.get_mut()[range]
441    }
442}
443
444impl Index<RangeFrom<usize>> for CursorVecU8 {
445    type Output = [u8];
446    fn index(&self, range: RangeFrom<usize>) -> &[u8] {
447        &self.0.get_ref()[range]
448    }
449}
450
451impl IndexMut<RangeFrom<usize>> for CursorVecU8 {
452    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut [u8] {
453        &mut self.0.get_mut()[range]
454    }
455}
456
457impl Index<RangeTo<usize>> for CursorVecU8 {
458    type Output = [u8];
459    fn index(&self, range: RangeTo<usize>) -> &[u8] {
460        &self.0.get_ref()[range]
461    }
462}
463
464impl IndexMut<RangeTo<usize>> for CursorVecU8 {
465    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut [u8] {
466        &mut self.0.get_mut()[range]
467    }
468}
469
470impl Index<RangeFull> for CursorVecU8 {
471    type Output = [u8];
472    fn index(&self, _range: RangeFull) -> &[u8] {
473        &self.0.get_ref()[..]
474    }
475}
476
477impl IndexMut<RangeFull> for CursorVecU8 {
478    fn index_mut(&mut self, _range: RangeFull) -> &mut [u8] {
479        &mut self.0.get_mut()[..]
480    }
481}
482
483/// * The shared `Cursor`.
484/// * Because it's shared, when the 3rd library owned it, we still can access to it..
485#[derive(Debug)]
486pub struct SharedCursor (Rc<RefCell<CursorVecU8>>);
487
488impl SharedCursor {
489    pub fn new() -> Self {
490        Self::default()
491    }
492
493    /// * Get the inner data size
494    pub fn len(&self) -> usize {
495        self.0.borrow().get_ref().len()
496    }
497
498    /// * Check if the inner data is empty
499    pub fn is_empty(&self) -> bool {
500        self.len() == 0
501    }
502
503    /// * Get the inner data as `Vec<u8>`
504    pub fn get_vec(&self) -> Vec<u8> {
505        self.0.borrow().get_ref().to_vec()
506    }
507
508    /// * Discard current inner data, replace it with new data, and set the read/write position to the end of the data
509    pub fn set_vec(&mut self, data: &[u8], rw_pos: u64) {
510        let mut new_cursor = CursorVecU8::new(data.to_vec());
511        new_cursor.set_position(rw_pos);
512        *self.0.borrow_mut() = new_cursor;
513    }
514
515    /// * Discard the inner data, set the read/write position to 0
516    pub fn clear(&mut self) {
517        *self.0.borrow_mut() = CursorVecU8::default();
518    }
519}
520
521impl Default for SharedCursor {
522    fn default() -> Self {
523        Self(Rc::new(RefCell::new(CursorVecU8::default())))
524    }
525}
526
527impl Read for SharedCursor {
528    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
529        self.0.borrow_mut().read(buf)
530    }
531}
532
533impl Write for SharedCursor {
534    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
535        self.0.borrow_mut().write(buf)
536    }
537    fn flush(&mut self) -> io::Result<()> {
538        self.0.borrow_mut().flush()
539    }
540}
541
542impl Seek for SharedCursor {
543    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
544        self.0.borrow_mut().seek(pos)
545    }
546}
547
548impl Clone for SharedCursor {
549    fn clone(&self) -> Self {
550        Self(self.0.clone())
551    }
552}
553
554/// * The `StreamType<R, W, RW>` is for the `MultistreamIO<R, W, RW>` to manage multiple IO objects.
555/// * A stream can be a reader, writer, reader + writer, or cursor.
556/// * By using the `MultistreamIO<R, W, RW>` you can control the 3rd party library to write data into different streams and manipulate them.
557#[derive(Debug)]
558pub enum StreamType<R, W, RW>
559where
560    R: Read + Seek + Debug,
561    W: Write + Seek + Debug,
562    RW: Read + Write + Seek + Debug {
563    /// * The `Read + Seek + Debug`
564    Reader(R),
565
566    /// * The `Write + Seek + Debug`
567    Writer(W),
568
569    /// * The `Read + Write + Seek + Debug`, better use it with the `tempfile()`
570    ReadWrite(RW),
571
572    /// * The `Read + Write + Seek + Debug` cursor.
573    CursorU8(CursorVecU8)
574}
575
576impl<R, W, RW> StreamType<R, W, RW>
577where
578    R: Read + Seek + Debug,
579    W: Write + Seek + Debug,
580    RW: Read + Write + Seek + Debug {
581
582    pub fn as_reader(&mut self) -> &mut R {
583        let name_r = type_name::<R>();
584        let name_w = type_name::<W>();
585        let name_rw = type_name::<RW>();
586        match self {
587            Self::Reader(reader) => reader,
588            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
589        }
590    }
591
592    pub fn as_writer(&mut self) -> &mut W {
593        let name_r = type_name::<R>();
594        let name_w = type_name::<W>();
595        let name_rw = type_name::<RW>();
596        match self {
597            Self::Writer(writer) => writer,
598            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
599        }
600    }
601
602    pub fn as_readwrite(&mut self) -> &mut RW {
603        let name_r = type_name::<R>();
604        let name_w = type_name::<W>();
605        let name_rw = type_name::<RW>();
606        match self {
607            Self::ReadWrite(readwrite) => readwrite,
608            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
609        }
610    }
611
612    pub fn as_cursor(&mut self) -> &mut CursorVecU8 {
613        let name_r = type_name::<R>();
614        let name_w = type_name::<W>();
615        let name_rw = type_name::<RW>();
616        match self {
617            Self::CursorU8(cursor) => cursor,
618            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
619        }
620    }
621
622    /// * Take the cursor data, leaving an empty cursor here.
623    pub fn take_cursor_data(&mut self) -> Vec<u8> {
624        let name_r = type_name::<R>();
625        let name_w = type_name::<W>();
626        let name_rw = type_name::<RW>();
627        match self {
628            Self::CursorU8(cursor) => {
629                mem::take(cursor).into_inner()
630            }
631            o => panic!("The `StreamType<{name_r}, {name_w}, {name_rw}>` is {:?}", o),
632        }
633    }
634}
635
636impl<R, W, RW> Read for StreamType<R, W, RW>
637where
638    R: Read + Seek + Debug,
639    W: Write + Seek + Debug,
640    RW: Read + Write + Seek + Debug {
641    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
642        match self {
643            Self::Reader(reader) => {
644                reader.read(buf)
645            }
646            Self::ReadWrite(readwrite) => {
647                readwrite.read(buf)
648            }
649            Self::CursorU8(cursor) => {
650                cursor.read(buf)
651            }
652            Self::Writer(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Writer()` can't read.")),
653        }
654    }
655}
656
657impl<R, W, RW> Write for StreamType<R, W, RW>
658where
659    R: Read + Seek + Debug,
660    W: Write + Seek + Debug,
661    RW: Read + Write + Seek + Debug {
662    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
663        match self {
664            Self::Writer(writer) => {
665                writer.write(buf)
666            }
667            Self::ReadWrite(readwrite) => {
668                readwrite.write(buf)
669            }
670            Self::CursorU8(cursor) => {
671                cursor.write(buf)
672            }
673            Self::Reader(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Reader()` can't write.")),
674        }
675    }
676    fn flush(&mut self) -> io::Result<()> {
677        match self {
678            Self::Writer(writer) => {
679                writer.flush()
680            }
681            Self::ReadWrite(readwrite) => {
682                readwrite.flush()
683            }
684            Self::CursorU8(cursor) => {
685                cursor.flush()
686            }
687            Self::Reader(_) => Err(io::Error::new(io::ErrorKind::Unsupported, "`StreamType::Reader()` can't flush.")),
688        }
689    }
690}
691
692impl<R, W, RW> Seek for StreamType<R, W, RW>
693where
694    R: Read + Seek + Debug,
695    W: Write + Seek + Debug,
696    RW: Read + Write + Seek + Debug {
697    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
698        match self {
699            Self::Reader(reader) => {
700                reader.seek(pos)
701            }
702            Self::Writer(writer) => {
703                writer.seek(pos)
704            }
705            Self::ReadWrite(readwrite) => {
706                readwrite.seek(pos)
707            }
708            Self::CursorU8(cursor) => {
709                cursor.seek(pos)
710            }
711        }
712    }
713}
714
715/// * The `MultistreamIO<R, W, RW>` is for managing multiple IO objects.
716/// * This thing itself implements `Read + Write + Seek + Debug`, when these traits methods are called, the selected stream is manipulated.
717/// * 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.
718#[derive(Debug)]
719pub struct MultistreamIO<R, W, RW>
720where
721    R: Read + Seek + Debug,
722    W: Write + Seek + Debug,
723    RW: Read + Write + Seek + Debug {
724    pub streams: Vec<StreamType<R, W, RW>>,
725    pub cur_stream: usize,
726}
727
728impl<R, W, RW> Default for MultistreamIO<R, W, RW>
729where
730    R: Read + Seek + Debug,
731    W: Write + Seek + Debug,
732    RW: Read + Write + Seek + Debug {
733    fn default() -> Self {
734        Self {
735            streams: Vec::new(),
736            cur_stream: 0,
737        }
738    }
739}
740
741impl<R, W, RW> MultistreamIO<R, W, RW>
742where
743    R: Read + Seek + Debug,
744    W: Write + Seek + Debug,
745    RW: Read + Write + Seek + Debug {
746
747    pub fn new() -> Self {
748        Self::default()
749    }
750
751    /// * Get the current selected stream object
752    pub fn get_cur_stream(&self) -> &StreamType<R, W, RW> {
753        &self.streams[self.cur_stream]
754    }
755
756    /// * Get the current selected stream object as mutable
757    pub fn get_cur_stream_mut(&mut self) -> &mut StreamType<R, W, RW> {
758        &mut self.streams[self.cur_stream]
759    }
760
761    /// * Get a stream object using an index
762    pub fn get_stream(&self, index: usize) -> &StreamType<R, W, RW> {
763        &self.streams[index]
764    }
765
766    /// * Get a mutable stream object using an index
767    pub fn get_stream_mut(&mut self, index: usize) -> &mut StreamType<R, W, RW> {
768        &mut self.streams[index]
769    }
770
771    /// * Add a new stream
772    pub fn push_stream(&mut self, stream: StreamType<R, W, RW>) {
773        self.streams.push(stream);
774    }
775
776    /// * Pop out the last stream
777    pub fn pop_stream(&mut self) -> Option<StreamType<R, W, RW>> {
778        self.streams.pop()
779    }
780
781    /// * Set the current stream index
782    pub fn set_stream(&mut self, index: usize) {
783        self.cur_stream = index;
784    }
785
786    /// * The number of streams in total
787    pub fn len(&self) -> usize {
788        self.streams.len()
789    }
790
791    /// * Is there no stream objects?
792    pub fn is_empty(&self) -> bool {
793        self.streams.is_empty()
794    }
795}
796
797impl<R, W, RW> Read for MultistreamIO<R, W, RW>
798where
799    R: Read + Seek + Debug,
800    W: Write + Seek + Debug,
801    RW: Read + Write + Seek + Debug {
802    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
803        self.get_cur_stream_mut().read(buf)
804    }
805}
806
807impl<R, W, RW> Write for MultistreamIO<R, W, RW>
808where
809    R: Read + Seek + Debug,
810    W: Write + Seek + Debug,
811    RW: Read + Write + Seek + Debug {
812    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
813        self.get_cur_stream_mut().write(buf)
814    }
815    fn flush(&mut self) -> io::Result<()> {
816        self.get_cur_stream_mut().flush()
817    }
818}
819
820impl<R, W, RW> Seek for MultistreamIO<R, W, RW>
821where
822    R: Read + Seek + Debug,
823    W: Write + Seek + Debug,
824    RW: Read + Write + Seek + Debug {
825    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
826        self.get_cur_stream_mut().seek(pos)
827    }
828}
829
830impl<R, W, RW> Index<usize> for MultistreamIO<R, W, RW>
831where
832    R: Read + Seek + Debug,
833    W: Write + Seek + Debug,
834    RW: Read + Write + Seek + Debug {
835    type Output = StreamType<R, W, RW>;
836
837    fn index(&self, index: usize) -> &Self::Output {
838        &self.streams[index]
839    }
840}
841
842impl<R, W, RW> IndexMut<usize> for MultistreamIO<R, W, RW>
843where
844    R: Read + Seek + Debug,
845    W: Write + Seek + Debug,
846    RW: Read + Write + Seek + Debug {
847    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
848        &mut self.streams[index]
849    }
850}
851
852impl<R, W, RW> Index<Range<usize>> for MultistreamIO<R, W, RW>
853where
854    R: Read + Seek + Debug,
855    W: Write + Seek + Debug,
856    RW: Read + Write + Seek + Debug {
857    type Output = [StreamType<R, W, RW>];
858
859    fn index(&self, range: Range<usize>) -> &Self::Output {
860        &self.streams[range]
861    }
862}
863
864impl<R, W, RW> IndexMut<Range<usize>> for MultistreamIO<R, W, RW>
865where
866    R: Read + Seek + Debug,
867    W: Write + Seek + Debug,
868    RW: Read + Write + Seek + Debug {
869    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
870        &mut self.streams[range]
871    }
872}
873
874impl<R, W, RW> Index<RangeFrom<usize>> for MultistreamIO<R, W, RW>
875where
876    R: Read + Seek + Debug,
877    W: Write + Seek + Debug,
878    RW: Read + Write + Seek + Debug {
879    type Output = [StreamType<R, W, RW>];
880
881    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
882        &self.streams[range]
883    }
884}
885
886impl<R, W, RW> IndexMut<RangeFrom<usize>> for MultistreamIO<R, W, RW>
887where
888    R: Read + Seek + Debug,
889    W: Write + Seek + Debug,
890    RW: Read + Write + Seek + Debug {
891    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
892        &mut self.streams[range]
893    }
894}
895
896impl<R, W, RW> Index<RangeTo<usize>> for MultistreamIO<R, W, RW>
897where
898    R: Read + Seek + Debug,
899    W: Write + Seek + Debug,
900    RW: Read + Write + Seek + Debug {
901    type Output = [StreamType<R, W, RW>];
902
903    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
904        &self.streams[range]
905    }
906}
907
908impl<R, W, RW> IndexMut<RangeTo<usize>> for MultistreamIO<R, W, RW>
909where
910    R: Read + Seek + Debug,
911    W: Write + Seek + Debug,
912    RW: Read + Write + Seek + Debug {
913    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
914        &mut self.streams[range]
915    }
916}
917
918impl<R, W, RW> Index<RangeFull> for MultistreamIO<R, W, RW>
919where
920    R: Read + Seek + Debug,
921    W: Write + Seek + Debug,
922    RW: Read + Write + Seek + Debug {
923    type Output = [StreamType<R, W, RW>];
924
925    fn index(&self, _range: RangeFull) -> &Self::Output {
926        &self.streams[..]
927    }
928}
929
930impl<R, W, RW> IndexMut<RangeFull> for MultistreamIO<R, W, RW>
931where
932    R: Read + Seek + Debug,
933    W: Write + Seek + Debug,
934    RW: Read + Write + Seek + Debug {
935    fn index_mut(&mut self, _range: RangeFull) -> &mut Self::Output {
936        &mut self.streams[..]
937    }
938}
939
940/// * The shared version of the `MultistreamIO`.
941/// * 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.
942#[derive(Debug)]
943pub struct SharedMultistreamIO<R, W, RW> (Rc<RefCell<MultistreamIO<R, W, RW>>>)
944where
945    R: Read + Seek + Debug,
946    W: Write + Seek + Debug,
947    RW: Read + Write + Seek + Debug;
948
949impl<R, W, RW> SharedMultistreamIO<R, W, RW>
950where
951    R: Read + Seek + Debug,
952    W: Write + Seek + Debug,
953    RW: Read + Write + Seek + Debug {
954    pub fn new(writer_with_cursor: MultistreamIO<R, W, RW>) -> Self {
955        Self(Rc::new(RefCell::new(writer_with_cursor)))
956    }
957}
958
959impl<R, W, RW> Deref for SharedMultistreamIO<R, W, RW>
960where
961    R: Read + Seek + Debug,
962    W: Write + Seek + Debug,
963    RW: Read + Write + Seek + Debug {
964    type Target = MultistreamIO<R, W, RW>;
965
966    fn deref(&self) -> &Self::Target {
967        unsafe { &*(self.0.as_ptr() as *const MultistreamIO<R, W, RW>) }
968    }
969}
970
971impl<R, W, RW> DerefMut for SharedMultistreamIO<R, W, RW>
972where
973    R: Read + Seek + Debug,
974    W: Write + Seek + Debug,
975    RW: Read + Write + Seek + Debug {
976    fn deref_mut(&mut self) -> &mut Self::Target {
977        unsafe { &mut *self.0.as_ptr() }
978    }
979}
980
981impl<R, W, RW> Read for SharedMultistreamIO<R, W, RW>
982where
983    R: Read + Seek + Debug,
984    W: Write + Seek + Debug,
985    RW: Read + Write + Seek + Debug {
986    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
987        self.0.borrow_mut().read(buf)
988    }
989}
990
991impl<R, W, RW> Write for SharedMultistreamIO<R, W, RW>
992where
993    R: Read + Seek + Debug,
994    W: Write + Seek + Debug,
995    RW: Read + Write + Seek + Debug {
996    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
997        self.0.borrow_mut().write(buf)
998    }
999    fn flush(&mut self) -> io::Result<()> {
1000        self.0.borrow_mut().flush()
1001    }
1002}
1003
1004impl<R, W, RW> Seek for SharedMultistreamIO<R, W, RW>
1005where
1006    R: Read + Seek + Debug,
1007    W: Write + Seek + Debug,
1008    RW: Read + Write + Seek + Debug {
1009    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1010        self.0.borrow_mut().seek(pos)
1011    }
1012}
1013
1014impl<R, W, RW> Clone for SharedMultistreamIO<R, W, RW>
1015where
1016    R: Read + Seek + Debug,
1017    W: Write + Seek + Debug,
1018    RW: Read + Write + Seek + Debug {
1019    fn clone(&self) -> Self {
1020        Self(self.0.clone())
1021    }
1022}
1023
1024impl<R, W, RW> Default for SharedMultistreamIO<R, W, RW>
1025where
1026    R: Read + Seek + Debug,
1027    W: Write + Seek + Debug,
1028    RW: Read + Write + Seek + Debug {
1029    fn default() -> Self {
1030        Self(Rc::new(RefCell::new(MultistreamIO::new())))
1031    }
1032}
1033
1034/// * Go to an offset without using seek. It's achieved by using dummy reads.
1035pub fn goto_offset_without_seek<T>(
1036    mut reader: T,
1037    cur_pos: &mut u64,
1038    position: u64,
1039) -> io::Result<u64>
1040where
1041    T: Read,
1042{
1043    const SKIP_SIZE: u64 = 1024;
1044    let mut skip_buf = [0u8; SKIP_SIZE as usize];
1045    while *cur_pos + SKIP_SIZE <= position {
1046        reader.read_exact(&mut skip_buf)?;
1047        *cur_pos += SKIP_SIZE;
1048    }
1049    if *cur_pos < position {
1050        let mut skip_buf = vec![0u8; (position - *cur_pos) as usize];
1051        reader.read_exact(&mut skip_buf)?;
1052        *cur_pos = position;
1053    }
1054    if *cur_pos > position {
1055        Err(io::Error::new(
1056            io::ErrorKind::NotSeekable,
1057            format!(
1058                "The current position {cur_pos} has already exceeded the target position {position}"
1059            ),
1060        ))
1061    } else {
1062        Ok(*cur_pos)
1063    }
1064}
1065
1066/// * Copy data from a reader to a writer from the current position.
1067pub fn copy<R, W>(reader: &mut R, writer: &mut W, bytes_to_copy: u64) -> io::Result<()>
1068where
1069    R: Read,
1070    W: Write,
1071{
1072    const BUFFER_SIZE: u64 = 1024;
1073    let mut buf = vec![0u8; BUFFER_SIZE as usize];
1074    let mut to_copy = bytes_to_copy;
1075    while to_copy >= BUFFER_SIZE {
1076        reader.read_exact(&mut buf)?;
1077        writer.write_all(&buf)?;
1078        to_copy -= BUFFER_SIZE;
1079    }
1080    if to_copy > 0 {
1081        buf.resize(to_copy as usize, 0);
1082        reader.read_exact(&mut buf)?;
1083        writer.write_all(&buf)?;
1084    }
1085    Ok(())
1086}
1087
1088/// * This is for read/write strings from/to file with specific encoding and size, or read/write as NUL-terminated strings.
1089pub mod string_io {
1090    use savagestr::{SavageStringCodecs, StringCodecMaps};
1091    use std::io::{self, Read, Write};
1092
1093    /// * Read some bytes, and return the bytes, without you to create a local `vec![0u8; size]` and scratch your head with the messy codes
1094    pub fn read_bytes<T: Read>(r: &mut T, size: usize) -> io::Result<Vec<u8>> {
1095        let mut buf = vec![0u8; size];
1096        r.read_exact(&mut buf)?;
1097        Ok(buf)
1098    }
1099
1100    /// * Read a fixed-size string and decode it using the `StringCodecMaps`
1101    pub fn read_str<T: Read>(
1102        r: &mut T,
1103        size: usize,
1104        text_encoding: &StringCodecMaps,
1105    ) -> io::Result<String> {
1106        let mut buf = vec![0u8; size];
1107        r.read_exact(&mut buf)?;
1108        Ok(text_encoding
1109            .decode(&buf)
1110            .trim_matches(char::from(0))
1111            .to_string())
1112    }
1113
1114    /// * Read a fixed-size string and decode it using the `StringCodecMaps` while you can specify the code page.
1115    pub fn read_str_by_code_page<T: Read>(
1116        r: &mut T,
1117        size: usize,
1118        text_encoding: &StringCodecMaps,
1119        code_page: u32,
1120    ) -> io::Result<String> {
1121        let mut buf = vec![0u8; size];
1122        r.read_exact(&mut buf)?;
1123        Ok(text_encoding
1124            .decode_bytes_by_code_page(&buf, code_page)
1125            .trim_matches(char::from(0))
1126            .to_string())
1127    }
1128
1129    /// * Read a NUL terminated string by raw, not decode it.
1130    pub fn read_sz_raw<T: Read>(r: &mut T) -> io::Result<Vec<u8>> {
1131        let mut buf = Vec::<u8>::new();
1132        loop {
1133            let b = [0u8; 1];
1134            r.read_exact(&mut buf)?;
1135            let b = b[0];
1136            if b != 0 {
1137                buf.push(b);
1138            } else {
1139                break;
1140            }
1141        }
1142        Ok(buf)
1143    }
1144
1145    /// * Read a NUL terminated string and decode it.
1146    pub fn read_sz<T: Read>(
1147        r: &mut T,
1148        text_encoding: &StringCodecMaps,
1149    ) -> io::Result<String> {
1150        Ok(text_encoding
1151            .decode(&read_sz_raw(r)?)
1152            .trim_matches(char::from(0))
1153            .to_string())
1154    }
1155
1156    /// * Read a NUL terminated string and decode it with the specified code page.
1157    pub fn read_sz_by_code_page<T: Read>(
1158        r: &mut T,
1159        text_encoding: &StringCodecMaps,
1160        code_page: u32,
1161    ) -> io::Result<String> {
1162        Ok(text_encoding
1163            .decode_bytes_by_code_page(&read_sz_raw(r)?, code_page)
1164            .trim_matches(char::from(0))
1165            .to_string())
1166    }
1167
1168    /// * Write a fixed-size encoded string.
1169    pub fn write_str_sized<T: Write + ?Sized>(
1170        w: &mut T,
1171        data: &str,
1172        size: usize,
1173        text_encoding: &StringCodecMaps,
1174    ) -> io::Result<()> {
1175        let mut data = text_encoding.encode(data);
1176        data.resize(size, 0);
1177        w.write_all(&data)?;
1178        Ok(())
1179    }
1180
1181    /// * Write an encoded string.
1182    pub fn write_str<T: Write + ?Sized>(
1183        w: &mut T,
1184        data: &str,
1185        text_encoding: &StringCodecMaps,
1186    ) -> io::Result<()> {
1187        let data = text_encoding.encode(data);
1188        w.write_all(&data)?;
1189        Ok(())
1190    }
1191
1192    /// * Write an encoded string encoded with the specified code page.
1193    pub fn write_str_by_code_page<T: Write + ?Sized>(
1194        w: &mut T,
1195        data: &str,
1196        text_encoding: &StringCodecMaps,
1197        code_page: u32,
1198    ) -> io::Result<()> {
1199        let data = text_encoding.encode_strings_by_code_page(data, code_page);
1200        w.write_all(&data)?;
1201        Ok(())
1202    }
1203}