Files
wad-reader/src/utils/helpers.rs

44 lines
1.1 KiB
Rust

use std::{
fs::File,
io::{self, Read},
path::Path,
};
/// Validates a WAD file to make sure that it is a legitimate file
///
/// Parameters:
/// - path: &str - Path to the WAD to validate
pub fn validate_wad(path: &str) -> io::Result<bool> {
let wad_file = Path::new(path);
// Check to see if the WAD exists
if !(wad_file.exists()) {
// Return back false because we didn't pass a valid file
return Ok(false);
}
// If the file exists open it and read the first 4 bytes
// of the file and see if we get "IWAD" or "PWAD"
let mut file = File::open(wad_file)?;
let mut magic = [0u8; 4];
file.read_exact(&mut magic)?;
// Now we return based on what we found
Ok(magic == *b"IWAD" || magic == *b"PWAD")
}
pub fn read_ascii(bytes: &[u8]) -> String {
std::str::from_utf8(&bytes[..bytes.len()])
.unwrap_or("")
.trim_end_matches('\0')
.to_string()
}
pub fn read_u32_le(bytes: &[u8]) -> u32 {
if bytes.len() < 4 {
0
} else {
u32::from_le_bytes(bytes[..4].try_into().unwrap())
}
}