wow-mpq 0.6.2

High-performance parser for World of Warcraft MPQ archives with parallel processing support
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
//! MPQ test archive creation utilities
//!
//! Replaces the functionality of mpq_tools.py

use crate::{ArchiveBuilder, FormatVersion, compression};
use rand::{Rng, SeedableRng, rngs::StdRng};
use std::fs;
use std::path::{Path, PathBuf};

/// Configuration for creating test MPQ archives
#[derive(Debug, Clone)]
pub struct TestArchiveConfig {
    /// Name of the archive (used for filename)
    pub name: String,
    /// MPQ format version to use
    pub version: FormatVersion,
    /// List of files to include in the archive
    pub files: Vec<TestFile>,
    /// Hash table size (if None, automatically determined)
    pub hash_table_size: Option<u32>,
    /// Block size shift value (sector size = 512 << block_size)
    pub block_size: Option<u8>,
    /// Whether to manually include a (listfile) entry
    pub include_listfile: bool,
    /// Whether to include an (attributes) file
    pub include_attributes: bool,
}

/// A file to include in the test archive
#[derive(Debug, Clone)]
pub struct TestFile {
    /// Path/name of the file within the archive
    pub name: String,
    /// File content data
    pub data: Vec<u8>,
    /// Compression method flags (None for no compression)
    pub compression: Option<u8>,
    /// Whether the file should be encrypted
    pub encrypted: bool,
    /// Whether to use FIX_KEY encryption mode
    pub fix_key: bool,
}

/// Type of test archive to create
#[derive(Debug, Clone, Copy)]
pub enum TestArchiveType {
    /// Minimal archive with single file
    Minimal,
    /// Archive with compressed files
    Compressed,
    /// Archive with encrypted files
    Encrypted,
    /// Archive with various edge cases
    EdgeCases,
    /// Comprehensive test archive
    Comprehensive,
    /// Archive with CRC verification
    WithCrc,
}

impl TestArchiveConfig {
    /// Create a minimal test archive configuration
    pub fn minimal(version: FormatVersion) -> Self {
        Self {
            name: format!("minimal_v{}", version as u8 + 1),
            version,
            files: vec![TestFile {
                name: "test.txt".to_string(),
                data: b"Hello, MPQ!".to_vec(),
                compression: None,
                encrypted: false,
                fix_key: false,
            }],
            hash_table_size: Some(16),
            block_size: Some(3),
            include_listfile: version == FormatVersion::V1,
            include_attributes: false,
        }
    }

    /// Create a compressed files test archive
    pub fn compressed(compression_type: &str) -> Self {
        let data = generate_compressible_data(50 * 1024); // 50KB

        let compression_flag = match compression_type {
            "zlib" => Some(compression::flags::ZLIB),
            "bzip2" => Some(compression::flags::BZIP2),
            "lzma" => Some(compression::flags::LZMA),
            "sparse" => Some(compression::flags::SPARSE),
            _ => None,
        };

        Self {
            name: format!("compressed_{compression_type}"),
            version: FormatVersion::V2,
            files: vec![
                TestFile {
                    name: "compressed.dat".to_string(),
                    data: data.clone(),
                    compression: compression_flag,
                    encrypted: false,
                    fix_key: false,
                },
                TestFile {
                    name: "uncompressed.dat".to_string(),
                    data: data[..1024].to_vec(),
                    compression: None,
                    encrypted: false,
                    fix_key: false,
                },
            ],
            hash_table_size: Some(32),
            block_size: Some(4),
            include_listfile: false,
            include_attributes: false,
        }
    }

    /// Create an encrypted files test archive
    pub fn encrypted() -> Self {
        Self {
            name: "encrypted".to_string(),
            version: FormatVersion::V2,
            files: vec![
                TestFile {
                    name: "secret.dat".to_string(),
                    data: b"This is encrypted data!".to_vec(),
                    compression: Some(compression::flags::ZLIB),
                    encrypted: true,
                    fix_key: false,
                },
                TestFile {
                    name: "fixed_key.dat".to_string(),
                    data: b"This uses fix key encryption!".to_vec(),
                    compression: None,
                    encrypted: true,
                    fix_key: true,
                },
            ],
            hash_table_size: Some(16),
            block_size: Some(3),
            include_listfile: false,
            include_attributes: false,
        }
    }

