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
// SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
// SPDX-License-Identifier: GPL-3.0-or-later

#![allow(clippy::identity_op)]

use std::io::SeekFrom;

use crate::common::Platform;
use crate::crc::Jamcrc;
use binrw::binrw;
use binrw::BinRead;
use modular_bitfield::prelude::*;

#[binrw]
#[br(magic = b"SqPack")]
pub struct SqPackHeader {
    #[br(pad_before = 2)]
    platform_id: Platform,
    #[br(pad_before = 3)]
    size: u32,
    version: u32,
    file_type: u32,
}

#[binrw]
pub struct SqPackIndexHeader {
    size: u32,
    file_type: u32,
    index_data_offset: u32,
    index_data_size: u32,
}

#[bitfield]
#[binrw]
#[br(map = Self::from_bytes)]
#[derive(Clone, Copy, Debug)]
pub struct IndexHashBitfield {
    pub size: B1,
    pub data_file_id: B3,
    pub offset: B28,
}

#[binrw]
pub struct IndexHashTableEntry {
    pub hash: u64,
    #[br(pad_after = 4)]
    pub(crate) bitfield: IndexHashBitfield,
}

// The only difference between index and index2 is how the path hash is stored.
// The folder name and the filename are split in index1 (hence why it's 64-bits and not 32-bit)
// But in index2, its both the file and folder name in one single CRC hash.
#[binrw]
#[derive(Debug)]
pub struct Index2HashTableEntry {
    pub hash: u32,
    pub(crate) bitfield: IndexHashBitfield,
}

#[derive(Debug)]
pub struct IndexEntry {
    pub hash: u64,
    pub data_file_id: u8,
    pub offset: u32,
}

#[binrw]
#[br(little)]
pub struct IndexFile {
    sqpack_header: SqPackHeader,

    #[br(seek_before = SeekFrom::Start(sqpack_header.size.into()))]
    index_header: SqPackIndexHeader,

    #[br(seek_before = SeekFrom::Start(index_header.index_data_offset.into()))]
    // +4 because of padding
    #[br(count = index_header.index_data_size / core::mem::size_of::<IndexHashTableEntry>() as u32 + 4)]
    pub entries: Vec<IndexHashTableEntry>,
}

#[binrw]
#[br(little)]
pub struct Index2File {
    sqpack_header: SqPackHeader,

    #[br(seek_before = SeekFrom::Start(sqpack_header.size.into()))]
    index_header: SqPackIndexHeader,

    #[br(seek_before = SeekFrom::Start(index_header.index_data_offset.into()))]
    #[br(count = index_header.index_data_size / core::mem::size_of::<Index2HashTableEntry>() as u32)]
    pub entries: Vec<Index2HashTableEntry>,
}

const CRC: Jamcrc = Jamcrc::new();

impl IndexFile {
    /// Creates a new reference to an existing index file.
    pub fn from_existing(path: &str) -> Option<Self> {
        let mut index_file = std::fs::File::open(path).ok()?;

        Self::read(&mut index_file).ok()
    }

    /// Calculates a partial hash for a given path
    pub fn calculate_partial_hash(path: &str) -> u32 {
        let lowercase = path.to_lowercase();

        CRC.checksum(lowercase.as_bytes())
    }

    /// Calculates a hash for `index` files from a game path.
    pub fn calculate_hash(path: &str) -> u64 {
        let lowercase = path.to_lowercase();

        if let Some(pos) = lowercase.rfind('/') {
            let (directory, filename) = lowercase.split_at(pos);

            let directory_crc = CRC.checksum(directory.as_bytes());
            let filename_crc = CRC.checksum(filename[1..filename.len()].as_bytes());

            (directory_crc as u64) << 32 | (filename_crc as u64)
        } else {
            CRC.checksum(lowercase.as_bytes()) as u64
        }
    }

    // TODO: turn into traits?
    pub fn exists(&self, path: &str) -> bool {
        let hash = IndexFile::calculate_hash(path);
        self.entries.iter().any(|s| s.hash == hash)
    }

    pub fn find_entry(&self, path: &str) -> Option<&IndexHashTableEntry> {
        let hash = IndexFile::calculate_hash(path);
        self.entries.iter().find(|s| s.hash == hash)
    }
}

impl Index2File {
    /// Creates a new reference to an existing index2 file.
    pub fn from_existing(path: &str) -> Option<Self> {
        let mut index_file = std::fs::File::open(path).ok()?;

        Self::read(&mut index_file).ok()
    }

    /// Calculates a hash for `index2` files from a game path.
    pub fn calculate_hash(path: &str) -> u32 {
        let lowercase = path.to_lowercase();

        CRC.checksum(lowercase.as_bytes())
    }

    pub fn exists(&self, path: &str) -> bool {
        let hash = Index2File::calculate_hash(path);
        self.entries.iter().any(|s| s.hash == hash)
    }

    pub fn find_entry(&self, path: &str) -> Option<&Index2HashTableEntry> {
        let hash = Index2File::calculate_hash(path);
        self.entries.iter().find(|s| s.hash == hash)
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    #[test]
    fn test_index_invalid() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("random");

        // Feeding it invalid data should not panic
        IndexFile::from_existing(d.to_str().unwrap());
    }

    #[test]
    fn test_index2_invalid() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("random");

        // Feeding it invalid data should not panic
        Index2File::from_existing(d.to_str().unwrap());
    }
}