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
#![warn(clippy::as_conversions)]

/// Pak Entry impl
mod entry;
/// A wrapper for file times
pub mod file_time;
/// Pak impl
mod pak;
/// Util for reading Pak files.
pub(crate) mod reader;
/// Util for writing Pak files.
pub(crate) mod writer;

pub use crate::entry::Entry;
pub use crate::file_time::FileTime;
pub use crate::pak::Pak;

/// The magic number of a valid pak file.
///
/// `[0xc0, 0x4a, 0xc0, 0xba]` XORed with `0xf7`, or "7½7M".
/// This file type is often called "7x7M" as a result.
pub(crate) const MAGIC: &[u8] = &[0xc0, 0x4a, 0xc0, 0xba];
/// The version of pakfile that this library can read.
///
/// `[0; 4]`.
pub(crate) const VERSION: &[u8] = &[0; 4];

/// The default file flag
const FILEFLAGS_DEFAULT: u8 = 0x00;
/// The end file flag.
const FILEFLAGS_END: u8 = 0x80;

/// Error type of this library
#[derive(Debug)]
pub enum PakError {
    /// IO errors that may occur during use
    Io(std::io::Error),

    /// Invalid Magic number.
    ///
    /// See [`MAGIC`].
    InvalidMagic([u8; 4]),

    /// Invalid Pak Version.
    ///
    /// See [`VERSION`].
    InvalidVersion([u8; 4]),

    /// The filename is too long.
    ///
    /// See [`MAX_NAME_LEN`].
    InvalidFileNameLength {
        length: usize,
        error: std::num::TryFromIntError,
    },

    /// The file data is too long.
    ///
    /// See [`MAX_DATA_LEN`].
    InvalidFileDataLength {
        length: usize,
        error: std::num::TryFromIntError,
    },

    /// The size of the file data in the record is too long.
    InvalidRecordFileSize {
        file_size: u32,
        error: std::num::TryFromIntError,
    },
}

impl From<std::io::Error> for PakError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl std::fmt::Display for PakError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => e.fmt(f),
            Self::InvalidMagic(magic) => {
                write!(f, "invalid magic number '{magic:?}', expected '{MAGIC:?}'",)
            }
            Self::InvalidVersion(version) => {
                write!(f, "invalid version '{version:?}', expected '{VERSION:?}'",)
            }
            Self::InvalidFileNameLength { length, .. } => {
                write!(f, "invalid file name length '{length}'")
            }
            Self::InvalidFileDataLength { length, .. } => {
                write!(f, "invalid file data length '{length}'")
            }
            Self::InvalidRecordFileSize { file_size, .. } => {
                write!(f, "invalid record file size '{file_size}'")
            }
        }
    }
}

impl std::error::Error for PakError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::InvalidFileNameLength { error, .. } => Some(error),
            Self::InvalidFileDataLength { error, .. } => Some(error),
            Self::InvalidRecordFileSize { error, .. } => Some(error),
            _ => None,
        }
    }
}

/// A record, describing a file
#[derive(Debug)]
struct Record {
    /// The file name
    pub name: Vec<u8>,
    /// The file size
    pub file_size: u32,
    /// The file time
    pub file_time: FileTime,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    const EXTRACT_PATH: &str = "test-extract";
    const PAK_PATH: &str = "test_data/Simple Building.pak";

    fn extract(pak: &mut Pak, extract_dir: &Path) {
        let _ = std::fs::remove_dir_all(extract_dir);

        for entry in pak.entries.iter_mut() {
            let entry_path = entry.path_str().unwrap();
            let entry_dir = entry.dir_str().transpose().unwrap();
            let entry_name = entry.name_str().unwrap();

            let (expected_entry_dir, expected_entry_name) = entry_path
                .rsplit_once(['/', '\\'])
                .map(|(dir, name)| (Some(dir), name))
                .unwrap_or((None, entry_path));
            assert!(
                expected_entry_name == entry_name,
                "{expected_entry_name} != {entry_name}"
            );
            assert!(
                expected_entry_dir == entry_dir,
                "{expected_entry_dir:?} != {entry_dir:?}"
            );

            println!("Extracting '{}'...", entry_path);
            if let Some(dir) = entry_dir {
                let entry_extract_dir = extract_dir.join(dir);
                std::fs::create_dir_all(&entry_extract_dir).unwrap();
            }

            let entry_extract_path = extract_dir.join(entry_path);
            let mut f = std::fs::File::create(&entry_extract_path).unwrap();
            std::io::copy(entry, &mut f).unwrap();
        }
    }

    #[test]
    fn extract_read() {
        let f = std::fs::File::open(PAK_PATH).unwrap();
        let mut p = Pak::from_read(f).unwrap();
        let extract_dir = Path::new(EXTRACT_PATH).join("read");

        extract(&mut p, &extract_dir);
    }

    #[test]
    fn extract_bytes() {
        let data = std::fs::read(PAK_PATH).unwrap();
        let mut p = Pak::from_bytes(&data).unwrap();
        let extract_dir = Path::new(EXTRACT_PATH).join("bytes");

        extract(&mut p, &extract_dir);
    }

    #[test]
    fn bytes_vs_read() {
        let data = std::fs::read(PAK_PATH).unwrap();
        let read = Pak::from_read(std::io::Cursor::new(&data)).unwrap();
        let bytes = Pak::from_bytes(&data).unwrap();
        assert_eq!(bytes, read);
    }

    #[test]
    fn round_trip() {
        let original = std::fs::read(PAK_PATH).unwrap();
        let mut pak = Pak::from_read(std::io::Cursor::new(&original)).unwrap();
        let mut round = Vec::new();
        pak.write_to(&mut round).unwrap();
        assert_eq!(&round, &original);
        let pak2 = Pak::from_read(std::io::Cursor::new(&round)).unwrap();
        assert_eq!(pak, pak2);
    }
}