    /// Create an edge cases test archive
    pub fn edge_cases() -> Self {
        Self {
            name: "edge_cases".to_string(),
            version: FormatVersion::V2,
            files: vec![
                // Empty file
                TestFile {
                    name: "empty.txt".to_string(),
                    data: vec![],
                    compression: None,
                    encrypted: false,
                    fix_key: false,
                },
                // Single byte file
                TestFile {
                    name: "single_byte.dat".to_string(),
                    data: vec![0x42],
                    compression: Some(compression::flags::ZLIB),
                    encrypted: false,
                    fix_key: false,
                },
                // File with spaces in name
                TestFile {
                    name: "file with spaces.txt".to_string(),
                    data: b"Spaces in filename!".to_vec(),
                    compression: None,
                    encrypted: false,
                    fix_key: false,
                },
                // File with path
                TestFile {
                    name: "folder/subfolder/nested.dat".to_string(),
                    data: b"Nested file".to_vec(),
                    compression: None,
                    encrypted: false,
                    fix_key: false,
                },
                // Large uncompressible file
                TestFile {
                    name: "random.bin".to_string(),
                    data: generate_random_data(100 * 1024), // 100KB
                    compression: Some(compression::flags::ZLIB),
                    encrypted: false,
                    fix_key: false,
                },
            ],
            hash_table_size: Some(64),
            block_size: Some(5),
            include_listfile: true,
            include_attributes: false,
        }
    }

    /// Create a comprehensive test archive
    pub fn comprehensive(version: FormatVersion) -> Self {
        let mut files = vec![
            TestFile {
                name: "readme.txt".to_string(),
                data: b"MPQ Archive Test Suite\n\nThis archive contains various test files."
                    .to_vec(),
                compression: None,
                encrypted: false,
                fix_key: false,
            },
            TestFile {
                name: "data/config.ini".to_string(),
                data: b"[Settings]\nversion=1.0\ntest=true".to_vec(),
                compression: Some(compression::flags::ZLIB),
                encrypted: false,
                fix_key: false,
            },
            TestFile {
                name: "data/binary.dat".to_string(),
                data: generate_binary_pattern(10 * 1024),
                compression: Some(compression::flags::BZIP2),
                encrypted: false,
                fix_key: false,
            },
            TestFile {
                name: "secure/encrypted.bin".to_string(),
                data: b"Secret data".to_vec(),
                compression: None,
                encrypted: true,
                fix_key: false,
            },
        ];

        // Add version-specific features
        if version >= FormatVersion::V2 {
            files.push(TestFile {
                name: "large/bigfile.dat".to_string(),
                data: generate_compressible_data(1024 * 1024), // 1MB
                compression: Some(compression::flags::LZMA),
                encrypted: false,
                fix_key: false,
            });
        }

        Self {
            name: format!("comprehensive_v{}", version as u8 + 1),
            version,
            files,
            hash_table_size: Some(128),
            block_size: Some(7), // 64KB sectors
            include_listfile: true,
            include_attributes: version >= FormatVersion::V2,
        }
    }

    /// Create test archive with CRC verification
    pub fn with_crc() -> Self {
        Self {
            name: "crc_test".to_string(),
            version: FormatVersion::V2,
            files: vec![TestFile {
                name: "crc_protected.dat".to_string(),
                data: b"This file has CRC protection".to_vec(),
                compression: Some(compression::flags::ZLIB),
                encrypted: false,
                fix_key: false,
            }],
            hash_table_size: Some(16),
            block_size: Some(3),
            include_listfile: false,
            include_attributes: false,
        }
    }
}

