rpfm_lib/files/mod.rs
1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! This module contains the definition of RFile, the file abstraction used by this lib to decode/encode files.
12//!
13//! There is an additional type: [`Unknown`]. This type is used as a wildcard,
14//! so you can get the raw data of any non-supported file type and manipulate it yourself in a safe way.
15//!
16//! For more information about specific file types, including their binary format spec, please
17//! **check their respective documentation**.
18//!
19//! # Core Abstractions
20//!
21//! ## RFile
22//!
23//! The [`RFile`] struct is the central abstraction for all files in rpfm_lib. It can represent:
24//! - Files within PackFiles (or any [`Container`])
25//! - Files on the filesystem
26//! - Files in memory only
27//!
28//! Key features:
29//! - **Lazy Loading**: Files can be loaded on-demand to reduce memory usage
30//! - **Type Detection**: Automatically identifies file types based on path and content
31//! - **Caching**: Supports caching decoded data or raw bytes
32//! - **Metadata**: Tracks path, timestamp, container name, and file type
33//!
34//! ## File States
35//!
36//! Files can be in one of three internal states:
37//! - **OnDisk**: Data not yet loaded (lazy loading)
38//! - **Cached**: Raw bytes loaded but not decoded
39//! - **Decoded**: Fully parsed into a type-specific structure
40//!
41//! ## Decoding/Encoding
42//!
43//! All file types implement the [`Decodeable`] and [`Encodeable`] traits:
44//! - **Decodeable**: Parse binary data into structured format
45//! - **Encodeable**: Serialize structured format back to binary
46//!
47//! Extra data can be passed via [`DecodeableExtraData`] and [`EncodeableExtraData`]
48//! to provide context like schemas, game info, or file names.
49//!
50//! # Known file types
51//!
52//! | File Type | Decoding Supported | Encoding Supported |
53//! | ---------------------- | ------------------ | ------------------ |
54//! | [`Anim`] | Limited | Limited |
55//! | [`AssetVariationDb`] | Yes | Yes |
56//! | [`AnimFragmentBattle`] | Limited | Limited |
57//! | [`AnimPack`] | Yes | Yes |
58//! | [`AnimsTable`] | Yes | Yes |
59//! | [`Atlas`] | Yes | Yes |
60//! | [`Audio`] | No | No |
61//! | [`BMD`] | Limited | Limited |
62//! | [`BMD_Vegetation`] | Limited | Limited |
63//! | [`CS2_Collision`] | Limited | Limited |
64//! | [`CS2_Parsed`] | Limited | Limited |
65//! | [`Dat`] | Limited | Limited |
66//! | [`DB`] | Yes | Yes |
67//! | [`ESF`] | Limited | Limited |
68//! | [`FastBinLists`] | Yes | Yes |
69//! | [`Font`] | Limited | Limited |
70//! | [`Fxc`] | Yes | Yes |
71//! | [`GroupFormations`] | Limited | Limited |
72//! | [`HLSL_Compiled`] | Limited | Limited |
73//! | [`Image`] | Limited | Limited |
74//! | [`Loc`] | Yes | Yes |
75//! | [`MatchedCombat`] | Yes | Yes |
76//! | [`Pack`] | Yes | Yes |
77//! | [`PortraitSettings`] | Yes | Yes |
78//! | [`RigidModel`] | No | No |
79//! | [`SoundBank`] | No | No |
80//! | SoundBankDatabase | Limited | Limited |
81//! | SoundEvents | Limited | Limited |
82//! | [`Text`] | Yes | Yes |
83//! | [`TileDatabase`] | Yes | Yes |
84//! | [`TradeRoutes`] | Yes | Yes |
85//! | [`UIC`] | No | No |
86//! | [`UnitVariant`] | Yes | Yes |
87//! | [`Video`] | Yes | Yes |
88//! | VMD | Yes | Yes |
89//! | WSModel | Yes | Yes |
90//!
91//! # Example Usage
92//!
93//! ```ignore
94//! use rpfm_lib::files::{RFile, Decodeable, db::DB, DecodeableExtraData, table::Table};
95//! use rpfm_lib::schema::Schema;
96//! use std::path::Path;
97//!
98//! // Load a DB table from disk
99//! let schema = Schema::load(Path::new("path/to/schema.ron"), None).unwrap();
100//! let mut extra = DecodeableExtraData::default();
101//! extra.set_schema(Some(&schema));
102//! extra.set_table_name(Some("units_tables"));
103//!
104//! let rfile = RFile::from_disk(Path::new("units"), &extra).unwrap();
105//!
106//! // Access the decoded data
107//! if let Some(db) = rfile.decoded().and_then(|d| d.db()) {
108//! println!("Table has {} rows", db.table().len());
109//! }
110//! ```
111//!
112//! [`Anim`]: crate::files::anim::Anim
113//! [`AnimFragmentBattle`]: crate::files::anim_fragment_battle::AnimFragmentBattle
114//! [`AnimPack`]: crate::files::animpack::AnimPack
115//! [`AnimsTable`]: crate::files::anims_table::AnimsTable
116//! [`Atlas`]: crate::files::atlas::Atlas
117//! [`Audio`]: crate::files::audio::Audio
118//! [`BMD`]: crate::files::bmd::Bmd
119//! [`BMD_Vegetation`]: crate::files::bmd_vegetation::BmdVegetation
120//! [`CS2_Collision`]: crate::files::cs2_collision::Cs2Collision
121//! [`CS2_Parsed`]: crate::files::cs2_parsed::Cs2Parsed
122//! [`Dat`]: crate::files::dat::Dat
123//! [`DB`]: crate::files::db::DB
124//! [`ESF`]: crate::files::esf::ESF
125//! [`AssetVariationDb`]: crate::files::asset_variation_db::AssetVariationDb
126//! [`FastBinLists`]: crate::files::fastbin_lists
127//! [`Font`]: crate::files::font::Font
128//! [`Fxc`]: crate::files::fxc::Fxc
129//! [`GroupFormations`]: crate::files::group_formations::GroupFormations
130//! [`HLSL_Compiled`]: crate::files::hlsl_compiled::HlslCompiled
131//! [`Image`]: crate::files::image::Image
132//! [`Loc`]: crate::files::loc::Loc
133//! [`MatchedCombat`]: crate::files::matched_combat::MatchedCombat
134//! [`Pack`]: crate::files::pack::Pack
135//! [`PortraitSettings`]: crate::files::portrait_settings::PortraitSettings
136//! [`RigidModel`]: crate::files::rigidmodel::RigidModel
137//! [`SoundBank`]: crate::files::sound_bank::SoundBank
138//! [`SoundEvents`]: crate::files::sound_events::SoundEvents
139//! [`Text`]: crate::files::text::Text
140//! [`TileDatabase`]: crate::files::tile_database::TileDatabase
141//! [`TradeRoutes`]: crate::files::trade_routes::TradeRoutes
142//! [`UIC`]: crate::files::uic::UIC
143//! [`UnitVariant`]: crate::files::unit_variant::UnitVariant
144//! [`Unknown`]: crate::files::unknown::Unknown
145//! [`Video`]: crate::files::video::Video
146
147// File decoders intentionally use the `let mut x = T::default(); x.field = …;` pattern
148// to make debugging them easier.
149#![allow(clippy::field_reassign_with_default)]
150
151use crc_fast::{checksum, CrcAlgorithm};
152use csv::{QuoteStyle, ReaderBuilder, WriterBuilder};
153use getset::*;
154use log::warn;
155use rayon::prelude::*;
156use serde_derive::{Serialize, Deserialize};
157
158use std::cmp::Ordering;
159use std::collections::{HashMap, HashSet};
160use std::{fmt, fmt::{Debug, Display}};
161use std::fs::{DirBuilder, File};
162use std::io::{BufReader, Cursor, Read, Seek, SeekFrom, BufWriter, Write};
163use std::path::{Path, PathBuf};
164
165use crate::binary::{ReadBytes, WriteBytes};
166use crate::compression::{CompressionFormat, Decompressible};
167use crate::encryption::Decryptable;
168use crate::error::{Result, RLibError};
169use crate::games::{GameInfo, pfh_version::PFHVersion, supported_games::*};
170use crate::{REGEX_CEO_DB, REGEX_DB, REGEX_PORTRAIT_SETTINGS};
171use crate::schema::{Schema, Definition};
172use crate::utils::*;
173
174#[cfg(feature = "format_anim")] use self::anim::Anim;
175#[cfg(feature = "format_anim_fragment_battle")] use self::anim_fragment_battle::AnimFragmentBattle;
176#[cfg(feature = "format_animpack")] use self::animpack::AnimPack;
177#[cfg(feature = "format_anims_table")] use self::anims_table::AnimsTable;
178#[cfg(feature = "format_atlas")] use self::atlas::Atlas;
179#[cfg(feature = "format_audio")] use self::audio::Audio;
180use self::bmd::Bmd;
181use self::bmd_vegetation::BmdVegetation;
182#[cfg(feature = "format_dat")] use self::dat::Dat;
183use self::db::DB;
184use self::esf::ESF;
185#[cfg(feature = "format_font")] use self::font::Font;
186#[cfg(feature = "format_group_formations")] use self::group_formations::GroupFormations;
187#[cfg(feature = "format_hlsl_compiled")] use self::hlsl_compiled::HlslCompiled;
188#[cfg(feature = "format_image")] use self::image::Image;
189use self::loc::Loc;
190#[cfg(feature = "format_matched_combat")] use self::matched_combat::MatchedCombat;
191use self::pack::{Pack, RESERVED_NAME_SETTINGS, RESERVED_NAME_NOTES, RESERVED_NAME_DEPENDENCIES_MANAGER, RESERVED_NAME_DEPENDENCIES_MANAGER_V2};
192#[cfg(feature = "format_portrait_settings")] use self::portrait_settings::PortraitSettings;
193use self::rigidmodel::RigidModel;
194#[cfg(feature = "format_sound_bank")] use self::sound_bank::SoundBank;
195use self::text::Text;
196#[cfg(feature = "format_trade_routes")] use self::trade_routes::TradeRoutes;
197#[cfg(feature = "format_uic")] use self::uic::UIC;
198#[cfg(feature = "format_unit_variant")] use self::unit_variant::UnitVariant;
199use self::unknown::Unknown;
200use self::video::Video;
201
202#[cfg(feature = "format_anim")] pub mod anim;
203#[cfg(feature = "format_anim_fragment_battle")] pub mod anim_fragment_battle;
204#[cfg(feature = "format_animpack")] pub mod animpack;
205#[cfg(feature = "format_anims_table")] pub mod anims_table;
206pub mod asset_variation_db;
207#[cfg(feature = "format_atlas")] pub mod atlas;
208#[cfg(feature = "format_audio")] pub mod audio;
209#[allow(dead_code)]pub mod bmd;
210#[allow(dead_code)]pub mod bmd_vegetation;
211pub mod cs2_collision;
212pub mod cs2_parsed;
213#[cfg(feature = "format_dat")] pub mod dat;
214pub mod db;
215mod detection;
216#[allow(dead_code)]pub mod esf;
217pub mod fastbin_lists;
218#[cfg(feature = "format_font")] pub mod font;
219pub mod fxc;
220#[cfg(feature = "format_group_formations")] pub mod group_formations;
221#[cfg(feature = "format_hlsl_compiled")] pub mod hlsl_compiled;
222#[cfg(feature = "format_image")] pub mod image;
223pub mod loc;
224#[cfg(feature = "format_matched_combat")] pub mod matched_combat;
225pub mod pack;
226#[cfg(feature = "format_portrait_settings")] pub mod portrait_settings;
227pub mod rigidmodel;
228#[cfg(feature = "format_sound_bank")] #[allow(dead_code)]pub mod sound_bank;
229#[cfg(feature = "format_sound_bank_database")] pub mod sound_bank_database;
230#[cfg(feature = "format_sound_events")] pub mod sound_events;
231pub mod table;
232pub mod text;
233pub mod tile_database;
234#[cfg(feature = "format_trade_routes")] pub mod trade_routes;
235#[cfg(feature = "format_uic")] pub mod uic;
236#[cfg(feature = "format_unit_variant")] pub mod unit_variant;
237pub mod unknown;
238pub mod video;
239
240#[cfg(test)] mod rfile_test;
241
242//---------------------------------------------------------------------------//
243// Enum & Structs
244//---------------------------------------------------------------------------//
245
246/// Central file abstraction for rpfm_lib.
247///
248/// Represents a file that can exist in multiple locations and states:
249/// - Inside a PackFile or other container
250/// - On the filesystem
251/// - In memory only
252///
253/// # Lazy Loading
254///
255/// RFile supports lazy loading to minimize memory usage. Files can remain on disk
256/// until their data is actually needed, at which point they're loaded into memory
257/// automatically.
258///
259/// # File States
260///
261/// Internally, RFile can be in three states:
262/// - **OnDisk**: Metadata loaded, data still on disk (minimal memory)
263/// - **Cached**: Raw bytes loaded, not yet decoded
264/// - **Decoded**: Fully parsed into type-specific structure
265///
266/// # Type Detection
267///
268/// File types are detected based on:
269/// - File extension and path patterns
270/// - Magic numbers and header bytes
271/// - Container metadata
272///
273/// # Metadata
274///
275/// Each RFile tracks:
276/// - **path**: Location within container or filesystem (may be empty for memory-only files)
277/// - **timestamp**: Last modified time (optional)
278/// - **file_type**: Detected or specified file type
279/// - **container_name**: Source container name if from a container
280///
281/// # Example
282///
283/// ```ignore
284/// use rpfm_lib::files::{RFile, FileType};
285/// use std::path::Path;
286///
287/// // Load a file from disk
288/// let rfile = RFile::from_disk(Path::new("units.loc"), &None).unwrap();
289///
290/// // Check file type
291/// assert_eq!(*rfile.file_type(), FileType::Loc);
292///
293/// // Decode the file
294/// let decoded = rfile.decode(&None, false, false).unwrap();
295/// ```
296#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
297pub struct RFile {
298
299 /// Path of the file within a container or filesystem.
300 ///
301 /// Empty string for memory-only files.
302 path: String,
303
304 /// Last modified timestamp (Unix epoch).
305 timestamp: Option<u64>,
306
307 /// Detected or specified file type.
308 file_type: FileType,
309
310 /// Name of the source container, if applicable.
311 container_name: Option<String>,
312
313 /// Internal data storage (OnDisk, Cached, or Decoded).
314 ///
315 /// Use RFile methods instead of accessing directly.
316 data: RFileInnerData,
317}
318
319/// Internal data storage states for RFile.
320///
321/// Represents the three possible states of file data in memory:
322/// - **Decoded**: Fully parsed into structured format (highest memory, fastest access)
323/// - **Cached**: Raw bytes in memory (medium memory, requires decoding)
324/// - **OnDisk**: Metadata only, data on disk (lowest memory, requires loading + decoding)
325///
326/// This enum is internal and should not be used directly. Use RFile's public methods instead.
327///
328/// # State Transitions
329///
330/// ```text
331/// OnDisk → load() → Cached → decode() → Decoded
332/// ↑ ↓
333/// └───── encode() ──────┘
334/// ```
335#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
336enum RFileInnerData {
337
338 /// File data loaded and decoded into type-specific structure.
339 ///
340 /// Ready for immediate use. Highest memory usage.
341 Decoded(Box<RFileDecoded>),
342
343 /// Raw bytes loaded into memory but not decoded.
344 ///
345 /// Requires decoding before use. Medium memory usage.
346 Cached(Vec<u8>),
347
348 /// File data still on disk, only metadata in memory.
349 ///
350 /// Requires loading and decoding before use. Lowest memory usage.
351 OnDisk(OnDisk)
352}
353
354/// This struct represents a file on disk, which data has not been loaded to memory yet.
355///
356/// This may be a file directly on disk, or one inside another file (like inside a [Container]).
357///
358/// This is internal only. Users should not use it directly.
359#[derive(Clone, Debug, PartialEq, Getters, Serialize, Deserialize)]
360struct OnDisk {
361
362 /// Path of the file on disk where the data is.
363 ///
364 /// This may be a singular file or a file containing it
365 path: String,
366
367 /// Last modified date of the file that contains the data.
368 ///
369 /// This is used to both, get the last modified data into the file's metadata
370 /// and to check if the file has been manipulated since we created the OnDisk of it.
371 timestamp: u64,
372
373 /// Offset of the start of the file's data.
374 ///
375 /// `0` if the whole file is the data we want.
376 start: u64,
377
378 /// Size in bytes of the file's data.
379 size: u64,
380
381 /// Is the data compressed?.
382 is_compressed: bool,
383
384 /// If the data is compressed with [`CompressionFormat::Lz4Block`], its uncompressed size.
385 ///
386 /// That format cannot be auto-detected, so this is how we know the data uses it.
387 #[serde(default)]
388 lz4_block_uncompressed_size: Option<u64>,
389
390 /// Is the data encrypted? And if so, with which format?.
391 is_encrypted: Option<PFHVersion>,
392}
393
394/// This enum allow us to store any kind of decoded file type on a common place.
395#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
396pub enum RFileDecoded {
397 #[cfg(feature = "format_anim")] Anim(Anim),
398 #[cfg(feature = "format_anim_fragment_battle")] AnimFragmentBattle(AnimFragmentBattle),
399 #[cfg(feature = "format_animpack")] AnimPack(AnimPack),
400 #[cfg(feature = "format_anims_table")] AnimsTable(AnimsTable),
401 #[cfg(feature = "format_atlas")] Atlas(Atlas),
402 #[cfg(feature = "format_audio")] Audio(Audio),
403 BMD(Box<Bmd>),
404 BMDVegetation(BmdVegetation),
405 #[cfg(feature = "format_dat")] Dat(Dat),
406 DB(DB),
407 ESF(ESF),
408 #[cfg(feature = "format_font")] Font(Font),
409 #[cfg(feature = "format_group_formations")] GroupFormations(GroupFormations),
410 #[cfg(feature = "format_hlsl_compiled")] HlslCompiled(HlslCompiled),
411 #[cfg(feature = "format_image")] Image(Image),
412 Loc(Loc),
413 #[cfg(feature = "format_matched_combat")] MatchedCombat(MatchedCombat),
414 Pack(Pack),
415 #[cfg(feature = "format_portrait_settings")] PortraitSettings(PortraitSettings),
416 RigidModel(RigidModel),
417 #[cfg(feature = "format_sound_bank")] SoundBank(SoundBank),
418 Text(Text),
419 #[cfg(feature = "format_trade_routes")] TradeRoutes(TradeRoutes),
420 #[cfg(feature = "format_uic")] UIC(UIC),
421 #[cfg(feature = "format_unit_variant")] UnitVariant(UnitVariant),
422 Unknown(Unknown),
423 Video(Video),
424 VMD(Text),
425 WSModel(Text),
426}
427
428/// Known file types in Total War games.
429///
430/// Categorizes files by their format and purpose. Each variant corresponds to a dedicated
431/// submodule that implements parsing and encoding for that file type.
432///
433/// # Type Detection
434///
435/// File types are determined by:
436/// - **Extension matching**: Primary method for most file types
437/// - **Path patterns**: For files with special naming (e.g., DB tables)
438/// - **Magic numbers**: For format disambiguation when needed
439///
440/// # Support Levels
441///
442/// - **Full**: Complete decoding and encoding support
443/// - **Partial**: Read support with limitations
444/// - **Passthrough**: Raw data only (use [`Unknown`] for custom handling)
445///
446/// See the module-level documentation for a complete support matrix.
447///
448/// # Unknown Type
449///
450/// [`FileType::Unknown`] is the default fallback for unrecognized files. These files
451/// can still be read and written using the [`Unknown`] file type, which provides
452/// access to raw bytes.
453#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
454pub enum FileType {
455 Anim,
456 AnimFragmentBattle,
457 AnimPack,
458 AnimsTable,
459 Atlas,
460 Audio,
461 BMD,
462 BMDVegetation,
463 Dat,
464 DB,
465 ESF,
466 Font,
467 GroupFormations,
468 HlslCompiled,
469 Image,
470 Loc,
471 MatchedCombat,
472 Pack,
473 PortraitSettings,
474 RigidModel,
475 SoundBank,
476 Text,
477 TradeRoutes,
478 UIC,
479 UnitVariant,
480 Video,
481 VMD,
482 WSModel,
483
484 #[default]
485 Unknown,
486}
487
488/// This enum represents a ***Path*** inside a [Container].
489#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
490pub enum ContainerPath {
491
492 /// This variant represents the path of a single file.
493 File(String),
494
495 /// This variant represents the path of a single folder.
496 ///
497 /// If this is empty, it represents the root of the container.
498 Folder(String),
499}
500
501/// Additional context data for [`Decodeable::decode()`] operations.
502///
503/// This structure provides optional configuration and metadata that decoders may need
504/// to properly interpret binary data. Different file types use different subsets of
505/// these fields.
506///
507/// # Field Categories
508///
509/// - **Configuration toggles**: Control decoder behavior (lazy loading, encryption status, etc.)
510/// - **OnDisk-related data**: File location and timestamp information
511/// - **Table-related data**: Database table-specific context
512/// - **Image-related data**: Image format detection flags
513/// - **General-purpose data**: Game info, file names, sizes
514///
515/// # Usage
516///
517/// ```ignore
518/// use rpfm_lib::files::DecodeableExtraData;
519///
520/// // For decoding a DB table
521/// let extra_data = DecodeableExtraData::default()
522/// .set_schema(Some(&schema))
523/// .set_game_info(Some(&game_info))
524/// .set_table_name(Some("units_tables"))
525/// .set_return_incomplete(true);
526/// ```
527///
528/// # Required Fields by Type
529///
530/// - **DB Tables**: Require `schema` and optionally `table_name` for fragments
531/// - **Containers (PackFiles)**: Use `lazy_load`, `disk_file_path`, `disk_file_offset`
532/// - **Images**: Use `is_dds` to enable DDS-specific decoding
533/// - **Generic files**: May use `game_info`, `file_name`, `data_size`
534///
535/// For specific requirements, consult each file type's documentation.
536#[derive(Clone, Debug, Default, Getters, Setters)]
537#[getset(get = "pub", set = "pub")]
538pub struct DecodeableExtraData<'a> {
539
540 //-----------------------//
541 // Configuration toggles //
542 //-----------------------//
543
544 /// Enable lazy loading for container files.
545 ///
546 /// When `true`, [`Container`] implementors will defer loading file data until accessed,
547 /// storing only metadata initially. This reduces memory usage for large containers.
548 lazy_load: bool,
549
550 /// Indicates whether the source data was encrypted.
551 ///
552 /// This is informational only - data reaching decode functions should already be decrypted.
553 /// Used for metadata tracking and logging.
554 is_encrypted: bool,
555
556 /// Allow returning partial data on decode errors (DB tables only).
557 ///
558 /// When `true`, table decoders will return successfully decoded rows even if later
559 /// rows fail to decode. When `false`, any decode error fails the entire operation.
560 return_incomplete: bool,
561
562 /// Schema definition for decoding DB tables and Loc files.
563 ///
564 /// Required for decoding database tables, as the schema defines the table structure,
565 /// column types, and versioning information.
566 schema: Option<&'a Schema>,
567
568 //----------------------------//
569 // OnDisk-related config data //
570 //----------------------------//
571
572 /// Absolute path to the file on disk.
573 ///
574 /// Used by lazy-loading containers to know where to read data from when needed.
575 /// Should be `None` for in-memory data.
576 disk_file_path: Option<&'a str>,
577
578 /// Byte offset within the disk file where this file's data begins.
579 ///
580 /// Used for files embedded within larger containers (e.g., individual files in a PackFile).
581 /// Set to `0` for standalone files.
582 disk_file_offset: u64,
583
584 /// File modification timestamp (Unix epoch seconds).
585 ///
586 /// Preserved from the original file for metadata tracking.
587 timestamp: u64,
588
589 //----------------------------//
590 // Table-related config data //
591 //----------------------------//
592
593 /// Name of the table (without extension or path).
594 ///
595 /// Used when decoding table fragments that don't have the full path context.
596 /// For example, when decoding a table from a loose file or unnamed buffer.
597 table_name: Option<&'a str>,
598
599 //----------------------------//
600 // Image-Related config data //
601 //----------------------------//
602
603 /// Flag indicating the image is in DDS (DirectDraw Surface) format.
604 ///
605 /// When `true`, enables DDS-specific decoding and conversion to PNG for display.
606 is_dds: bool,
607
608 //------------------------------//
609 // General-purpose config data //
610 //------------------------------//
611
612 /// Complete game information context.
613 ///
614 /// Provides game-specific settings, version info, and feature flags that may
615 /// affect decoding behavior (e.g., format variations between game versions).
616 game_info: Option<&'a GameInfo>,
617
618 /// Original filename (with extension).
619 ///
620 /// Used for file type detection, logging, and error messages.
621 file_name: Option<&'a str>,
622
623 /// Total size of the file data in bytes.
624 ///
625 /// May differ from buffer size if dealing with partial data or compressed streams.
626 data_size: u64,
627
628 /// Skip automatic path cache generation for containers.
629 ///
630 /// When `true`, container decoders won't build the lowercase path cache automatically.
631 /// You must manually call [`Container::paths_cache_generate()`] after decoding or
632 /// case-insensitive lookups will fail.
633 ///
634 /// This is an optimization for bulk operations where you'll rebuild the cache once
635 /// at the end instead of incrementally.
636 skip_path_cache_generation: bool,
637}
638
639/// Additional context data for [`Encodeable::encode()`] operations.
640///
641/// This structure provides optional configuration and metadata that encoders may need
642/// to properly serialize structured data to binary format. Different file types use
643/// different subsets of these fields.
644///
645/// # Field Categories
646///
647/// - **Configuration toggles**: Control encoder behavior (test mode, date handling, GUIDs)
648/// - **Optional config data**: Game info, compression settings
649///
650/// # Usage
651///
652/// ```ignore
653/// use rpfm_lib::files::EncodeableExtraData;
654/// use rpfm_lib::compression::CompressionFormat;
655///
656/// // For encoding a DB table with GUID
657/// let extra_data = EncodeableExtraData::default()
658/// .set_game_info(Some(&game_info))
659/// .set_table_has_guid(true)
660/// .set_regenerate_table_guid(true);
661///
662/// // For encoding with compression
663/// let extra_data = EncodeableExtraData::default()
664/// .set_compression_format(CompressionFormat::Lz4)
665/// .set_game_info(Some(&game_info));
666/// ```
667///
668/// # Common Configurations
669///
670/// - **DB Tables**: Use `table_has_guid` and `regenerate_table_guid` to control GUID handling
671/// - **Containers (PackFiles)**: Use `compression_format` to enable compression
672/// - **Testing**: Use `test_mode` and `nullify_dates` for deterministic output
673/// - **ESF Files**: Use `disable_compression` for nested encoding
674///
675/// For specific requirements, consult each file type's documentation.
676#[derive(Clone, Default, Getters, Setters)]
677#[getset(get = "pub", set = "pub")]
678pub struct EncodeableExtraData<'a> {
679
680 //-----------------------//
681 // Configuration toggles //
682 //-----------------------//
683
684 /// Enable test mode for deterministic output.
685 ///
686 /// When `true`, encoders may skip randomization or use fixed values for fields
687 /// that would normally vary (like auto-generated IDs), making output reproducible
688 /// for testing purposes.
689 test_mode: bool,
690
691 /// Zero out all date and timestamp fields.
692 ///
693 /// When `true`, any date or timestamp fields are written as `0` instead of their
694 /// actual values. Used in conjunction with `test_mode` for reproducible output,
695 /// or when dates should be reset.
696 nullify_dates: bool,
697
698 /// Include a GUID in the DB table header.
699 ///
700 /// When `true`, table encoders will write a GUID (Globally Unique Identifier) in
701 /// the table header. Required for Shogun 2 and newer games. Must be `false` for Empire
702 /// and Napoleon, as including a GUID crashes those games on load.
703 table_has_guid: bool,
704
705 /// Generate a new GUID for the table instead of preserving the existing one.
706 ///
707 /// When `true`, a fresh random GUID is generated. When `false`, the existing GUID
708 /// (if any) is preserved. Only meaningful when `table_has_guid` is also `true`.
709 regenerate_table_guid: bool,
710
711 //-----------------------//
712 // Optional config data //
713 //-----------------------//
714
715 /// Complete game information context.
716 ///
717 /// Provides game-specific settings, version info, and feature flags that may
718 /// affect encoding behavior (e.g., format variations between game versions).
719 game_info: Option<&'a GameInfo>,
720
721 /// Compression format to use when writing files.
722 ///
723 /// Specifies which compression algorithm to apply. Common formats include:
724 /// - [`CompressionFormat::None`]: No compression
725 /// - [`CompressionFormat::Lz4`]: Fast compression
726 /// - [`CompressionFormat::Zstd`]: Modern compression (best ratio)
727 /// - [`CompressionFormat::Lzma1`]: Legacy compression (older games)
728 /// - [`CompressionFormat::Lz4Block`]: Raw Lz4 blocks (Shogun 2 Complete Edition PFH3 Packs only)
729 ///
730 /// The game info may override this based on what the target game supports.
731 compression_format: CompressionFormat,
732
733 /// Disable compression for nested encoding operations.
734 ///
735 /// When `true`, prevents compression even if `compression_format` is set. Used for
736 /// ESF (Empire Save File) encoding where the outer container handles compression
737 /// and inner structures should remain uncompressed to avoid double-compression.
738 disable_compression: bool
739}
740
741//---------------------------------------------------------------------------//
742// Trait Definitions
743//---------------------------------------------------------------------------//
744
745/// Generic trait for decoding binary data into structured types.
746///
747/// This trait provides a standardized interface for deserializing binary data from any
748/// source implementing [`ReadBytes`]. All Total War file types
749/// in RPFM implement this trait to enable consistent decoding behavior.
750///
751/// # Type Parameters
752///
753/// The trait is object-safe and requires `Send + Sync` to enable concurrent decoding operations.
754///
755/// # Examples
756///
757/// ```ignore
758/// use rpfm_lib::files::{Decodeable, DecodeableExtraData};
759/// use rpfm_lib::binary::ReadBytes;
760///
761/// let data = &[0x01, 0x02, 0x03, 0x04];
762/// let extra_data = None;
763/// let decoded = MyType::decode(&mut data.as_slice(), &extra_data)?;
764/// ```
765pub trait Decodeable: Send + Sync {
766
767 /// Decodes binary data into the implementing type.
768 ///
769 /// This method reads from any source implementing [`ReadBytes`]
770 /// and constructs an instance of the implementing type.
771 ///
772 /// # Parameters
773 ///
774 /// - `data`: A mutable reference to a type implementing [`ReadBytes`]
775 /// - `extra_data`: Optional additional context needed for decoding (schemas, game version, etc.)
776 ///
777 /// # Returns
778 ///
779 /// Returns `Ok(Self)` on successful decoding, or an error if the data is malformed or
780 /// insufficient context was provided.
781 ///
782 /// # Errors
783 ///
784 /// This function may return errors if:
785 /// - The binary data is corrupted or malformed
786 /// - Required schema information is missing from `extra_data`
787 /// - The data stream ends unexpectedly
788 fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> where Self: Sized;
789}
790
791/// Generic trait for encoding structured types into binary data.
792///
793/// This trait provides a standardized interface for serializing structured data to any
794/// destination implementing [`WriteBytes`]. All Total War file types
795/// in RPFM implement this trait to enable consistent encoding behavior.
796///
797/// # Type Parameters
798///
799/// The trait is object-safe and requires `Send + Sync` to enable concurrent encoding operations.
800///
801/// # Examples
802///
803/// ```ignore
804/// use rpfm_lib::files::{Encodeable, EncodeableExtraData};
805/// use rpfm_lib::binary::WriteBytes;
806///
807/// let mut buffer = Vec::new();
808/// let extra_data = None;
809/// my_instance.encode(&mut buffer, &extra_data)?;
810/// ```
811pub trait Encodeable: Send + Sync {
812
813 /// Encodes the implementing type into binary data.
814 ///
815 /// This method writes to any destination implementing [`WriteBytes`],
816 /// serializing the instance's data in the appropriate Total War file format.
817 ///
818 /// # Parameters
819 ///
820 /// - `buffer`: A mutable reference to a type implementing [`WriteBytes`]
821 /// - `extra_data`: Optional additional context needed for encoding (schemas, game version, etc.)
822 ///
823 /// # Returns
824 ///
825 /// Returns `Ok(())` on successful encoding, or an error if the encoding process fails.
826 ///
827 /// # Errors
828 ///
829 /// This function may return errors if:
830 /// - Writing to the buffer fails
831 /// - Required schema information is missing from `extra_data`
832 /// - The data contains invalid values that cannot be serialized
833 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()>;
834}
835
836/// Interface for working with container-like files.
837///
838/// This trait provides a unified API for manipulating file containers such as PackFiles,
839/// allowing implementors to store, retrieve, and manage collections of [`RFile`]s with
840/// hierarchical path structures.
841///
842/// # Implementors
843///
844/// - `Pack`: Total War PackFile containers (`.pack` files)
845/// - Other container formats that store multiple files
846///
847/// # Core Operations
848///
849/// The trait provides several categories of operations:
850///
851/// - **File access**: Get references to files by path, type, or pattern
852/// - **Insertion**: Add files from disk or [`RFile`] instances
853/// - **Extraction**: Write files to disk, optionally as TSV for DB/Loc files
854/// - **Removal**: Delete files or folders by path
855/// - **Queries**: Check existence, list folders, filter by type
856///
857/// # Path Handling
858///
859/// All paths use forward slashes (`/`) as separators, regardless of OS. Paths starting
860/// with `/` are automatically normalized by removing the leading slash.
861pub trait Container {
862
863 /// Extracts files from the container to disk.
864 ///
865 /// This method writes files matching the provided [`ContainerPath`] to the filesystem,
866 /// optionally preserving the container's folder structure.
867 ///
868 /// # Parameters
869 ///
870 /// - `container_path`: Path to file or folder within the container to extract
871 /// - `destination_path`: Target directory on disk where files will be written
872 /// - `keep_container_path_structure`: If `true`, preserves the container's folder hierarchy
873 /// - `schema`: If provided, attempts to export DB/Loc files as TSV (falls back to binary on error)
874 /// - `case_insensitive`: Enable case-insensitive folder matching (file extraction is always case-sensitive)
875 /// - `keys_first`: When exporting to TSV, place key columns first
876 /// - `extra_data`: Optional encoding context for binary files
877 ///
878 /// # Returns
879 ///
880 /// Returns a list of paths to the extracted files on disk.
881 ///
882 /// # Errors
883 ///
884 /// Returns an error if:
885 /// - The specified container path doesn't exist
886 /// - Disk I/O operations fail
887 /// - File decoding fails (for TSV export)
888 ///
889 /// # Examples
890 ///
891 /// ```ignore
892 /// // Extract a single file, preserving structure
893 /// let paths = container.extract(
894 /// ContainerPath::File("db/units_tables/units.bin".to_string()),
895 /// Path::new("./output"),
896 /// true, // Keep structure
897 /// &Some(schema),
898 /// false, // Case-sensitive
899 /// true, // Keys first
900 /// &None,
901 /// )?;
902 ///
903 /// // Extract entire folder as TSV
904 /// let paths = container.extract(
905 /// ContainerPath::Folder("db/".to_string()),
906 /// Path::new("./output"),
907 /// false, // Flat extraction
908 /// &Some(schema),
909 /// true, // Case-insensitive
910 /// true,
911 /// &None,
912 /// )?;
913 /// ```
914 #[allow(clippy::too_many_arguments)]
915 fn extract(&mut self,
916 container_path: ContainerPath,
917 destination_path: &Path,
918 keep_container_path_structure: bool,
919 schema: &Option<Schema>,
920 case_insensitive: bool,
921 keys_first: bool,
922 extra_data: &Option<EncodeableExtraData>,
923 ) -> Result<Vec<PathBuf>> {
924
925 let mut extracted_paths = vec![];
926 match container_path {
927 ContainerPath::File(mut container_path) => {
928 if container_path.starts_with('/') {
929 container_path.remove(0);
930 }
931
932 let destination_path = if keep_container_path_structure {
933 destination_path.to_owned().join(&container_path)
934 } else {
935 destination_path.to_owned()
936 };
937
938 let mut destination_folder = destination_path.to_owned();
939 destination_folder.pop();
940 DirBuilder::new().recursive(true).create(&destination_folder)?;
941
942 let rfile = self.files_mut().get_mut(&container_path).ok_or_else(|| RLibError::FileNotFound(container_path.to_string()))?;
943
944 // If we want to extract as tsv and we got a db/loc, export to tsv.
945 if let Some(schema) = schema {
946 if rfile.file_type() == FileType::DB || rfile.file_type() == FileType::Loc {
947 let mut destination_path_tsv = destination_path.to_owned();
948
949 // Make sure to NOT replace the extension if there is one, only append to it.
950 match destination_path_tsv.extension() {
951 Some(extension) => {
952 let extension = format!("{}.tsv", extension.to_string_lossy());
953 destination_path_tsv.set_extension(extension)
954 },
955 None => destination_path_tsv.set_extension("tsv"),
956 };
957
958 let result = rfile.tsv_export_to_path(&destination_path_tsv, schema, keys_first);
959
960 // If it fails to extract as tsv, extract as binary.
961 if result.is_err() {
962 warn!("File with path {} failed to extract as TSV. Extracting it as binary.", rfile.path_in_container_raw());
963
964 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
965 extracted_paths.push(extracted_path);
966 } else {
967 extracted_paths.push(destination_path_tsv);
968 result?;
969 }
970 } else {
971 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
972 extracted_paths.push(extracted_path);
973 }
974 }
975
976 // Otherwise, just write the binary data to disk.
977 else {
978 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
979 extracted_paths.push(extracted_path);
980 }
981 }
982 ContainerPath::Folder(mut container_path) => {
983 if container_path.starts_with('/') {
984 container_path.remove(0);
985 }
986
987 let mut rfiles = self.files_by_path_mut(&ContainerPath::Folder(container_path.clone()), case_insensitive);
988 for rfile in &mut rfiles {
989 let container_path = rfile.path_in_container_raw();
990 let destination_path = if keep_container_path_structure {
991 destination_path.to_owned().join(container_path)
992 } else {
993 destination_path.to_owned()
994 };
995
996 let mut destination_folder = destination_path.to_owned();
997 destination_folder.pop();
998 DirBuilder::new().recursive(true).create(&destination_folder)?;
999
1000 // If we want to extract as tsv and we got a db/loc, export to tsv.
1001 if let Some(schema) = schema {
1002 if rfile.file_type() == FileType::DB || rfile.file_type() == FileType::Loc {
1003 let mut destination_path_tsv = destination_path.to_owned();
1004
1005 // Make sure to NOT replace the extension if there is one, only append to it.
1006 match destination_path_tsv.extension() {
1007 Some(extension) => {
1008 let extension = format!("{}.tsv", extension.to_string_lossy());
1009 destination_path_tsv.set_extension(extension)
1010 },
1011 None => destination_path_tsv.set_extension("tsv"),
1012 };
1013
1014 let result = rfile.tsv_export_to_path(&destination_path_tsv, schema, keys_first);
1015
1016 // If it fails to extract as tsv, extract as binary.
1017 if result.is_err() {
1018 warn!("File with path {} failed to extract as TSV. Extracting it as binary.", rfile.path_in_container_raw());
1019
1020 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
1021 extracted_paths.push(extracted_path);
1022 } else {
1023 extracted_paths.push(destination_path_tsv);
1024 result?;
1025 }
1026 } else {
1027 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
1028 extracted_paths.push(extracted_path);
1029 }
1030 }
1031
1032 // Otherwise, just write the binary data to disk.
1033 else {
1034 let extracted_path = rfile.sanitize_and_create_file(&destination_path, extra_data)?;
1035 extracted_paths.push(extracted_path);
1036 }
1037
1038 }
1039
1040 // If we're extracting the whole container, also extract any relevant metadata file associated with it.
1041 if container_path.is_empty() {
1042 extracted_paths.append(&mut self.extract_metadata(destination_path)?);
1043 }
1044 }
1045 }
1046
1047 Ok(extracted_paths)
1048 }
1049
1050 /// Extracts container metadata as `.json` files.
1051 ///
1052 /// This method writes any metadata associated with the container (such as pack settings,
1053 /// notes, or configuration) to the specified destination directory.
1054 ///
1055 /// # Parameters
1056 ///
1057 /// - `destination_path`: Directory where metadata files will be written
1058 ///
1059 /// # Returns
1060 ///
1061 /// Returns a list of paths to the extracted metadata files.
1062 ///
1063 /// # Default Implementation
1064 ///
1065 /// The default implementation does nothing and returns an empty list. Container types
1066 /// with metadata should override this method.
1067 fn extract_metadata(&mut self, _destination_path: &Path) -> Result<Vec<PathBuf>> {
1068 Ok(vec![])
1069 }
1070
1071 /// Inserts an [`RFile`] into the container.
1072 ///
1073 /// If a file with the same path already exists, it will be replaced.
1074 ///
1075 /// # Parameters
1076 ///
1077 /// - `file`: The [`RFile`] to insert
1078 ///
1079 /// # Returns
1080 ///
1081 /// Returns the [`ContainerPath`] of the inserted file, or `None` if insertion failed.
1082 fn insert(&mut self, file: RFile) -> Result<Option<ContainerPath>> {
1083 let path = file.path_in_container();
1084 let path_raw = file.path_in_container_raw();
1085
1086 self.paths_cache_insert_path(path_raw);
1087 self.files_mut().insert(path_raw.to_owned(), file);
1088 Ok(Some(path))
1089 }
1090
1091 /// Inserts a file from disk into the container.
1092 ///
1093 /// This method reads a file from the filesystem and inserts it at the specified path
1094 /// within the container. If a file already exists at that path, it will be replaced.
1095 ///
1096 /// # TSV Import
1097 ///
1098 /// If a [`Schema`] is provided and the source file has a `.tsv` extension, this method
1099 /// will attempt to import it as a binary DB/Loc file. If the conversion fails, it falls
1100 /// back to importing it as a plain text file.
1101 ///
1102 /// # Parameters
1103 ///
1104 /// - `source_path`: Path to the file on disk to import
1105 /// - `container_path_folder`: Target path within the container (folder or full path)
1106 /// - `schema`: Optional schema for TSV-to-binary conversion
1107 ///
1108 /// # Returns
1109 ///
1110 /// Returns the [`ContainerPath`] of the inserted file, or `None` if insertion failed.
1111 ///
1112 /// # Errors
1113 ///
1114 /// Returns an error if:
1115 /// - The source file cannot be read
1116 /// - File type detection fails
1117 ///
1118 /// # Path Behavior
1119 ///
1120 /// - If `container_path_folder` ends with `/` or is empty, the source filename is appended
1121 /// - Otherwise, `container_path_folder` is used as the full target path
1122 fn insert_file(&mut self, source_path: &Path, container_path_folder: &str, schema: &Option<Schema>) -> Result<Option<ContainerPath>> {
1123 let mut container_path_folder = container_path_folder.replace('\\', "/");
1124 if container_path_folder.starts_with('/') {
1125 container_path_folder.remove(0);
1126 }
1127
1128 if container_path_folder.ends_with('/') || container_path_folder.is_empty() {
1129 let trimmed_path = source_path.file_name()
1130 .ok_or_else(|| RLibError::PathMissingFileName(source_path.to_string_lossy().to_string()))?
1131 .to_string_lossy().to_string();
1132 container_path_folder = container_path_folder.to_owned() + &trimmed_path;
1133 }
1134
1135 // If tsv import is enabled, try to import the file to binary before adding it to the Container.
1136 let mut tsv_imported = false;
1137 let mut rfile = match source_path.extension() {
1138 Some(extension) if extension.to_string_lossy() == "tsv" => {
1139 tsv_imported = true;
1140 let rfile = RFile::tsv_import_from_path(source_path, schema);
1141 if let Err(error) = rfile {
1142 warn!("File with path {} failed to import as TSV. Importing it as binary. If you're using the CLI - did you forget to provide schema with --tsv-as-binary flag? Error was: {}", source_path.to_string_lossy(), error);
1143
1144 tsv_imported = false;
1145 RFile::new_from_file_path(source_path)
1146 } else {
1147 rfile
1148 }
1149 }
1150 _ => RFile::new_from_file_path(source_path),
1151 }?;
1152
1153 if !tsv_imported {
1154 rfile.set_path_in_container_raw(&container_path_folder);
1155 }
1156
1157 // Make sure to guess the file type before inserting it.
1158 rfile.load()?;
1159 rfile.guess_file_type()?;
1160
1161 self.insert(rfile)
1162 }
1163
1164 /// Inserts an entire folder from disk into the container recursively.
1165 ///
1166 /// This method recursively scans a directory and imports all files, preserving
1167 /// the folder structure. Files with identical paths in the container are replaced.
1168 ///
1169 /// # TSV Import
1170 ///
1171 /// If a [`Schema`] is provided, `.tsv` files will be converted to binary DB/Loc format.
1172 /// If conversion fails, they're imported as plain text files.
1173 ///
1174 /// # Parameters
1175 ///
1176 /// - `source_path`: Path to the folder on disk to import
1177 /// - `container_path_folder`: Target folder path within the container
1178 /// - `ignored_paths`: Optional list of relative paths to exclude from import
1179 /// - `schema`: Optional schema for TSV-to-binary conversion
1180 /// - `include_base_folder`: If `true`, includes the source folder name in container paths
1181 ///
1182 /// # Returns
1183 ///
1184 /// Returns a list of all [`ContainerPath`]s that were inserted.
1185 ///
1186 /// # Errors
1187 ///
1188 /// Returns an error if:
1189 /// - The source directory cannot be read
1190 /// - Any file read or type detection fails
1191 ///
1192 /// # Folder Inclusion Behavior
1193 ///
1194 /// - `include_base_folder = false`: Contents of `source_path` go directly into `container_path_folder`
1195 /// - `include_base_folder = true`: A subfolder with the source folder's name is created first
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```ignore
1200 /// // Import folder contents directly into "data/"
1201 /// container.insert_folder(
1202 /// Path::new("./my_mod"),
1203 /// "data/",
1204 /// &None,
1205 /// &Some(schema),
1206 /// false // Don't include "my_mod" folder name
1207 /// )?;
1208 ///
1209 /// // Import with ignored paths
1210 /// container.insert_folder(
1211 /// Path::new("./my_mod"),
1212 /// "data/",
1213 /// &Some(vec![".git/", "node_modules/"]),
1214 /// &None,
1215 /// true // Include "my_mod" folder name
1216 /// )?;
1217 /// ```
1218 fn insert_folder(&mut self, source_path: &Path, container_path_folder: &str, ignored_paths: &Option<Vec<&str>>, schema: &Option<Schema>, include_base_folder: bool) -> Result<Vec<ContainerPath>> {
1219 let mut container_path_folder = container_path_folder.replace('\\', "/");
1220 if !container_path_folder.is_empty() && !container_path_folder.ends_with('/') {
1221 container_path_folder.push('/');
1222 }
1223
1224 if container_path_folder.starts_with('/') {
1225 container_path_folder.remove(0);
1226 }
1227
1228 let mut source_path_without_base_folder = source_path.to_path_buf();
1229 source_path_without_base_folder.pop();
1230
1231 let file_paths = files_from_subdir(source_path, true)?;
1232 let mut inserted_paths = Vec::with_capacity(file_paths.len());
1233 for file_path in file_paths {
1234 let trimmed_path = if include_base_folder {
1235 file_path.strip_prefix(&source_path_without_base_folder)?
1236 } else {
1237 file_path.strip_prefix(source_path)?
1238 }.to_string_lossy().replace('\\', "/");
1239
1240 let file_container_path = container_path_folder.to_owned() + &trimmed_path;
1241
1242 if let Some(ignored_paths) = ignored_paths {
1243 if ignored_paths.iter().any(|x| trimmed_path.starts_with(x)) {
1244 continue;
1245 }
1246 }
1247
1248 // If tsv import is enabled, try to import the file to binary before adding it to the Container.
1249 let mut tsv_imported = false;
1250 let mut rfile = match file_path.extension() {
1251 Some(extension) if extension.to_string_lossy() == "tsv" => {
1252 tsv_imported = true;
1253 let rfile = RFile::tsv_import_from_path(&file_path, schema);
1254 if let Err(error) = rfile {
1255 warn!("File with path {} failed to import as TSV. Importing it as binary. If you're using the CLI - did you forget to provide schema with --tsv-as-binary flag? Error was: {}", file_path.to_string_lossy(), error);
1256
1257 tsv_imported = false;
1258 RFile::new_from_file_path(&file_path)
1259 } else {
1260 rfile
1261 }
1262 }
1263 _ => RFile::new_from_file_path(&file_path),
1264 }?;
1265
1266 if !tsv_imported {
1267 rfile.set_path_in_container_raw(&file_container_path);
1268 }
1269
1270 // Make sure to guess the file type before inserting it.
1271 rfile.load()?;
1272 rfile.guess_file_type()?;
1273
1274 if let Some(path) = self.insert(rfile)? {
1275 inserted_paths.push(path);
1276 }
1277 }
1278
1279 Ok(inserted_paths)
1280 }
1281
1282 /// Removes files matching the provided [`ContainerPath`] from the container.
1283 ///
1284 /// This method deletes files or entire folder hierarchies from the container.
1285 ///
1286 /// # Parameters
1287 ///
1288 /// - `path`: The container path to remove (file or folder)
1289 ///
1290 /// # Returns
1291 ///
1292 /// Returns a list of removed [`ContainerPath`]s, always using the [`File`](ContainerPath::File) variant.
1293 ///
1294 /// # Special Cases
1295 ///
1296 /// - `ContainerPath::Folder("")`: Represents the container root, deletes **all** files
1297 /// - `ContainerPath::File(...)`: Deletes a single file
1298 /// - `ContainerPath::Folder(...)`: Deletes all files under that folder (recursive)
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```ignore
1303 /// // Remove a single file
1304 /// container.remove(&ContainerPath::File("data/units.bin".to_string()));
1305 ///
1306 /// // Remove entire folder
1307 /// container.remove(&ContainerPath::Folder("db/".to_string()));
1308 ///
1309 /// // Clear entire container
1310 /// container.remove(&ContainerPath::Folder("".to_string()));
1311 /// ```
1312 fn remove(&mut self, path: &ContainerPath) -> Vec<ContainerPath> {
1313 match path {
1314 ContainerPath::File(path) => {
1315 let mut path = path.to_owned();
1316 if path.starts_with('/') {
1317 path.remove(0);
1318 }
1319
1320 self.paths_cache_remove_path(&path);
1321 self.files_mut().remove(&path);
1322 vec![ContainerPath::File(path.to_owned())]
1323 },
1324 ContainerPath::Folder(path) => {
1325 let mut path = path.to_owned();
1326 if path.starts_with('/') {
1327 path.remove(0);
1328 }
1329
1330 // If the path is empty, we mean the root of the container, including everything on it.
1331 if path.is_empty() {
1332 self.files_mut().clear();
1333 vec![ContainerPath::Folder(String::new()); 1]
1334 }
1335
1336 // Otherwise, it's a normal folder.
1337 else {
1338 let mut path_full = path.to_owned();
1339 path_full.push('/');
1340
1341 let paths_to_remove = self.files().par_iter()
1342 .filter_map(|(key, _)| {
1343
1344 // Make sure to only pick folders, not files matching folder names or partial folder matches!
1345 if key.starts_with(&path_full) {
1346 Some(key.to_owned())
1347 } else {
1348 None
1349 }
1350 }).collect::<Vec<String>>();
1351
1352 paths_to_remove.iter().for_each(|path| {
1353 self.paths_cache_remove_path(path);
1354 self.files_mut().remove(path);
1355 });
1356
1357 // Fix for when we try to delete empty folders.
1358 if paths_to_remove.is_empty() {
1359 vec![ContainerPath::Folder(path); 1]
1360 } else {
1361 paths_to_remove.par_iter().map(|path| ContainerPath::File(path.to_string())).collect()
1362 }
1363 }
1364 }
1365 }
1366 }
1367
1368 /// Returns the full path on disk where this container is stored.
1369 ///
1370 /// # Returns
1371 ///
1372 /// The absolute file path, or an empty string if the container is not backed by a disk file.
1373 fn disk_file_path(&self) -> &str;
1374
1375 /// Returns the filename of the container on disk.
1376 ///
1377 /// Extracts just the filename portion from [`disk_file_path()`](Self::disk_file_path).
1378 ///
1379 /// # Returns
1380 ///
1381 /// The filename as a string, or an empty string if no disk path is set.
1382 fn disk_file_name(&self) -> String {
1383 PathBuf::from(self.disk_file_path()).file_name().unwrap_or_default().to_string_lossy().to_string()
1384 }
1385
1386 /// Returns the byte offset of this container's data within its disk file.
1387 ///
1388 /// This is used for nested containers (e.g., a container embedded within another file).
1389 ///
1390 /// # Returns
1391 ///
1392 /// The offset in bytes, or `0` if the container starts at the beginning of the file.
1393 fn disk_file_offset(&self) -> u64;
1394
1395 /// Checks if a file with the specified path exists in the container.
1396 ///
1397 /// # Parameters
1398 ///
1399 /// - `path`: The file path to check (case-sensitive)
1400 ///
1401 /// # Returns
1402 ///
1403 /// `true` if the file exists, `false` otherwise.
1404 fn has_file(&self, path: &str) -> bool {
1405 self.files().get(path).is_some()
1406 }
1407
1408 /// Checks if a non-empty folder exists at the specified path.
1409 ///
1410 /// A folder is considered to exist if there is at least one file whose path starts
1411 /// with the provided folder path.
1412 ///
1413 /// # Parameters
1414 ///
1415 /// - `path`: The folder path to check
1416 ///
1417 /// # Returns
1418 ///
1419 /// `true` if the folder exists and contains files, `false` otherwise.
1420 ///
1421 /// # Note
1422 ///
1423 /// Empty string always returns `false`. Paths are normalized to end with `/` for matching.
1424 fn has_folder(&self, path: &str) -> bool {
1425 if path.is_empty() {
1426 false
1427 } else {
1428
1429 // Make sure we don't trigger false positives due to similarly started files/folders.
1430 let path = if path.ends_with('/') {
1431 path.to_string()
1432 } else {
1433 let mut path = path.to_string();
1434 path.push('/');
1435 path
1436 };
1437
1438 self.files().keys().any(|x| x.starts_with(&path) && x.len() > path.len())
1439 }
1440 }
1441
1442 /// Returns a reference to an [`RFile`] in the container by path.
1443 ///
1444 /// # Parameters
1445 ///
1446 /// - `path`: The file path to look up
1447 /// - `case_insensitive`: If `true`, performs case-insensitive matching
1448 ///
1449 /// # Returns
1450 ///
1451 /// `Some(&RFile)` if the file exists, `None` otherwise.
1452 fn file(&self, path: &str, case_insensitive: bool) -> Option<&RFile> {
1453 if case_insensitive {
1454 let lower = path.to_lowercase();
1455 self.paths_cache().get(&lower).and_then(|paths| self.files().get(&paths[0]))
1456 } else {
1457 self.files().get(path)
1458 }
1459 }
1460
1461 /// Returns a mutable reference to an [`RFile`] in the container by path.
1462 ///
1463 /// # Parameters
1464 ///
1465 /// - `path`: The file path to look up
1466 /// - `case_insensitive`: If `true`, performs case-insensitive matching
1467 ///
1468 /// # Returns
1469 ///
1470 /// `Some(&mut RFile)` if the file exists, `None` otherwise.
1471 fn file_mut(&mut self, path: &str, case_insensitive: bool) -> Option<&mut RFile> {
1472 if case_insensitive {
1473 let lower = path.to_lowercase();
1474 self.paths_cache().get(&lower).cloned().and_then(|paths| self.files_mut().get_mut(&paths[0]))
1475 } else {
1476 self.files_mut().get_mut(path)
1477 }
1478 }
1479
1480 /// Returns a reference to the internal file map.
1481 ///
1482 /// The map uses file paths as keys and [`RFile`]s as values.
1483 fn files(&self) -> &HashMap<String, RFile>;
1484
1485 /// Returns a mutable reference to the internal file map.
1486 ///
1487 /// The map uses file paths as keys and [`RFile`]s as values.
1488 fn files_mut(&mut self) -> &mut HashMap<String, RFile>;
1489
1490 /// Returns references to all files of the specified types.
1491 ///
1492 /// # Parameters
1493 ///
1494 /// - `file_types`: Slice of [`FileType`]s to filter by
1495 ///
1496 /// # Returns
1497 ///
1498 /// A vector of references to matching files.
1499 fn files_by_type(&self, file_types: &[FileType]) -> Vec<&RFile> {
1500 self.files()
1501 .iter()
1502 .filter(|(_, file)| file_types.contains(&file.file_type))
1503 .map(|(_, file)| file)
1504 .collect()
1505 }
1506
1507 /// Returns mutable references to all files of the specified types.
1508 ///
1509 /// # Parameters
1510 ///
1511 /// - `file_types`: Slice of [`FileType`]s to filter by
1512 ///
1513 /// # Returns
1514 ///
1515 /// A vector of mutable references to matching files.
1516 fn files_by_type_mut(&mut self, file_types: &[FileType]) -> Vec<&mut RFile> {
1517 self.files_mut().par_iter_mut().filter(|(_, file)| file_types.contains(&file.file_type)).map(|(_, file)| file).collect()
1518 }
1519
1520 /// Returns references to files matching the provided [`ContainerPath`].
1521 ///
1522 /// # Parameters
1523 ///
1524 /// - `path`: The container path to match (file or folder)
1525 /// - `case_insensitive`: Enable case-insensitive matching
1526 ///
1527 /// # Returns
1528 ///
1529 /// A vector of references to matching files.
1530 ///
1531 /// # Special Cases
1532 ///
1533 /// `ContainerPath::Folder("")` represents the container root and returns **all** files.
1534 fn files_by_path(&self, path: &ContainerPath, case_insensitive: bool) -> Vec<&RFile> {
1535 match path {
1536 ContainerPath::File(path) => self.file(path, case_insensitive).map(|file| vec![file]).unwrap_or(vec![]),
1537 ContainerPath::Folder(path) => {
1538
1539 // If the path is empty, get everything.
1540 if path.is_empty() {
1541 self.files().values().collect()
1542 }
1543
1544 else {
1545 let mut path = if case_insensitive { path.to_lowercase() } else { path.to_owned() };
1546 if !path.ends_with('/') {
1547 path.push('/');
1548 }
1549
1550 // Otherwise, only get the files under our folder.
1551 let real_paths = self.paths_cache()
1552 .par_iter()
1553 .filter_map(|(lower_path, real_paths)| if lower_path.starts_with(&path) { Some(real_paths) } else { None })
1554 .map(|paths| paths.iter().map(|path| ContainerPath::File(path.to_owned())).collect::<Vec<_>>())
1555 .flatten()
1556 .collect::<Vec<_>>();
1557
1558 self.files_by_paths(&real_paths, false)
1559 }
1560 },
1561 }
1562 }
1563
1564 /// Returns mutable references to files matching the provided [`ContainerPath`].
1565 ///
1566 /// # Parameters
1567 ///
1568 /// - `path`: The container path to match (file or folder)
1569 /// - `case_insensitive`: Enable case-insensitive matching
1570 ///
1571 /// # Returns
1572 ///
1573 /// A vector of mutable references to matching files.
1574 ///
1575 /// # Special Cases
1576 ///
1577 /// `ContainerPath::Folder("")` represents the container root and returns **all** files.
1578 fn files_by_path_mut(&mut self, path: &ContainerPath, case_insensitive: bool) -> Vec<&mut RFile> {
1579 match path {
1580 ContainerPath::File(path) => self.file_mut(path, case_insensitive).map(|file| vec![file]).unwrap_or(vec![]),
1581 ContainerPath::Folder(path) => {
1582
1583 // If the path is empty, get everything.
1584 if path.is_empty() {
1585 self.files_mut().values_mut().collect()
1586 }
1587
1588 // Otherwise, only get the files under our folder.
1589 else {
1590 self.files_mut().par_iter_mut()
1591 .filter_map(|(key, file)|
1592 if case_insensitive {
1593 if starts_with_case_insensitive(key, path) { Some(file) } else { None }
1594 } else if key.starts_with(path) {
1595 Some(file)
1596 } else {
1597 None
1598 }
1599 ).collect::<Vec<&mut RFile>>()
1600 }
1601 },
1602 }
1603 }
1604
1605 /// Returns references to files matching any of the provided [`ContainerPath`]s.
1606 ///
1607 /// # Parameters
1608 ///
1609 /// - `paths`: Slice of container paths to match
1610 /// - `case_insensitive`: Enable case-insensitive matching
1611 ///
1612 /// # Returns
1613 ///
1614 /// A vector of references to all matching files (may contain duplicates if paths overlap).
1615 fn files_by_paths(&self, paths: &[ContainerPath], case_insensitive: bool) -> Vec<&RFile> {
1616 paths.iter()
1617 .flat_map(|path| self.files_by_path(path, case_insensitive))
1618 .collect()
1619 }
1620
1621 /// Returns mutable references to files matching any of the provided [`ContainerPath`]s.
1622 ///
1623 /// This method should be used instead of [`files_by_path_mut()`](Self::files_by_path_mut)
1624 /// when you need mutable references to files across multiple different paths, as it
1625 /// properly handles the borrowing requirements.
1626 ///
1627 /// # Parameters
1628 ///
1629 /// - `paths`: Slice of container paths to match
1630 /// - `case_insensitive`: Enable case-insensitive matching
1631 ///
1632 /// # Returns
1633 ///
1634 /// A vector of mutable references to all matching files (no duplicates).
1635 fn files_by_paths_mut(&mut self, paths: &[ContainerPath], case_insensitive: bool) -> Vec<&mut RFile> {
1636 self.files_mut()
1637 .iter_mut()
1638 .filter(|(file_path, _)| {
1639 paths.iter().any(|path| {
1640 match path {
1641 ContainerPath::File(path) => {
1642 if case_insensitive {
1643 caseless::canonical_caseless_match_str(file_path, path)
1644 } else {
1645 file_path == &path
1646 }
1647 }
1648 ContainerPath::Folder(path) => {
1649 if case_insensitive {
1650 starts_with_case_insensitive(file_path, path)
1651 } else {
1652 file_path.starts_with(path)
1653 }
1654 }
1655 }
1656 })
1657 })
1658 .map(|(_, file)| file)
1659 .collect()
1660 }
1661
1662 /// Returns references to files matching both type and path criteria.
1663 ///
1664 /// This is a filtered combination of [`files_by_type()`](Self::files_by_type) and
1665 /// [`files_by_paths()`](Self::files_by_paths).
1666 ///
1667 /// # Parameters
1668 ///
1669 /// - `file_types`: Slice of [`FileType`]s to filter by
1670 /// - `paths`: Slice of [`ContainerPath`]s to match
1671 /// - `case_insensitive`: Enable case-insensitive path matching
1672 ///
1673 /// # Returns
1674 ///
1675 /// A vector of references to files matching both the type and path criteria.
1676 fn files_by_type_and_paths(&self, file_types: &[FileType], paths: &[ContainerPath], case_insensitive: bool) -> Vec<&RFile> {
1677 paths.iter()
1678 .flat_map(|path| self.files_by_path(path, case_insensitive)
1679 .into_iter()
1680 .filter(|file| file_types.contains(&file.file_type()))
1681 .collect::<Vec<_>>()
1682 ).collect()
1683 }
1684
1685 /// Returns mutable references to files matching both type and path criteria.
1686 ///
1687 /// This is a filtered combination of [`files_by_type_mut()`](Self::files_by_type_mut) and
1688 /// [`files_by_paths_mut()`](Self::files_by_paths_mut).
1689 ///
1690 /// # Parameters
1691 ///
1692 /// - `file_types`: Slice of [`FileType`]s to filter by
1693 /// - `paths`: Slice of [`ContainerPath`]s to match
1694 /// - `case_insensitive`: Enable case-insensitive path matching
1695 ///
1696 /// # Returns
1697 ///
1698 /// A vector of mutable references to files matching both the type and path criteria.
1699 fn files_by_type_and_paths_mut(&mut self, file_types: &[FileType], paths: &[ContainerPath], case_insensitive: bool) -> Vec<&mut RFile> {
1700 self.files_by_paths_mut(paths, case_insensitive).into_iter().filter(|file| file_types.contains(&file.file_type())).collect()
1701 }
1702
1703 /// Regenerates the internal paths cache from the current file list.
1704 ///
1705 /// The paths cache maps lowercase paths to their actual casing variants, enabling
1706 /// efficient case-insensitive lookups. This method should be called after bulk
1707 /// modifications to the file list.
1708 fn paths_cache_generate(&mut self) {
1709 self.paths_cache_mut().clear();
1710
1711 let mut cache: HashMap<String, Vec<String>> = HashMap::new();
1712 self.files().keys().for_each(|path| {
1713 let lower = path.to_lowercase();
1714 match cache.get_mut(&lower) {
1715 Some(paths) => paths.push(path.to_owned()),
1716 None => { cache.insert(lower, vec![path.to_owned()]); },
1717 }
1718 });
1719
1720 *self.paths_cache_mut() = cache;
1721 }
1722
1723 /// Adds a single path to the paths cache.
1724 ///
1725 /// This is more efficient than regenerating the entire cache when adding individual files.
1726 ///
1727 /// # Parameters
1728 ///
1729 /// - `path`: The file path to add (with original casing)
1730 fn paths_cache_insert_path(&mut self, path: &str) {
1731 let path_lower = path.to_lowercase();
1732 match self.paths_cache_mut().get_mut(&path_lower) {
1733 Some(paths) => if paths.iter().all(|x| x != path) {
1734 paths.push(path.to_owned());
1735 }
1736 None => { self.paths_cache_mut().insert(path_lower, vec![path.to_owned()]); }
1737 }
1738 }
1739
1740 /// Removes a single path from the paths cache.
1741 ///
1742 /// This is more efficient than regenerating the entire cache when removing individual files.
1743 ///
1744 /// # Parameters
1745 ///
1746 /// - `path`: The file path to remove (with original casing)
1747 ///
1748 /// # Note
1749 ///
1750 /// Reserved paths (notes, settings) are automatically skipped.
1751 fn paths_cache_remove_path(&mut self, path: &str) {
1752 let path_lower = path.to_lowercase();
1753
1754 // Skip reserved paths when using this.
1755 if path_lower == RESERVED_NAME_NOTES || path_lower == RESERVED_NAME_SETTINGS || path_lower == RESERVED_NAME_DEPENDENCIES_MANAGER_V2 {
1756 return;
1757 }
1758
1759 match self.paths_cache_mut().get_mut(&path_lower) {
1760 Some(paths) => {
1761 match paths.iter().position(|x| x == path) {
1762 Some(pos) => {
1763 paths.remove(pos);
1764 if paths.is_empty() {
1765 self.paths_cache_mut().remove(&path_lower);
1766 }
1767 },
1768 None => { warn!("remove_path received a valid path, but we don't have casing equivalence for it. This is a bug. {path_lower}, {path}"); },
1769 }
1770 }
1771 None => { warn!("remove_path received an invalid path. This is a bug. {path_lower}, {path}"); },
1772 }
1773 }
1774
1775 /// Returns the paths cache mapping lowercase paths to their original-cased variants.
1776 ///
1777 /// This cache enables efficient case-insensitive file lookups. The map structure is:
1778 /// `lowercase_path -> vec![OriginalCased1, OriginalCased2, ...]`
1779 ///
1780 /// # Important
1781 ///
1782 /// If you manipulate the file list directly (via [`files_mut()`](Self::files_mut)),
1783 /// you **must** update this cache using [`paths_cache_insert_path()`](Self::paths_cache_insert_path),
1784 /// [`paths_cache_remove_path()`](Self::paths_cache_remove_path), or
1785 /// [`paths_cache_generate()`](Self::paths_cache_generate).
1786 fn paths_cache(&self) -> &HashMap<String, Vec<String>>;
1787
1788 /// Returns a mutable reference to the paths cache.
1789 ///
1790 /// See [`paths_cache()`](Self::paths_cache) for details on cache structure and maintenance.
1791 fn paths_cache_mut(&mut self) -> &mut HashMap<String, Vec<String>>;
1792
1793 /// Returns a set of all folder paths contained within the container.
1794 ///
1795 /// This method analyzes file paths to extract unique folder hierarchies.
1796 ///
1797 /// # Returns
1798 ///
1799 /// A set of folder paths (without trailing slashes). Root-level files contribute no entries.
1800 fn paths_folders_raw(&self) -> HashSet<String> {
1801 self.files()
1802 .par_iter()
1803 .filter_map(|(path, _)| {
1804 let file_path_split = path.split('/').collect::<Vec<&str>>();
1805 let folder_path_len = file_path_split.len() - 1;
1806 if folder_path_len == 0 {
1807 None
1808 } else {
1809
1810 let mut paths = Vec::with_capacity(folder_path_len);
1811
1812 for (index, folder) in file_path_split.iter().enumerate() {
1813 if index < path.len() - 1 && !folder.is_empty() {
1814 paths.push(file_path_split[0..=index].join("/"))
1815 }
1816 }
1817
1818 Some(paths)
1819 }
1820 })
1821 .flatten()
1822 .collect::<HashSet<String>>()
1823 }
1824
1825 /// This method returns the list of [ContainerPath] corresponding to RFiles within the provided Container.
1826 fn paths(&self) -> Vec<ContainerPath> {
1827 self.files()
1828 .par_iter()
1829 .map(|(path, _)| ContainerPath::File(path.to_owned()))
1830 .collect()
1831 }
1832
1833 /// This method returns the list of paths (as [&str]) corresponding to RFiles within the provided Container.
1834 fn paths_raw(&self) -> Vec<&str> {
1835 self.files()
1836 .par_iter()
1837 .map(|(path, _)| &**path)
1838 .collect()
1839 }
1840
1841 /// This function returns the list of paths (as [String]) corresponding to RFiles that match the provided [ContainerPath].
1842 fn paths_raw_from_container_path(&self, path: &ContainerPath) -> Vec<String> {
1843 match path {
1844 ContainerPath::File(path) => vec![path.to_owned(); 1],
1845 ContainerPath::Folder(path) => {
1846
1847 // If the path is empty, get everything.
1848 if path.is_empty() {
1849 self.paths_raw().iter().map(|x| x.to_string()).collect()
1850 }
1851
1852 // Otherwise, only get the paths under our folder.
1853 else {
1854 self.files().par_iter()
1855 .filter_map(|(key, file)|
1856 if key.starts_with(path) {
1857 Some(file.path_in_container_raw().to_owned())
1858 } else {
1859 None
1860 }
1861 ).collect::<Vec<String>>()
1862 }
1863 },
1864 }
1865 }
1866
1867 /// This method returns the `Last modified date` stored on the provided Container, in seconds.
1868 ///
1869 /// A default implementation that returns `0` is provided for Container types that don't support internal timestamps.
1870 ///
1871 /// Implementors should return `0` if the Container doesn't have a file on disk yet.
1872 fn internal_timestamp(&self) -> u64 {
1873 0
1874 }
1875
1876 /// This method returns the `Last modified date` the filesystem reports for the container file, in seconds.
1877 ///
1878 /// Implementors should return `0` if the Container doesn't have a file on disk yet.
1879 fn local_timestamp(&self) -> u64;
1880
1881 /// This function preloads to memory any lazy-loaded RFile within this container.
1882 fn preload(&mut self) -> Result<()> {
1883 self.files_mut()
1884 .into_par_iter()
1885 .try_for_each(|(_, rfile)| rfile.encode(&None, false, true, false).map(|_| ()))
1886 }
1887
1888 /// This function allows you to *move* multiple RFiles or folders of RFiles from one folder to another.
1889 ///
1890 /// It returns a list with all the new [ContainerPath].
1891 fn move_paths(&mut self, in_out_paths: &[(ContainerPath, ContainerPath)]) -> Result<Vec<(ContainerPath, ContainerPath)>> {
1892 let mut successes = vec![];
1893 for (source_path, destination_path) in in_out_paths {
1894 successes.append(&mut self.move_path(source_path, destination_path)?);
1895 }
1896
1897 Ok(successes)
1898 }
1899
1900 /// This function allows you to *move* any RFile or folder of RFiles from one folder to another.
1901 ///
1902 /// It returns a list with all the new [ContainerPath].
1903 fn move_path(&mut self, source_path: &ContainerPath, destination_path: &ContainerPath) -> Result<Vec<(ContainerPath, ContainerPath)>> {
1904 match source_path {
1905 ContainerPath::File(source_path) => match destination_path {
1906 ContainerPath::File(destination_path) => {
1907 if destination_path.is_empty() {
1908 return Err(RLibError::EmptyDestiny);
1909 }
1910
1911 self.paths_cache_remove_path(source_path);
1912 let mut moved = self
1913 .files_mut()
1914 .remove(source_path)
1915 .ok_or_else(|| RLibError::FileNotFound(source_path.to_string()))?;
1916
1917 moved.set_path_in_container_raw(destination_path);
1918
1919 self.insert(moved).map(|x| match x {
1920 Some(x) => vec![(ContainerPath::File(source_path.to_string()), x); 1],
1921 None => Vec::with_capacity(0)
1922 })
1923 },
1924 ContainerPath::Folder(_) => unreachable!("move_path_1"),
1925 },
1926 ContainerPath::Folder(source_path) => match destination_path {
1927 ContainerPath::File(_) => unreachable!("move_path_2"),
1928 ContainerPath::Folder(destination_path) => {
1929 if destination_path.is_empty() {
1930 return Err(RLibError::EmptyDestiny);
1931 }
1932
1933 // Fix to avoid false positives.
1934 let mut source_path_end = source_path.to_owned();
1935 if !source_path_end.ends_with('/') {
1936 source_path_end.push('/');
1937 }
1938
1939 let moved_paths = self.files()
1940 .par_iter()
1941 .filter_map(|(path, _)| if path.starts_with(&source_path_end) { Some(path.to_owned()) } else { None })
1942 .collect::<Vec<_>>();
1943
1944 let moved = moved_paths.iter()
1945 .filter_map(|x| {
1946 self.paths_cache_remove_path(x);
1947 self.files_mut().remove(x)
1948 })
1949 .collect::<Vec<_>>();
1950
1951 let mut new_paths = Vec::with_capacity(moved.len());
1952 for mut moved in moved {
1953 let old_path = moved.path_in_container();
1954 let new_path = moved.path_in_container_raw().replacen(source_path, destination_path, 1);
1955 moved.set_path_in_container_raw(&new_path);
1956
1957 if let Some(new_path) = self.insert(moved)? {
1958 new_paths.push((old_path, new_path));
1959 }
1960 }
1961
1962 Ok(new_paths)
1963 },
1964 },
1965 }
1966 }
1967
1968 /// This function removes all not-in-memory-already Files from the Container.
1969 ///
1970 /// Used for removing possibly corrupted RFiles from the Container in order to sanitize it.
1971 ///
1972 /// BE CAREFUL WITH USING THIS. IT MAY (PROBABLY WILL) CAUSE DATA LOSSES.
1973 fn clean_undecoded(&mut self) {
1974 self.files_mut().retain(|_, file| file.decoded().is_ok() || file.cached().is_ok());
1975 }
1976}
1977
1978//----------------------------------------------------------------//
1979// Implementations
1980//----------------------------------------------------------------//
1981
1982impl RFile {
1983
1984 /// This function creates a RFile from a lazy-loaded file inside a Container.
1985 ///
1986 /// About the parameters:
1987 /// - `container`: The container this RFile is on.
1988 /// - `size`: Size in bytes of the RFile.
1989 /// - `is_compressed`: If the RFile is compressed.
1990 /// - `is_encrypted`: If the RFile is encrypted.
1991 /// - `data_pos`: Byte offset of the data from the beginning of the Container.
1992 /// - `file_timestamp`: Timestamp of this specific file (not of the container, but the file). If it doesn't have one, pass 0.
1993 /// - `path_in_container`: Path of the RFile in the container.
1994 ///
1995 /// NOTE: Remember to call `guess_file_type` after this to properly set the FileType.
1996 pub fn new_from_container<C: Container>(
1997 container: &C,
1998 size: u64,
1999 is_compressed: bool,
2000 is_encrypted: Option<PFHVersion>,
2001 data_pos: u64,
2002 file_timestamp: u64,
2003 path_in_container: &str,
2004 ) -> Result<Self> {
2005 let on_disk = OnDisk {
2006 path: container.disk_file_path().to_owned(),
2007 timestamp: container.local_timestamp(),
2008 start: container.disk_file_offset() + data_pos,
2009 size,
2010 is_compressed,
2011 lz4_block_uncompressed_size: None,
2012 is_encrypted,
2013 };
2014
2015 let rfile = Self {
2016 path: path_in_container.to_owned(),
2017 timestamp: if file_timestamp == 0 { None } else { Some(file_timestamp) },
2018 file_type: FileType::Unknown,
2019 container_name: Some(container.disk_file_name()),
2020 data: RFileInnerData::OnDisk(on_disk)
2021 };
2022
2023 Ok(rfile)
2024 }
2025
2026 /// This function creates a RFile from a path on disk.
2027 ///
2028 /// This may fail if the file doesn't exist or errors out when trying to be read for metadata.
2029 ///
2030 /// NOTE: Remember to call `guess_file_type` after this to properly set the FileType.
2031 pub fn new_from_file(path: &str) -> Result<Self> {
2032 let path_checked = PathBuf::from(path);
2033 if !path_checked.is_file() {
2034 return Err(RLibError::FileNotFound(path.to_owned()));
2035 }
2036
2037 let mut file = File::open(path)?;
2038 let on_disk = OnDisk {
2039 path: path.to_owned(),
2040 timestamp: last_modified_time_from_file(&file)?,
2041 start: 0,
2042 size: file.len()?,
2043 is_compressed: false,
2044 lz4_block_uncompressed_size: None,
2045 is_encrypted: None,
2046 };
2047
2048
2049 let rfile = Self {
2050 path: path.to_owned(),
2051 timestamp: Some(on_disk.timestamp),
2052 file_type: FileType::Unknown,
2053 container_name: None,
2054 data: RFileInnerData::OnDisk(on_disk)
2055 };
2056
2057 Ok(rfile)
2058 }
2059
2060 /// This function sets the uncompressed size of a lazy-loaded RFile compressed with [`CompressionFormat::Lz4Block`].
2061 ///
2062 /// That format cannot be auto-detected, so this is required to decompress it. Does nothing if the RFile is not lazy-loaded.
2063 pub(crate) fn set_lz4_block_uncompressed_size(&mut self, uncompressed_size: u64) {
2064 if let RFileInnerData::OnDisk(ref mut on_disk) = self.data {
2065 on_disk.lz4_block_uncompressed_size = Some(uncompressed_size);
2066 }
2067 }
2068
2069 /// This function creates a RFile from a path on disk.
2070 ///
2071 /// This may fail if the file doesn't exist or errors out when trying to be read for metadata.
2072 ///
2073 /// NOTE: Remember to call `guess_file_type` after this to properly set the FileType.
2074 pub fn new_from_file_path(path: &Path) -> Result<Self> {
2075 let path = path.to_string_lossy().to_string();
2076 Self::new_from_file(&path)
2077 }
2078
2079 /// This function creates a RFile from raw data on memory.
2080 ///
2081 /// NOTE: Remember to call `guess_file_type` after this to properly set the FileType.
2082 pub fn new_from_vec(data: &[u8], file_type: FileType, timestamp: u64, path: &str) -> Self {
2083 Self {
2084 path: path.to_owned(),
2085 timestamp: if timestamp == 0 { None } else { Some(timestamp) },
2086 file_type,
2087 container_name: None,
2088 data: RFileInnerData::Cached(data.to_vec())
2089 }
2090 }
2091
2092 /// This function creates a RFile from an RFileDecoded on memory.
2093 ///
2094 /// NOTE: Remember to call `guess_file_type` after this to properly set the FileType.
2095 pub fn new_from_decoded(data: &RFileDecoded, timestamp: u64, path: &str) -> Self {
2096 Self {
2097 path: path.to_owned(),
2098 timestamp: if timestamp == 0 { None } else { Some(timestamp) },
2099 file_type: FileType::from(data),
2100 container_name: None,
2101 data: RFileInnerData::Decoded(Box::new(data.clone()))
2102 }
2103 }
2104
2105 /// This function returns a reference to the cached data of an RFile, if said RFile has been cached. If not, it returns an error.
2106 ///
2107 /// Useful for accessing preloaded data.
2108 pub fn cached(&self) -> Result<&[u8]> {
2109 match self.data {
2110 RFileInnerData::Cached(ref data) => Ok(data),
2111 _ => Err(RLibError::FileNotCached(self.path_in_container_raw().to_string()))
2112 }
2113 }
2114
2115 /// This function returns a mutable reference to the cached data of an RFile, if said RFile has been cached. If not, it returns an error.
2116 ///
2117 /// Useful for accessing preloaded data.
2118 pub fn cached_mut(&mut self) -> Result<&mut Vec<u8>> {
2119 match self.data {
2120 RFileInnerData::Cached(ref mut data) => Ok(data),
2121 _ => Err(RLibError::FileNotCached(self.path_in_container_raw().to_string()))
2122 }
2123 }
2124
2125 /// This function returns a reference to the decoded data of an RFile, if said RFile has been decoded. If not, it returns an error.
2126 ///
2127 /// Useful for accessing preloaded data.
2128 pub fn decoded(&self) -> Result<&RFileDecoded> {
2129 match self.data {
2130 RFileInnerData::Decoded(ref data) => Ok(data),
2131 _ => Err(RLibError::FileNotDecoded(self.path_in_container_raw().to_string()))
2132 }
2133 }
2134
2135 /// This function returns a mutable reference to the decoded data of an RFile, if said RFile has been decoded. If not, it returns an error.
2136 ///
2137 /// Useful for accessing preloaded data.
2138 pub fn decoded_mut(&mut self) -> Result<&mut RFileDecoded> {
2139 match self.data {
2140 RFileInnerData::Decoded(ref mut data) => Ok(data),
2141 _ => Err(RLibError::FileNotDecoded(self.path_in_container_raw().to_string()))
2142 }
2143 }
2144
2145 /// This function replace any data a RFile has with the provided raw data.
2146 pub fn set_cached(&mut self, data: &[u8]) {
2147 self.data = RFileInnerData::Cached(data.to_vec());
2148 }
2149
2150 /// This function allows to replace the inner decoded data of a RFile with another. It'll fail if the decoded data is not valid for the file's type.
2151 pub fn set_decoded(&mut self, decoded: RFileDecoded) -> Result<()> {
2152 let decoded_type = FileType::from(&decoded);
2153 if self.file_type() != decoded_type {
2154 return Err(RLibError::DecodedDataDoesNotMatchFileType(self.file_type(), decoded_type));
2155 }
2156
2157 self.data = RFileInnerData::Decoded(Box::new(decoded));
2158 Ok(())
2159 }
2160
2161 /// This function decodes an RFile from binary data, optionally caching and returning the decoded RFile.
2162 ///
2163 /// About the arguments:
2164 ///
2165 /// - `extra_data`: any data needed to decode specific file types. Check each file type for info about what do each file type need.
2166 /// - `keep_in_cache`: if true, the data will be cached on memory.
2167 /// - `return_data`: if true, the decoded data will be returned.
2168 ///
2169 /// NOTE: Passing `keep_in_cache` and `return_data` at false causes this function to decode the RFile and
2170 /// immediately drop the resulting data.
2171 pub fn decode(&mut self, extra_data: &Option<DecodeableExtraData>, keep_in_cache: bool, return_data: bool) -> Result<Option<RFileDecoded>> {
2172 let mut already_decoded = false;
2173 let decoded = match &self.data {
2174
2175 // If the data is already decoded, just return a copy of it.
2176 RFileInnerData::Decoded(data) => {
2177 already_decoded = true;
2178
2179 // Microoptimization: don't clone data if we're not going to use it.
2180 if !return_data {
2181 return Ok(None);
2182 }
2183
2184 *data.clone()
2185 },
2186
2187 // If the data is on memory but not yet decoded, decode it.
2188 RFileInnerData::Cached(data) => {
2189
2190 // Copy the provided extra data (if any), then replace the file-specific stuff.
2191 let mut extra_data = match extra_data {
2192 Some(extra_data) => extra_data.clone(),
2193 None => DecodeableExtraData::default(),
2194 };
2195 extra_data.file_name = self.file_name();
2196 extra_data.data_size = data.len() as u64;
2197
2198 self.decode_data(&mut Cursor::new(data), extra_data)?
2199 },
2200
2201 // If the data is not yet in memory, it depends:
2202 // - If it's something we can lazy-load and we want to, decode it directly from disk.
2203 // - If it's not, load it to memory and decode it from there.
2204 RFileInnerData::OnDisk(data) => {
2205
2206 // Copy the provided extra data (if any), then replace the file-specific stuff.
2207 let raw_data = data.read()?;
2208 let mut extra_data = match extra_data {
2209 Some(extra_data) => extra_data.clone(),
2210 None => DecodeableExtraData::default(),
2211 };
2212
2213 extra_data.file_name = self.file_name();
2214 extra_data.data_size = raw_data.len() as u64;
2215
2216 // These are the easy types: just load the data to memory, and decode.
2217 self.decode_data(&mut Cursor::new(raw_data), extra_data)?
2218 },
2219 };
2220
2221 // If we're returning data, clone it. If not, skip the clone.
2222 if !already_decoded && keep_in_cache && return_data {
2223 self.data = RFileInnerData::Decoded(Box::new(decoded.clone()));
2224 } else if !already_decoded && keep_in_cache && !return_data{
2225 self.data = RFileInnerData::Decoded(Box::new(decoded));
2226 return Ok(None)
2227 }
2228
2229 if return_data {
2230 Ok(Some(decoded))
2231 } else {
2232 Ok(None)
2233 }
2234 }
2235
2236 /// This function decodes the provided data as the RFile's [`FileType`].
2237 ///
2238 /// Types whose format is disabled through cargo features are decoded as [`Unknown`], keeping their data intact.
2239 ///
2240 /// # Arguments
2241 ///
2242 /// * `data` - Reader with the RFile's raw data.
2243 /// * `extra_data` - Extra data needed to decode the RFile, with the file-specific fields already set.
2244 ///
2245 /// # Returns
2246 ///
2247 /// The decoded data of the RFile.
2248 fn decode_data<'a, R: ReadBytes>(&'a self, data: &mut R, mut extra_data: DecodeableExtraData<'a>) -> Result<RFileDecoded> {
2249
2250 // Some types require extra data specific for them to be added to the extra data before decoding.
2251 let decoded = match self.file_type {
2252 #[cfg(feature = "format_anim")] FileType::Anim => RFileDecoded::Anim(Anim::decode(data, &Some(extra_data))?),
2253 #[cfg(feature = "format_anim_fragment_battle")] FileType::AnimFragmentBattle => RFileDecoded::AnimFragmentBattle(AnimFragmentBattle::decode(data, &Some(extra_data))?),
2254 #[cfg(feature = "format_animpack")] FileType::AnimPack => RFileDecoded::AnimPack(AnimPack::decode(data, &Some(extra_data))?),
2255 #[cfg(feature = "format_anims_table")] FileType::AnimsTable => RFileDecoded::AnimsTable(AnimsTable::decode(data, &Some(extra_data))?),
2256 #[cfg(feature = "format_atlas")] FileType::Atlas => RFileDecoded::Atlas(Atlas::decode(data, &Some(extra_data))?),
2257 #[cfg(feature = "format_audio")] FileType::Audio => RFileDecoded::Audio(Audio::decode(data, &Some(extra_data))?),
2258 FileType::BMD => RFileDecoded::BMD(Box::new(Bmd::decode(data, &Some(extra_data))?)),
2259 FileType::BMDVegetation => RFileDecoded::BMDVegetation(BmdVegetation::decode(data, &Some(extra_data))?),
2260 #[cfg(feature = "format_dat")] FileType::Dat => RFileDecoded::Dat(Dat::decode(data, &Some(extra_data))?),
2261 FileType::DB => {
2262
2263 if extra_data.table_name.is_none() {
2264 extra_data.table_name = self.db_table_name_from_path();
2265 }
2266 RFileDecoded::DB(DB::decode(data, &Some(extra_data))?)
2267 },
2268 FileType::ESF => RFileDecoded::ESF(ESF::decode(data, &Some(extra_data))?),
2269 #[cfg(feature = "format_font")] FileType::Font => RFileDecoded::Font(Font::decode(data, &Some(extra_data))?),
2270 #[cfg(feature = "format_group_formations")] FileType::GroupFormations => RFileDecoded::GroupFormations(GroupFormations::decode(data, &Some(extra_data))?),
2271 #[cfg(feature = "format_hlsl_compiled")] FileType::HlslCompiled => RFileDecoded::HlslCompiled(HlslCompiled::decode(data, &Some(extra_data))?),
2272 #[cfg(feature = "format_image")] FileType::Image => {
2273
2274 if self.path.ends_with(".dds") {
2275 extra_data.is_dds = true;
2276 }
2277
2278 RFileDecoded::Image(Image::decode(data, &Some(extra_data))?)
2279 },
2280 FileType::Loc => RFileDecoded::Loc(Loc::decode(data, &Some(extra_data))?),
2281 #[cfg(feature = "format_matched_combat")] FileType::MatchedCombat => RFileDecoded::MatchedCombat(MatchedCombat::decode(data, &Some(extra_data))?),
2282 FileType::Pack => RFileDecoded::Pack(Pack::decode(data, &Some(extra_data))?),
2283 #[cfg(feature = "format_portrait_settings")] FileType::PortraitSettings => RFileDecoded::PortraitSettings(PortraitSettings::decode(data, &Some(extra_data))?),
2284 FileType::RigidModel => RFileDecoded::RigidModel(RigidModel::decode(data, &Some(extra_data))?),
2285 #[cfg(feature = "format_sound_bank")] FileType::SoundBank => RFileDecoded::SoundBank(SoundBank::decode(data, &Some(extra_data))?),
2286 FileType::Text => RFileDecoded::Text(Text::decode(data, &Some(extra_data))?),
2287 #[cfg(feature = "format_trade_routes")] FileType::TradeRoutes => RFileDecoded::TradeRoutes(TradeRoutes::decode(data, &Some(extra_data))?),
2288 #[cfg(feature = "format_uic")] FileType::UIC => RFileDecoded::UIC(UIC::decode(data, &Some(extra_data))?),
2289 #[cfg(feature = "format_unit_variant")] FileType::UnitVariant => RFileDecoded::UnitVariant(UnitVariant::decode(data, &Some(extra_data))?),
2290 FileType::Unknown => RFileDecoded::Unknown(Unknown::decode(data, &Some(extra_data))?),
2291 FileType::Video => RFileDecoded::Video(Video::decode(data, &Some(extra_data))?),
2292 FileType::VMD => RFileDecoded::VMD(Text::decode(data, &Some(extra_data))?),
2293 FileType::WSModel => RFileDecoded::WSModel(Text::decode(data, &Some(extra_data))?),
2294
2295 // Types whose format feature is disabled. Unreachable when all formats are enabled.
2296 #[allow(unreachable_patterns)]
2297 _ => RFileDecoded::Unknown(Unknown::decode(data, &Some(extra_data))?),
2298 };
2299
2300 Ok(decoded)
2301 }
2302
2303 /// This function encodes an RFile to binary, optionally caching and returning the data.
2304 ///
2305 /// About the arguments:
2306 /// - `extra_data`: any data needed to encode specific file types. Check each file type for info about what do each file type need.
2307 /// - `move_decoded_to_cache`: if true, the decoded data will be dropped in favor of undecoded cached data.
2308 /// - `move_undecoded_to_cache`: if true, the data will be cached on memory.
2309 /// - `return_data`: if true, the data will be returned.
2310 pub fn encode(&mut self, extra_data: &Option<EncodeableExtraData>, move_decoded_to_cache: bool, move_undecoded_to_cache: bool, return_data: bool) -> Result<Option<Vec<u8>>> {
2311 let mut previously_decoded = false;
2312 let mut already_encoded = false;
2313 let mut previously_undecoded = false;
2314
2315 let encoded = match &mut self.data {
2316 RFileInnerData::Decoded(data) => {
2317 previously_decoded = true;
2318 let mut buffer = vec![];
2319 match &mut **data {
2320 #[cfg(feature = "format_anim")] RFileDecoded::Anim(data) => data.encode(&mut buffer, extra_data)?,
2321 #[cfg(feature = "format_anim_fragment_battle")] RFileDecoded::AnimFragmentBattle(data) => data.encode(&mut buffer, extra_data)?,
2322 #[cfg(feature = "format_animpack")] RFileDecoded::AnimPack(data) => data.encode(&mut buffer, extra_data)?,
2323 #[cfg(feature = "format_anims_table")] RFileDecoded::AnimsTable(data) => data.encode(&mut buffer, extra_data)?,
2324 #[cfg(feature = "format_atlas")] RFileDecoded::Atlas(data) => data.encode(&mut buffer, extra_data)?,
2325 #[cfg(feature = "format_audio")] RFileDecoded::Audio(data) => data.encode(&mut buffer, extra_data)?,
2326 RFileDecoded::BMD(data) => data.encode(&mut buffer, extra_data)?,
2327 RFileDecoded::BMDVegetation(data) => data.encode(&mut buffer, extra_data)?,
2328 #[cfg(feature = "format_dat")] RFileDecoded::Dat(data) => data.encode(&mut buffer, extra_data)?,
2329 RFileDecoded::DB(data) => data.encode(&mut buffer, extra_data)?,
2330 RFileDecoded::ESF(data) => data.encode(&mut buffer, extra_data)?,
2331 #[cfg(feature = "format_font")] RFileDecoded::Font(data) => data.encode(&mut buffer, extra_data)?,
2332 #[cfg(feature = "format_group_formations")] RFileDecoded::GroupFormations(data) => data.encode(&mut buffer, extra_data)?,
2333 #[cfg(feature = "format_hlsl_compiled")] RFileDecoded::HlslCompiled(data) => data.encode(&mut buffer, extra_data)?,
2334 #[cfg(feature = "format_image")] RFileDecoded::Image(data) => data.encode(&mut buffer, extra_data)?,
2335 RFileDecoded::Loc(data) => data.encode(&mut buffer, extra_data)?,
2336 #[cfg(feature = "format_matched_combat")] RFileDecoded::MatchedCombat(data) => data.encode(&mut buffer, extra_data)?,
2337 RFileDecoded::Pack(data) => data.encode(&mut buffer, extra_data)?,
2338 #[cfg(feature = "format_portrait_settings")] RFileDecoded::PortraitSettings(data) => data.encode(&mut buffer, extra_data)?,
2339 RFileDecoded::RigidModel(data) => data.encode(&mut buffer, extra_data)?,
2340 #[cfg(feature = "format_sound_bank")] RFileDecoded::SoundBank(data) => data.encode(&mut buffer, extra_data)?,
2341 RFileDecoded::Text(data) => data.encode(&mut buffer, extra_data)?,
2342 #[cfg(feature = "format_trade_routes")] RFileDecoded::TradeRoutes(data) => data.encode(&mut buffer, extra_data)?,
2343 #[cfg(feature = "format_uic")] RFileDecoded::UIC(data) => data.encode(&mut buffer, extra_data)?,
2344 #[cfg(feature = "format_unit_variant")] RFileDecoded::UnitVariant(data) => data.encode(&mut buffer, extra_data)?,
2345 RFileDecoded::Unknown(data) => data.encode(&mut buffer, extra_data)?,
2346 RFileDecoded::Video(data) => data.encode(&mut buffer, extra_data)?,
2347 RFileDecoded::VMD(data) => data.encode(&mut buffer, extra_data)?,
2348 RFileDecoded::WSModel(data) => data.encode(&mut buffer, extra_data)?,
2349 }
2350
2351 buffer
2352 },
2353 RFileInnerData::Cached(data) => {
2354 already_encoded = true;
2355 data.to_vec()
2356 },
2357 RFileInnerData::OnDisk(data) => {
2358 previously_undecoded = true;
2359 data.read()?
2360 },
2361 };
2362
2363 // If the RFile was already decoded.
2364 if previously_decoded {
2365 if move_decoded_to_cache {
2366 if return_data {
2367 self.data = RFileInnerData::Cached(encoded.to_vec());
2368 Ok(Some(encoded))
2369 } else {
2370 self.data = RFileInnerData::Cached(encoded);
2371 Ok(None)
2372 }
2373 } else if return_data {
2374 Ok(Some(encoded))
2375 } else {
2376 Ok(None)
2377 }
2378 }
2379
2380 // If the RFile was not even loaded.
2381 else if previously_undecoded {
2382 if move_undecoded_to_cache {
2383 if return_data {
2384 self.data = RFileInnerData::Cached(encoded.to_vec());
2385 Ok(Some(encoded))
2386 } else {
2387 self.data = RFileInnerData::Cached(encoded);
2388 Ok(None)
2389 }
2390 } else if return_data {
2391 Ok(Some(encoded))
2392 } else {
2393 Ok(None)
2394 }
2395 }
2396
2397 // If the RFile was already encoded and loaded.
2398 else if already_encoded && return_data {
2399 Ok(Some(encoded))
2400 } else {
2401 Ok(None)
2402 }
2403 }
2404
2405 /// This function loads the data of an RFile to memory if it's not yet loaded.
2406 ///
2407 /// If it has already been loaded either to cache, or for decoding, this does nothing.
2408 pub fn load(&mut self) -> Result<()> {
2409 let loaded = match &self.data {
2410 RFileInnerData::Decoded(_) |
2411 RFileInnerData::Cached(_) => return Ok(()),
2412 RFileInnerData::OnDisk(data) => data.read()?,
2413 };
2414
2415 // Piece of code to find text files we do not support yet. Needs enabling the content_inspector crate.
2416 #[cfg(feature = "enable_content_inspector")]
2417 if self.file_type() == FileType::Unknown && !loaded.is_empty() && content_inspector::inspect(&loaded).is_text() {
2418 dbg!(self.path_in_container_raw());
2419 }
2420
2421 self.data = RFileInnerData::Cached(loaded);
2422 Ok(())
2423 }
2424
2425 /// This function returns the size in bytes of the RFile's data as stored (compressed or encrypted if it is), if it's known
2426 /// without loading it: the stored size for data still on disk, the length for cached data, and `None` for decoded data.
2427 ///
2428 /// Patch packs use empty files to remove files of the packs below them, which this finds without reading them.
2429 pub fn stored_size(&self) -> Option<u64> {
2430 match &self.data {
2431 RFileInnerData::OnDisk(data) => Some(data.size),
2432 RFileInnerData::Cached(data) => Some(data.len() as u64),
2433 RFileInnerData::Decoded(_) => None,
2434 }
2435 }
2436
2437 /// This function returns a copy of the `Last modified date` of this RFile, if any.
2438 pub fn timestamp(&self) -> Option<u64> {
2439 self.timestamp
2440 }
2441
2442 /// This function returns a copy of the FileType of this RFile.
2443 pub fn file_type(&self) -> FileType {
2444 self.file_type
2445 }
2446
2447 /// This function returns the file name if this RFile, if it has one.
2448 pub fn file_name(&self) -> Option<&str> {
2449 self.path_in_container_raw().split('/').next_back()
2450 }
2451
2452 /// This function returns the file name of the container this RFile originates from, if any.
2453 pub fn container_name(&self) -> &Option<String> {
2454 &self.container_name
2455 }
2456
2457 /// This function returns the [ContainerPath] corresponding to this file.
2458 pub fn path_in_container(&self) -> ContainerPath {
2459 ContainerPath::File(self.path.to_owned())
2460 }
2461
2462 /// This function returns the [ContainerPath] corresponding to this file as an [&str].
2463 pub fn path_in_container_raw(&self) -> &str {
2464 &self.path
2465 }
2466
2467 /// This function returns the [ContainerPath] corresponding to this file as a [Vec] of [&str].
2468 pub fn path_in_container_split(&self) -> Vec<&str> {
2469 self.path.split('/').collect()
2470 }
2471
2472 /// This function the *table_name* of this file (the folder that contains this file) if this file is a DB table.
2473 ///
2474 /// It returns None of the file provided is not a DB Table.
2475 pub fn db_table_name_from_path(&self) -> Option<&str> {
2476 let split_path = self.path.split('/').collect::<Vec<_>>();
2477 let start_lower = split_path[0].to_lowercase();
2478 if split_path.len() == 3 && (start_lower == "db" || start_lower == "ceo_db") {
2479 Some(split_path[1])
2480 } else {
2481 None
2482 }
2483 }
2484
2485 /// This function sets the [ContainerPath] of the provided RFile to the provided path..
2486 pub fn set_path_in_container_raw(&mut self, path: &str) {
2487 self.path = path.to_owned();
2488 }
2489
2490 /// This function returns if the RFile can be compressed or not.
2491 pub fn is_compressible(&self, game_info: &GameInfo) -> bool {
2492 !game_info.compression_formats_supported().is_empty() &&
2493
2494 // These files are needed in plain text for this lib to read them.
2495 self.file_name() != Some(RESERVED_NAME_DEPENDENCIES_MANAGER_V2) &&
2496 self.file_name() != Some(RESERVED_NAME_DEPENDENCIES_MANAGER) &&
2497 self.file_name() != Some(RESERVED_NAME_SETTINGS) &&
2498 self.file_name() != Some(RESERVED_NAME_NOTES) &&
2499
2500 // These files either do not benefit from compression (video), may cause issues due to compression (audio not working)
2501 // or may cause overhead due to decompression (models).
2502 !matches!(self.file_type, FileType::Audio | FileType::Dat | FileType::RigidModel | FileType::SoundBank | FileType::Video) &&
2503
2504 // We can only compress files if the game supports them. And only in WH3 (and newer games?) is the table compression bug fixed.
2505 (
2506 !matches!(self.file_type, FileType::DB | FileType::Loc) || (
2507 game_info.key() != KEY_PHARAOH_DYNASTIES &&
2508 game_info.key() != KEY_PHARAOH &&
2509 game_info.key() != KEY_TROY &&
2510 game_info.key() != KEY_THREE_KINGDOMS &&
2511 game_info.key() != KEY_WARHAMMER_2
2512 )
2513 )
2514 }
2515
2516 /// This function guesses the [`FileType`] of the provided RFile and stores it on it for later queries.
2517 ///
2518 /// The way it works is: first it tries to guess it by extension (fast), then by full path (not as fast), then by data (slow and it may fail on lazy-loaded files).
2519 ///
2520 /// This may fail for some files, so if you doubt set the type manually.
2521 pub fn guess_file_type(&mut self) -> Result<()> {
2522
2523 // First, try with extensions.
2524 let path = self.path.to_lowercase();
2525
2526 if path.ends_with(pack::EXTENSION) {
2527 self.file_type = FileType::Pack;
2528 }
2529
2530 else if path.ends_with(loc::EXTENSION) {
2531 self.file_type = FileType::Loc;
2532 }
2533
2534 else if path.ends_with(rigidmodel::EXTENSION) {
2535 self.file_type = FileType::RigidModel
2536 }
2537
2538 else if path.ends_with(detection::animpack::EXTENSION) {
2539 self.file_type = FileType::AnimPack
2540 }
2541
2542 else if path.ends_with(detection::anim::EXTENSION) {
2543 self.file_type = FileType::Anim
2544 }
2545
2546 else if path.ends_with(video::EXTENSION) {
2547 self.file_type = FileType::Video;
2548 }
2549
2550 else if path.ends_with(detection::dat::EXTENSION) {
2551 self.file_type = FileType::Dat;
2552 }
2553
2554 else if path.ends_with(detection::font::EXTENSION) {
2555 self.file_type = FileType::Font;
2556 }
2557
2558 else if detection::audio::EXTENSIONS.iter().any(|x| path.ends_with(x)) {
2559 self.file_type = FileType::Audio;
2560 }
2561
2562 // TODO: detect bin files for maps and tile maps.
2563 else if bmd::EXTENSIONS.iter().any(|x| path.ends_with(x)) {
2564 self.file_type = FileType::BMD;
2565 }
2566
2567 else if bmd_vegetation::EXTENSIONS.iter().any(|x| path.ends_with(x)) {
2568 self.file_type = FileType::BMDVegetation;
2569 }
2570
2571 else if path.ends_with(detection::sound_bank::EXTENSION) {
2572 self.file_type = FileType::SoundBank;
2573 }
2574
2575 else if detection::image::EXTENSIONS.iter().any(|x| path.ends_with(x)) {
2576 self.file_type = FileType::Image;
2577 }
2578
2579 else if cfg!(feature = "support_uic") && path.starts_with(detection::uic::BASE_PATH) && detection::uic::EXTENSIONS.iter().any(|x| path.ends_with(x) || !path.contains('.')) {
2580 self.file_type = FileType::UIC;
2581 }
2582
2583 else if path.ends_with(text::EXTENSION_VMD.0) {
2584 self.file_type = FileType::VMD;
2585 }
2586
2587 else if path.ends_with(text::EXTENSION_WSMODEL.0) {
2588 self.file_type = FileType::WSModel;
2589 }
2590
2591 else if text::EXTENSIONS.iter().any(|(x, _)| path.ends_with(x)) {
2592 self.file_type = FileType::Text;
2593 }
2594
2595 else if path.ends_with(detection::unit_variant::EXTENSION) {
2596 self.file_type = FileType::UnitVariant
2597 }
2598
2599 else if path == detection::group_formations::PATH {
2600 self.file_type = FileType::GroupFormations;
2601 }
2602
2603 else if esf::EXTENSIONS.iter().any(|x| path.ends_with(x)) {
2604 self.file_type = FileType::ESF;
2605 }
2606
2607 // If that failed, try types that need to be in a specific path.
2608 else if detection::matched_combat::BASE_PATHS.iter().any(|x| path.starts_with(*x)) && path.ends_with(detection::matched_combat::EXTENSION) {
2609 self.file_type = FileType::MatchedCombat;
2610 }
2611
2612 else if path.starts_with(detection::anims_table::BASE_PATH) && path.ends_with(detection::anims_table::EXTENSION) {
2613 self.file_type = FileType::AnimsTable;
2614 }
2615
2616 else if path.ends_with(detection::anim_fragment_battle::EXTENSION_OLD) || (path.starts_with(detection::anim_fragment_battle::BASE_PATH) && path.contains(detection::anim_fragment_battle::MID_PATH) && path.ends_with(detection::anim_fragment_battle::EXTENSION_NEW)) {
2617 self.file_type = FileType::AnimFragmentBattle;
2618 }
2619
2620 // If that failed, check if it's in a folder which is known to only have specific files.
2621 // Microoptimization: check the path before using the regex. Regex is very, VERY slow.
2622 else if (path.starts_with("db/") && REGEX_DB.is_match(&path)) || (path.starts_with("ceo_db/") && REGEX_CEO_DB.is_match(&path)) {
2623 self.file_type = FileType::DB;
2624 }
2625
2626 else if path.ends_with(detection::portrait_settings::EXTENSION) && REGEX_PORTRAIT_SETTINGS.is_match(&path) {
2627 self.file_type = FileType::PortraitSettings;
2628 }
2629
2630 else if path.ends_with(detection::atlas::EXTENSION) {
2631 self.file_type = FileType::Atlas;
2632 }
2633
2634 else if path.ends_with(detection::hlsl_compiled::EXTENSION) {
2635 self.file_type = FileType::HlslCompiled;
2636 }
2637
2638 else if path.ends_with(detection::trade_routes::EXTENSION) {
2639 self.file_type = FileType::TradeRoutes;
2640 }
2641
2642 // If we reach this... we're clueless. Leave it unknown.
2643 else {
2644 self.file_type = FileType::Unknown;
2645 }
2646
2647 Ok(())
2648 }
2649
2650 /// This function allows to import a TSV file on the provided Path into a binary database file.
2651 ///
2652 /// It requires the path on disk of the TSV file and the Schema to use. Schema is only needed for DB tables.
2653 pub fn tsv_import_from_path(path: &Path, schema: &Option<Schema>) -> Result<Self> {
2654
2655 // We want the reader to have no quotes, tab as delimiter and custom headers, because otherwise
2656 // Excel, Libreoffice and all the programs that edit this kind of files break them on save.
2657 let mut reader = ReaderBuilder::new()
2658 .delimiter(b'\t')
2659 .quoting(false)
2660 .has_headers(true)
2661 .flexible(true)
2662 .from_path(path)?;
2663
2664 // If we successfully load the TSV file into a reader, check the first line to get the column list and order.
2665 let field_order = reader.headers()?
2666 .iter()
2667 .enumerate()
2668 .map(|(x, y)| (x as u32, y.to_owned()))
2669 .collect::<HashMap<u32, String>>();
2670
2671 // Get the record iterator so we can check the metadata from the second row.
2672 let mut records = reader.records();
2673 let (table_type, table_version, file_path) = match records.next() {
2674 Some(Ok(record)) => {
2675 let metadata = match record.get(0) {
2676 Some(metadata) => metadata.split(';').map(|x| x.to_owned()).collect::<Vec<String>>(),
2677 None => return Err(RLibError::ImportTSVWrongTypeTable),
2678 };
2679
2680 let table_type = match metadata.first() {
2681 Some(table_type) => {
2682 let mut table_type = table_type.to_owned();
2683 if table_type.starts_with('#') {
2684 table_type.remove(0);
2685 }
2686 table_type
2687 },
2688 None => return Err(RLibError::ImportTSVWrongTypeTable),
2689 };
2690
2691 let table_version = match metadata.get(1) {
2692 Some(table_version) => table_version.parse::<i32>().map_err(|_| RLibError::ImportTSVInvalidVersion)?,
2693 None => return Err(RLibError::ImportTSVInvalidVersion),
2694 };
2695
2696 let file_path = match metadata.get(2) {
2697 Some(file_path) => file_path.replace('\\', "/"),
2698 None => return Err(RLibError::ImportTSVInvalidOrMissingPath),
2699 };
2700
2701 (table_type, table_version, file_path)
2702 }
2703 Some(Err(_)) |
2704 None => return Err(RLibError::ImportTSVIncorrectRow(1, 0)),
2705 };
2706
2707 // Once we get the metadata, we know what kind of file we have. Create it and pass the records.
2708 let decoded = match &*table_type {
2709 loc::TSV_NAME_LOC | loc::TSV_NAME_LOC_OLD => {
2710 let decoded = Loc::tsv_import(records, &field_order)?;
2711 RFileDecoded::Loc(decoded)
2712 }
2713
2714 // Any other name is assumed to be a db table.
2715 _ => {
2716 match schema {
2717 Some(schema) => {
2718 let decoded = DB::tsv_import(records, &field_order, schema, &table_type, table_version)?;
2719 RFileDecoded::DB(decoded)
2720 },
2721 None => return Err(RLibError::SchemaNotProvided),
2722 }
2723 }
2724 };
2725
2726 let rfile = RFile::new_from_decoded(&decoded, 0, &file_path);
2727 Ok(rfile)
2728 }
2729
2730 /// This function allows to export a RFile into a TSV file on disk.
2731 ///
2732 /// Only supported for DB and Loc files.
2733 pub fn tsv_export_to_path(&mut self, path: &Path, schema: &Schema, keys_first: bool) -> Result<()> {
2734
2735 // Sanitize the path before creating the file
2736 let sanitized_path = sanitize_path(path);
2737
2738 // Make sure the folder actually exists.
2739 let mut folder_path = sanitized_path.to_path_buf();
2740 folder_path.pop();
2741 DirBuilder::new().recursive(true).create(&folder_path)?;
2742
2743 // We want the writer to have no quotes, tab as delimiter and custom headers, because otherwise
2744 // Excel, Libreoffice and all the programs that edit this kind of files break them on save.
2745 let mut writer = WriterBuilder::new()
2746 .delimiter(b'\t')
2747 .quote_style(QuoteStyle::Never)
2748 .has_headers(false)
2749 .flexible(true)
2750 .from_path(&sanitized_path)?;
2751
2752 let mut extra_data = DecodeableExtraData::default();
2753 extra_data.set_schema(Some(schema));
2754
2755 let extra_data = Some(extra_data);
2756
2757 // If it fails in decoding, delete the tsv file.
2758 let file = self.decode(&extra_data, false, true);
2759 if let Err(error) = file {
2760 let _ = std::fs::remove_file(&sanitized_path);
2761 return Err(error);
2762 }
2763
2764 let file = match file?.unwrap() {
2765 RFileDecoded::DB(table) => table.tsv_export(&mut writer, self.path_in_container_raw(), keys_first),
2766 RFileDecoded::Loc(table) => table.tsv_export(&mut writer, self.path_in_container_raw()),
2767 _ => Err(RLibError::ExportTSVUnsupportedFileType),
2768 };
2769
2770 // If the tsv export failed, delete the tsv file.
2771 if file.is_err() {
2772 let _ = std::fs::remove_file(&sanitized_path);
2773 }
2774
2775 file
2776 }
2777
2778 /// This function tries to merge multiple files into one.
2779 ///
2780 /// All files must be of the same type and said type must support merging.
2781 pub fn merge(sources: &[&Self], path: &str) -> Result<Self> {
2782 if sources.len() <= 1 {
2783 return Err(RLibError::RFileMergeOnlyOneFileProvided);
2784 }
2785
2786 let mut file_types = sources.iter().map(|file| file.file_type()).collect::<Vec<_>>();
2787 file_types.sort();
2788 file_types.dedup();
2789
2790 if file_types.len() > 1 {
2791 return Err(RLibError::RFileMergeDifferentTypes);
2792 }
2793
2794 match file_types[0] {
2795 FileType::DB => {
2796 let files = sources.iter().filter_map(|file| if let Ok(RFileDecoded::DB(table)) = file.decoded() { Some(table) } else { None }).collect::<Vec<_>>();
2797 let data = RFileDecoded::DB(DB::merge(&files)?);
2798 Ok(Self::new_from_decoded(&data, current_time()?, path))
2799 },
2800 FileType::Loc => {
2801 let files = sources.iter().filter_map(|file| if let Ok(RFileDecoded::Loc(table)) = file.decoded() { Some(table) } else { None }).collect::<Vec<_>>();
2802 let data = RFileDecoded::Loc(Loc::merge(&files)?);
2803 Ok(Self::new_from_decoded(&data, current_time()?, path))
2804 },
2805 _ => Err(RLibError::RFileMergeNotSupportedForType(file_types[0].to_string())),
2806 }
2807 }
2808
2809 /// This function tries to update a file to a new version of the same file's format.
2810 ///
2811 /// Files used by this function are expected to be pre-decoded.
2812 pub fn update(&mut self, definition: &Option<Definition>) -> Result<()> {
2813 match self.decoded_mut() {
2814 Ok(RFileDecoded::DB(file)) => match definition {
2815 Some(definition) => file.update(definition),
2816 None => return Err(RLibError::RawTableMissingDefinition),
2817 }
2818 _ => return Err(RLibError::FileNotDecoded(self.path_in_container_raw().to_string())),
2819 }
2820
2821 Ok(())
2822 }
2823
2824 /// This function returns the data hash of the file.
2825 pub fn data_hash(&mut self, extra_data: &Option<EncodeableExtraData>) -> Result<u64> {
2826 Ok(match self.data {
2827 RFileInnerData::Decoded(_) => checksum(CrcAlgorithm::Crc32Iscsi, &self.encode(extra_data, false, false, true)?.unwrap()),
2828 RFileInnerData::Cached(ref data) => checksum(CrcAlgorithm::Crc32Iscsi, data),
2829 RFileInnerData::OnDisk(ref on_disk) => checksum(CrcAlgorithm::Crc32Iscsi, &on_disk.read()?),
2830 })
2831 }
2832
2833 /// Sanitizes a destination path and creates a file with the sanitized path.
2834 /// Logs a message if the filename was changed due to invalid Windows characters.
2835 pub fn sanitize_and_create_file(&mut self, destination_path: &Path, extra_data: &Option<EncodeableExtraData>) -> Result<PathBuf> {
2836 let sanitized_destination_path = sanitize_path(destination_path);
2837
2838 if sanitized_destination_path != destination_path {
2839 warn!("Filename sanitized from '{}' to '{}' due to invalid Windows characters",
2840 destination_path.to_owned().file_name().unwrap_or_default().to_string_lossy(),
2841 sanitized_destination_path.file_name().unwrap_or_default().to_string_lossy());
2842 }
2843
2844 // Encode first, then create the destination file. This way, if the source happens to be
2845 // the same path we're writing to (e.g. MyMod Import/Export), we read the source bytes
2846 // before File::create truncates it. Avoids needing to pre-load OnDisk files into memory.
2847 let data = self.encode(extra_data, false, false, true)?.unwrap();
2848 let mut file = BufWriter::new(File::create(&sanitized_destination_path)?);
2849 file.write_all(&data)?;
2850 Ok(sanitized_destination_path)
2851 }
2852
2853 /// Function to encode a file using data from a external path, effectively replacing its data.
2854 /// without replacing the file's metadata.
2855 ///
2856 /// NOTE: If TSV is detected and fails to import, this returns an error.
2857 pub fn encode_from_external_data(&mut self, schema: &Option<Schema>, external_path: &Path) -> Result<()> {
2858
2859 let mut file = BufReader::new(File::open(external_path)?);
2860 let mut data = vec![];
2861 file.read_to_end(&mut data)?;
2862
2863 // If we're dealing with a TSV, make sure to import it before setting up the data.
2864 match external_path.extension() {
2865 Some(extension) => {
2866 if extension.to_string_lossy() == "tsv" {
2867 match RFile::tsv_import_from_path(external_path, schema) {
2868 Ok(rfile) => self.set_decoded(rfile.decoded()?.clone())?,
2869 Err(_) => self.set_cached(&data),
2870 }
2871 } else {
2872 self.set_cached(&data);
2873 }
2874 }
2875 None => self.set_cached(&data),
2876 }
2877
2878 // If they're tables, make sure they're left decoded in memory.
2879 if self.file_type() == FileType::DB || self.file_type() == FileType::Loc {
2880 if let Some(ref schema) = schema {
2881 let mut extra_data = DecodeableExtraData::default();
2882 extra_data.set_schema(Some(schema));
2883 let extra_data = Some(extra_data);
2884 let _ = self.decode(&extra_data, true, false);
2885 }
2886 }
2887
2888 Ok(())
2889 }
2890}
2891
2892impl OnDisk {
2893
2894 /// This function tries to read and return the raw data of an RFile.
2895 ///
2896 /// This returns the data uncompressed and unencrypted.
2897 fn read(&self) -> Result<Vec<u8>> {
2898
2899 // Date check, to ensure the source file or container hasn't been modified since we got the indexes to read it.
2900 let mut file = BufReader::new(File::open(&self.path)?);
2901 let timestamp = last_modified_time_from_file(file.get_ref())?;
2902 if timestamp != self.timestamp {
2903 return Err(RLibError::FileSourceChanged(self.path.clone()));
2904 }
2905
2906 // Read the data from disk.
2907 let mut data = vec![0; self.size as usize];
2908 file.seek(SeekFrom::Start(self.start))?;
2909 file.read_exact(&mut data)?;
2910
2911 // If the data is encrypted, decrypt it.
2912 if let Some(pfh_version) = self.is_encrypted {
2913 data = Cursor::new(data).decrypt(pfh_version)?;
2914 }
2915
2916 // If the data is compressed. decompress it.
2917 if self.is_compressed {
2918 data = match self.lz4_block_uncompressed_size {
2919 Some(uncompressed_size) => data.as_slice().decompress_lz4_block(uncompressed_size as usize)?,
2920 None => data.as_slice().decompress()?,
2921 };
2922 }
2923
2924 Ok(data)
2925 }
2926}
2927
2928impl ContainerPath {
2929
2930 /// This function returns true if the provided [ContainerPath] corresponds to a file.
2931 pub fn is_file(&self) -> bool {
2932 matches!(self, ContainerPath::File(_))
2933 }
2934
2935 /// This function returns true if the provided [ContainerPath] corresponds to a folder.
2936 pub fn is_folder(&self) -> bool {
2937 matches!(self, ContainerPath::Folder(_))
2938 }
2939
2940 /// This function returns true if the provided [ContainerPath] corresponds to a root Pack.
2941 pub fn is_pack(&self) -> bool {
2942 match self {
2943 ContainerPath::Folder(path) => path.is_empty(),
2944 _ => false,
2945 }
2946 }
2947
2948 /// This function returns a reference to the path stored within the provided [ContainerPath].
2949 pub fn path_raw(&self) -> &str {
2950 match self {
2951 Self::File(ref path) => path,
2952 Self::Folder(ref path) => path,
2953 }
2954 }
2955
2956 /// This function returns the last item of the provided [ContainerPath], if any.
2957 pub fn name(&self) -> Option<&str> {
2958 self.path_raw().split('/').next_back()
2959 }
2960
2961 /// This function the *table_name* of this file (the folder that contains this file) if this file is a DB table.
2962 ///
2963 /// It returns None of the file provided is not a DB Table.
2964 pub fn db_table_name_from_path(&self) -> Option<&str> {
2965 let split_path = self.path_raw().split('/').collect::<Vec<_>>();
2966 let start_lower = split_path[0].to_lowercase();
2967 if split_path.len() == 3 && (start_lower == "db" || start_lower == "ceo_db") {
2968 Some(split_path[1])
2969 } else {
2970 None
2971 }
2972 }
2973
2974 /// This function returns the `db/` and `ceo_db/` folder paths for the provided *table_name*.
2975 ///
2976 /// Use it with `files_by_paths` instead of hardcoding the `db/` prefix.
2977 pub fn db_table_folders(table_name: &str) -> Vec<ContainerPath> {
2978 vec![
2979 ContainerPath::Folder(format!("db/{table_name}")),
2980 ContainerPath::Folder(format!("ceo_db/{table_name}")),
2981 ]
2982 }
2983
2984 /// This function returns the path of the parent folder of the provided [ContainerPath].
2985 ///
2986 /// If the provided [ContainerPath] corresponds to a Container root, the path returned will be the current one.
2987 pub fn parent_path(&self) -> String {
2988 match self {
2989 ContainerPath::File(path) |
2990 ContainerPath::Folder(path) => {
2991 if path.is_empty() || (path.chars().count() == 1 && path.starts_with('/')) {
2992 path.to_owned()
2993 } else {
2994 let mut path_split = path.split('/').collect::<Vec<_>>();
2995 path_split.pop();
2996 path_split.join("/")
2997 }
2998 },
2999 }
3000 }
3001
3002 /// This function removes collided items from the provided list of [ContainerPath].
3003 ///
3004 /// This means, if you have a file and a folder containing the file, it removes the file.
3005 pub fn dedup(paths: &[Self]) -> Vec<Self> {
3006
3007 // As this operation can get very expensive very fast, we first check if we have a path containing the root of the container.
3008 let root = ContainerPath::Folder("".to_string());
3009 if paths.contains(&root) {
3010 return vec![root; 1];
3011 }
3012
3013 // If we don't have the root of the container, second optimization: check if we have at least one folder.
3014 // If not, we just need to dedup the file list.
3015 if !paths.par_iter().any(|item| matches!(item, ContainerPath::Folder(_))) {
3016 let mut paths = paths.to_vec();
3017 paths.sort();
3018 paths.dedup();
3019 return paths;
3020 }
3021
3022 // If we reached this point, we have a mix of files and folders, or only folders.
3023 // In any case, we need to filter them, then dedup the resultant paths.
3024 let items_to_remove = paths.par_iter().filter(|item_type_to_add| {
3025 match item_type_to_add {
3026
3027 // If it's a file, we have to check if there is a folder containing it.
3028 ContainerPath::File(ref path_to_add) => {
3029 !paths.par_iter()
3030 .any(|item_type| {
3031
3032 // If the other one is a folder that contains it, dont add it.
3033 item_type.is_folder() && path_to_add.starts_with(item_type.path_raw())
3034 })
3035 }
3036
3037 // If it's a folder, we have to check if there is already another folder containing it.
3038 ContainerPath::Folder(ref path_to_add) => {
3039 !paths.par_iter()
3040 .any(|item_type| {
3041
3042 // If the other one is a folder that contains it, dont add it.
3043 let path = item_type.path_raw();
3044 item_type.is_folder() && path_to_add.starts_with(path) && path_to_add.len() > path.len() && path_to_add.is_char_boundary(path.len()) && path_to_add.as_bytes()[path.len()] == b'/'
3045 })
3046 }
3047 }
3048 }).cloned().collect::<Vec<Self>>();
3049
3050 let mut paths = paths.to_vec();
3051 paths.retain(|x| items_to_remove.contains(x));
3052 paths.sort();
3053 paths.dedup();
3054 paths
3055 }
3056}
3057
3058impl Ord for ContainerPath {
3059 fn cmp(&self, other: &Self) -> Ordering {
3060 match self {
3061 ContainerPath::File(a) => match other {
3062 ContainerPath::File(b) => a.cmp(b),
3063 ContainerPath::Folder(_) => Ordering::Less,
3064 }
3065 ContainerPath::Folder(a) => match other {
3066 ContainerPath::File(_) => Ordering::Greater,
3067 ContainerPath::Folder(b) => a.cmp(b),
3068 }
3069 }
3070 }
3071}
3072
3073impl PartialOrd for ContainerPath {
3074 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3075 Some(self.cmp(other))
3076 }
3077}
3078
3079impl Display for FileType {
3080 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3081 match self {
3082 FileType::Anim => write!(f, "Anim"),
3083 FileType::AnimFragmentBattle => write!(f, "AnimFragmentBattle"),
3084 FileType::AnimPack => write!(f, "AnimPack"),
3085 FileType::AnimsTable => write!(f, "AnimsTable"),
3086 FileType::Atlas => write!(f, "Atlas"),
3087 FileType::Audio => write!(f, "Audio"),
3088 FileType::BMD => write!(f, "Battle Map Definition"),
3089 FileType::BMDVegetation => write!(f, "Battle Map Definition (Vegetation)"),
3090 FileType::Dat => write!(f, "Dat Audio File"),
3091 FileType::DB => write!(f, "DB Table"),
3092 FileType::ESF => write!(f, "ESF"),
3093 FileType::Font => write!(f, "Font"),
3094 FileType::HlslCompiled => write!(f, "Hlsl Compiled"),
3095 FileType::GroupFormations => write!(f, "Group Formations"),
3096 FileType::Image => write!(f, "Image"),
3097 FileType::Loc => write!(f, "Loc Table"),
3098 FileType::MatchedCombat => write!(f, "Matched Combat"),
3099 FileType::Pack => write!(f, "PackFile"),
3100 FileType::PortraitSettings => write!(f, "Portrait Settings"),
3101 FileType::RigidModel => write!(f, "RigidModel"),
3102 FileType::SoundBank => write!(f, "SoundBank"),
3103 FileType::Text => write!(f, "Text"),
3104 FileType::TradeRoutes => write!(f, "Trade Routes"),
3105 FileType::UIC => write!(f, "UI Component"),
3106 FileType::UnitVariant => write!(f, "Unit Variant"),
3107 FileType::Unknown => write!(f, "Unknown"),
3108 FileType::Video => write!(f, "Video"),
3109 FileType::VMD => write!(f, "VMD"),
3110 FileType::WSModel => write!(f, "WSModel"),
3111 }
3112 }
3113}
3114
3115impl From<&str> for FileType {
3116 fn from(value: &str) -> Self {
3117 match value {
3118 "Anim" => FileType::Anim,
3119 "AnimFragmentBattle" => FileType::AnimFragmentBattle,
3120 "AnimPack" => FileType::AnimPack,
3121 "AnimsTable" => FileType::AnimsTable,
3122 "Atlas" => FileType::Atlas,
3123 "Audio" => FileType::Audio,
3124 "BMD" => FileType::BMD,
3125 "BMDVegetation" => FileType::BMDVegetation,
3126 "Dat" => FileType::Dat,
3127 "DB" => FileType::DB,
3128 "ESF" => FileType::ESF,
3129 "Font" => FileType::Font,
3130 "HlslCompiled" => FileType::HlslCompiled,
3131 "GroupFormations" => FileType::GroupFormations,
3132 "Image" => FileType::Image,
3133 "Loc" => FileType::Loc,
3134 "MatchedCombat" => FileType::MatchedCombat,
3135 "Pack" => FileType::Pack,
3136 "PortraitSettings" => FileType::PortraitSettings,
3137 "RigidModel" => FileType::RigidModel,
3138 "SoundBank" => FileType::SoundBank,
3139 "Text" => FileType::Text,
3140 "TradeRoutes" => FileType::TradeRoutes,
3141 "UIC" => FileType::UIC,
3142 "UnitVariant" => FileType::UnitVariant,
3143 "Unknown" => FileType::Unknown,
3144 "Video" => FileType::Video,
3145 "VMD" => FileType::VMD,
3146 "WSModel" => FileType::WSModel,
3147 _ => unimplemented!(),
3148 }
3149 }
3150}
3151
3152impl From<FileType> for String {
3153 fn from(value: FileType) -> String {
3154 match value {
3155 FileType::Anim => "Anim",
3156 FileType::AnimFragmentBattle => "AnimFragmentBattle",
3157 FileType::AnimPack => "AnimPack",
3158 FileType::AnimsTable => "AnimsTable",
3159 FileType::Atlas => "Atlas",
3160 FileType::Audio => "Audio",
3161 FileType::BMD => "BMD",
3162 FileType::BMDVegetation => "BMD Vegetation",
3163 FileType::Dat => "Dat",
3164 FileType::DB => "DB",
3165 FileType::ESF => "ESF",
3166 FileType::Font => "Font",
3167 FileType::HlslCompiled => "HlslCompiled",
3168 FileType::GroupFormations => "GroupFormations",
3169 FileType::Image => "Image",
3170 FileType::Loc => "Loc",
3171 FileType::MatchedCombat => "MatchedCombat",
3172 FileType::Pack => "Pack",
3173 FileType::PortraitSettings => "PortraitSettings",
3174 FileType::RigidModel => "RigidModel",
3175 FileType::SoundBank => "SoundBank",
3176 FileType::Text => "Text",
3177 FileType::TradeRoutes => "TradeRoutes",
3178 FileType::UIC => "UIC",
3179 FileType::UnitVariant => "UnitVariant",
3180 FileType::Unknown => "Unknown",
3181 FileType::Video => "Video",
3182 FileType::VMD => "VMD",
3183 FileType::WSModel => "WSModel",
3184 }.to_owned()
3185 }
3186}
3187
3188impl From<&RFileDecoded> for FileType {
3189 fn from(file: &RFileDecoded) -> Self {
3190 match file {
3191 #[cfg(feature = "format_anim")] RFileDecoded::Anim(_) => Self::Anim,
3192 #[cfg(feature = "format_anim_fragment_battle")] RFileDecoded::AnimFragmentBattle(_) => Self::AnimFragmentBattle,
3193 #[cfg(feature = "format_animpack")] RFileDecoded::AnimPack(_) => Self::AnimPack,
3194 #[cfg(feature = "format_anims_table")] RFileDecoded::AnimsTable(_) => Self::AnimsTable,
3195 #[cfg(feature = "format_atlas")] RFileDecoded::Atlas(_) => Self::Atlas,
3196 #[cfg(feature = "format_audio")] RFileDecoded::Audio(_) => Self::Audio,
3197 RFileDecoded::BMD(_) => Self::BMD,
3198 RFileDecoded::BMDVegetation(_) => Self::BMDVegetation,
3199 #[cfg(feature = "format_dat")] RFileDecoded::Dat(_) => Self::Dat,
3200 RFileDecoded::DB(_) => Self::DB,
3201 RFileDecoded::ESF(_) => Self::ESF,
3202 #[cfg(feature = "format_font")] RFileDecoded::Font(_) => Self::Font,
3203 #[cfg(feature = "format_hlsl_compiled")] RFileDecoded::HlslCompiled(_) => Self::HlslCompiled,
3204 #[cfg(feature = "format_group_formations")] RFileDecoded::GroupFormations(_) => Self::GroupFormations,
3205 #[cfg(feature = "format_image")] RFileDecoded::Image(_) => Self::Image,
3206 RFileDecoded::Loc(_) => Self::Loc,
3207 #[cfg(feature = "format_matched_combat")] RFileDecoded::MatchedCombat(_) => Self::MatchedCombat,
3208 RFileDecoded::Pack(_) => Self::Pack,
3209 #[cfg(feature = "format_portrait_settings")] RFileDecoded::PortraitSettings(_) => Self::PortraitSettings,
3210 RFileDecoded::RigidModel(_) => Self::RigidModel,
3211 #[cfg(feature = "format_sound_bank")] RFileDecoded::SoundBank(_) => Self::SoundBank,
3212 RFileDecoded::Text(_) => Self::Text,
3213 #[cfg(feature = "format_trade_routes")] RFileDecoded::TradeRoutes(_) => Self::TradeRoutes,
3214 #[cfg(feature = "format_uic")] RFileDecoded::UIC(_) => Self::UIC,
3215 #[cfg(feature = "format_unit_variant")] RFileDecoded::UnitVariant(_) => Self::UnitVariant,
3216 RFileDecoded::Unknown(_) => Self::Unknown,
3217 RFileDecoded::Video(_) => Self::Video,
3218 RFileDecoded::VMD(_) => Self::VMD,
3219 RFileDecoded::WSModel(_) => Self::WSModel,
3220 }
3221 }
3222}
3223
3224impl<'a> EncodeableExtraData<'a> {
3225
3226 /// This functions generates an EncodeableExtraData for a specific game.
3227 pub fn new_from_game_info(game_info: &'a GameInfo) -> Self {
3228 let mut extra_data = Self::default();
3229 extra_data.set_game_info(Some(game_info));
3230 extra_data.set_table_has_guid(*game_info.db_tables_have_guid());
3231 extra_data
3232 }
3233
3234 /// This functions generates an EncodeableExtraData for a specific game and settings.
3235 pub fn new_from_game_info_and_settings(game_info: &'a GameInfo, cf: CompressionFormat, disable_regen_table_guid: bool) -> EncodeableExtraData<'a> {
3236 let mut extra_data = EncodeableExtraData::new_from_game_info(game_info);
3237 extra_data.set_regenerate_table_guid(!disable_regen_table_guid);
3238 extra_data.set_compression_format(cf);
3239 extra_data
3240 }
3241}