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
/*
 * Created on Sun Dec 13 2020
 *
 * Copyright (c) storycraft. Licensed under the Apache Licence 2.0.
 */

use std::{cell::RefCell, collections::hash_map::Iter, io::{Read, Seek, Write}};

use super::{VirtualXP3, XP3Error, XP3ErrorKind, index::file::XP3FileIndex, reader::XP3Reader};

/// An XP3 archive with XP3 container.
/// Read only occur when user request.
#[derive(Debug)]
pub struct XP3Archive<T: Read + Seek> {

    container: VirtualXP3,

    stream: RefCell<T>

}

impl<T: Read + Seek> XP3Archive<T> {

    pub fn new(container: VirtualXP3, data: T) -> Self {
        Self {
            container,
            stream: RefCell::new(data)
        }
    }

    pub fn container(&self) -> &VirtualXP3 {
        &self.container
    }

    pub fn entries(&self) -> Iter<String, XP3FileIndex> {
        self.container.index_set().entries()
    }

    /// Unpack file to stream
    pub fn unpack<W: Write>(&self, name: &String, stream: &mut W) -> Result<(), XP3Error> {
        let item = self.container.index_set().get(name);

        match item {
            Some(index) => {
                for segment in index.segments().iter() {
                    XP3Reader::read_segment(segment, self.stream.borrow_mut().by_ref(), stream)?;
                }

                Ok(())
            },

            None => Err(XP3Error::new(XP3ErrorKind::FileNotFound, None))
        }
    }

    /// Close xp3 archive
    pub fn close(self) -> (VirtualXP3, T) {
        (self.container, self.stream.into_inner())
    }

}