/// Create a test MPQ archive
pub fn create_test_archive(
    output_path: &Path,
    config: &TestArchiveConfig,
) -> Result<PathBuf, crate::Error> {
    let mut builder = if config.include_listfile {
        // If we're manually including a listfile, don't auto-generate
        ArchiveBuilder::new().listfile_option(crate::ListfileOption::None)
    } else {
        // Otherwise, auto-generate
        ArchiveBuilder::new().listfile_option(crate::ListfileOption::Generate)
    };

    // Set version
    builder = builder.version(config.version);

    // Set block size if specified
    if let Some(block_size) = config.block_size {
        builder = builder.block_size(block_size.into());
    }

    // Note: hash_table_size is automatically determined by the builder

    // Add files
    for file in &config.files {
        if file.encrypted {
            builder = builder.add_file_data_with_encryption(
                file.data.clone(),
                &file.name,
                file.compression.unwrap_or(0),
                file.fix_key,
                0, // locale
            );
        } else if let Some(compression) = file.compression {
            builder = builder.add_file_data_with_options(
                file.data.clone(),
                &file.name,
                compression,
                false, // encrypt
                0,     // locale
            );
        } else {
            builder = builder.add_file_data(file.data.clone(), &file.name);
        }
    }

    // Add (listfile) if requested
    if config.include_listfile {
        let listfile_content = config
            .files
            .iter()
            .map(|f| f.name.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        builder = builder.add_file_data(listfile_content.into_bytes(), "(listfile)");
    }

    // Add (attributes) if requested
    if config.include_attributes {
        let attributes = generate_attributes(&config.files);
        builder = builder.add_file_data(attributes, "(attributes)");
    }

    // Build the archive
    let archive_path = output_path.join(&config.name).with_extension("mpq");
    builder.build(&archive_path)?;

    Ok(archive_path)
}

/// Generate compressible test data
fn generate_compressible_data(size: usize) -> Vec<u8> {
    let pattern = b"This is test data that should compress well because it has repeated patterns. ";
    let mut data = Vec::with_capacity(size);

    while data.len() < size {
        let remaining = size - data.len();
        let to_copy = remaining.min(pattern.len());
        data.extend_from_slice(&pattern[..to_copy]);
    }

    data
}

/// Generate random uncompressible data
fn generate_random_data(size: usize) -> Vec<u8> {
    let mut rng = StdRng::seed_from_u64(42);
    let mut data = vec![0u8; size];
    rng.fill(&mut data[..]);
    data
}

/// Generate binary pattern data
fn generate_binary_pattern(size: usize) -> Vec<u8> {
    let mut data = Vec::with_capacity(size);
    let mut value = 0u8;

    while data.len() < size {
        data.push(value);
        value = value.wrapping_add(1);
    }

    data
}

/// Generate attributes file content
fn generate_attributes(files: &[TestFile]) -> Vec<u8> {
    // Simple attributes format: CRC32 and timestamps
    let mut attributes = Vec::new();

    // Version
    attributes.extend_from_slice(&100u32.to_le_bytes());

    // Flags (CRC32 + TIMESTAMP)
    attributes.extend_from_slice(&0x03u32.to_le_bytes());

    // For each file: CRC32 and timestamp
    for file in files {
        // CRC32 (simplified - just use data length as fake CRC)
        attributes.extend_from_slice(&(file.data.len() as u32).to_le_bytes());
        // Timestamp (fake)
        attributes.extend_from_slice(&0x5F000000u32.to_le_bytes());
    }

    attributes
}

/// Create all test archive types
pub fn create_all_test_archives(output_dir: &Path) -> Result<Vec<PathBuf>, crate::Error> {
    fs::create_dir_all(output_dir)?;
    let mut created = Vec::new();

    // Create minimal archives for each version
    for version in [
        FormatVersion::V1,
        FormatVersion::V2,
        FormatVersion::V3,
        FormatVersion::V4,
    ] {
        let config = TestArchiveConfig::minimal(version);
        let path = create_test_archive(output_dir, &config)?;
        created.push(path);
    }

    // Create compressed archives
    for compression in ["zlib", "bzip2", "lzma", "sparse"] {
        let config = TestArchiveConfig::compressed(compression);
        let path = create_test_archive(output_dir, &config)?;
        created.push(path);
    }

    // Create other test types
    let configs = vec![
        TestArchiveConfig::encrypted(),
        TestArchiveConfig::edge_cases(),
        TestArchiveConfig::comprehensive(FormatVersion::V2),
        TestArchiveConfig::comprehensive(FormatVersion::V4),
        TestArchiveConfig::with_crc(),
    ];

    for config in configs {
        let path = create_test_archive(output_dir, &config)?;
        created.push(path);
    }

    Ok(created)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_minimal_archive_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config = TestArchiveConfig::minimal(FormatVersion::V1);
        let result = create_test_archive(temp_dir.path(), &config).unwrap();

        assert!(result.exists());
        assert!(
            result
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .contains("minimal")
        );
    }

    #[test]
    fn test_compressed_archive_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config = TestArchiveConfig::compressed("zlib");
        let result = create_test_archive(temp_dir.path(), &config).unwrap();

        assert!(result.exists());
    }
}