use super::{Error, Result, parser};
use crate::bsa::{FilenameEncoding, NormalizedPath, decode_filename_lossy, normalize_lookup_path};
use crate::{BStr, BString};
use crate::{
Copied,
extract::{
ensure_parent_dir, output_path_decoded_into, output_path_into, write_file_atomically,
},
storage::Storage,
};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ArchiveInfo {
pub hash_offset: u32,
pub file_count: u32,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct EntryId(usize);
impl EntryId {
#[must_use]
pub const fn from_index(index: usize) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Entry {
path: BString,
lookup_path: BString,
record: FileRecord,
hash: u64,
}
impl Entry {
#[must_use]
pub fn path(&self) -> &BStr {
self.path.as_ref()
}
#[must_use]
pub fn file(&self) -> FileRecord {
self.record
}
#[must_use]
pub fn hash(&self) -> u64 {
self.hash
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FileRecord {
pub size: u32,
pub offset: u32,
}
#[derive(Clone, Debug)]
pub struct Archive {
storage: Storage,
info: ArchiveInfo,
entries: Vec<Entry>,
data_offset: usize,
lookup: HashMap<BString, usize>,
}
impl Archive {
pub fn from_vec(bytes: Vec<u8>) -> Result<Self> {
parser::parse(Storage::from_vec(bytes))
}
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
Self::from_vec(bytes.to_vec())
}
pub fn open_path(path: impl AsRef<Path>) -> Result<Self> {
parser::parse(Storage::open_path(path)?)
}
#[must_use]
pub fn info(&self) -> ArchiveInfo {
self.info
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn entries(&self) -> &[Entry] {
&self.entries
}
pub fn entries_with_ids(&self) -> impl Iterator<Item = (EntryId, &Entry)> {
self.entries
.iter()
.enumerate()
.map(|(index, entry)| (EntryId(index), entry))
}
#[must_use]
pub fn entry_by_id(&self, id: EntryId) -> Option<&Entry> {
self.entries.get(id.0)
}
pub fn entry_by_id_required(&self, id: EntryId) -> Result<&Entry> {
self.entry_by_id(id).ok_or(Error::OutOfBounds)
}
pub fn extract_entry_by_id(&self, id: EntryId, out: impl std::io::Write) -> Result<u64> {
self.extract_entry(self.entry_by_id_required(id)?, out)
}
#[must_use]
pub fn get(&self, path: impl AsRef<[u8]>) -> Option<&Entry> {
let normalized = normalize_lookup_path(path.as_ref());
self.lookup
.get(normalized.as_slice())
.map(|&index| &self.entries[index])
}
#[must_use]
pub fn get_normalized(&self, path: &NormalizedPath) -> Option<&Entry> {
self.lookup
.get(path.as_bytes())
.map(|&index| &self.entries[index])
}
pub fn get_required(&self, path: impl AsRef<[u8]>) -> Result<&Entry> {
let path = path.as_ref();
self.get(path)
.ok_or_else(|| Error::FileNotFound(BString::from(path)))
}
#[must_use]
pub fn contains(&self, path: impl AsRef<[u8]>) -> bool {
self.get(path).is_some()
}
#[must_use]
pub fn contains_normalized(&self, path: &NormalizedPath) -> bool {
self.get_normalized(path).is_some()
}
#[must_use]
pub fn archive_size(&self) -> usize {
self.storage.as_bytes().len()
}
pub fn read_entry_into(&self, entry: &Entry, out: &mut Vec<u8>) -> Result<()> {
let payload = self.entry_payload(entry)?;
out.try_reserve_exact(payload.len())?;
out.extend_from_slice(payload);
Ok(())
}
pub fn extract_entry(&self, entry: &Entry, mut out: impl std::io::Write) -> Result<u64> {
let payload = self.entry_payload(entry)?;
out.write_all(payload)?;
Ok(payload.len().try_into()?)
}
pub fn extract_entry_to_path(&self, entry: &Entry, path: impl AsRef<Path>) -> Result<u64> {
write_file_atomically(path.as_ref(), |file| self.extract_entry(entry, file))
}
pub fn read_entry(&self, entry: &Entry) -> Result<Vec<u8>> {
let mut out = Vec::new();
self.read_entry_into(entry, &mut out)?;
Ok(out)
}
pub fn read_file(&self, path: impl AsRef<[u8]>) -> Result<Option<Vec<u8>>> {
self.get(path)
.map(|entry| self.read_entry(entry))
.transpose()
}
pub fn read_file_required(&self, path: impl AsRef<[u8]>) -> Result<Vec<u8>> {
self.read_entry(self.get_required(path)?)
}
pub fn extract_file(
&self,
path: impl AsRef<[u8]>,
out: impl std::io::Write,
) -> Result<Option<u64>> {
self.get(path)
.map(|entry| self.extract_entry(entry, out))
.transpose()
}
pub fn extract_file_required(
&self,
path: impl AsRef<[u8]>,
out: impl std::io::Write,
) -> Result<u64> {
self.extract_entry(self.get_required(path)?, out)
}
pub fn extract_to(&self, target_dir: impl AsRef<Path>) -> Result<u64> {
let target_dir = target_dir.as_ref();
#[cfg(feature = "parallel")]
{
self.extract_to_parallel(target_dir)
}
#[cfg(not(feature = "parallel"))]
{
self.extract_to_sequential(target_dir)
}
}
pub fn extract_to_with_encoding(
&self,
target_dir: impl AsRef<Path>,
encoding: FilenameEncoding,
) -> Result<u64> {
let target_dir = target_dir.as_ref();
let mut written = 0u64;
let mut path = PathBuf::new();
let mut last_parent = PathBuf::new();
for entry in &self.entries {
output_path_decoded_into(&mut path, target_dir, entry.path(), |component| {
decode_filename_lossy(component, encoding)
})?;
ensure_parent_dir(&path, &mut last_parent)?;
written += self.extract_entry_to_path(entry, &path)?;
}
Ok(written)
}
fn extract_to_sequential(&self, target_dir: &Path) -> Result<u64> {
let mut written = 0u64;
let mut path = PathBuf::new();
let mut last_parent = PathBuf::new();
for entry in &self.entries {
output_path_into(&mut path, target_dir, entry.path())?;
ensure_parent_dir(&path, &mut last_parent)?;
written += self.extract_entry_to_path(entry, &path)?;
}
Ok(written)
}
#[cfg(feature = "parallel")]
fn extract_to_parallel(&self, target_dir: &Path) -> Result<u64> {
let paths = self.extract_output_paths(target_dir)?;
if crate::extract::has_duplicate_paths(&paths) {
return self.extract_to_sequential(target_dir);
}
crate::extract::ensure_parent_dirs(&paths)?;
self.entries
.par_iter()
.zip(paths.par_iter())
.map(|(entry, path)| self.extract_entry_to_path(entry, path))
.try_reduce(|| 0, |left, right| Ok(left + right))
}
#[cfg(feature = "parallel")]
fn extract_output_paths(&self, target_dir: &Path) -> Result<Vec<PathBuf>> {
let mut paths = Vec::new();
paths.try_reserve_exact(self.entries.len())?;
for entry in &self.entries {
let mut path = PathBuf::new();
output_path_into(&mut path, target_dir, entry.path())?;
paths.push(path);
}
Ok(paths)
}
pub(super) fn from_parts(
storage: Storage,
info: ArchiveInfo,
entries: Vec<Entry>,
data_offset: usize,
) -> Self {
let mut lookup = HashMap::with_capacity(entries.len());
for (index, entry) in entries.iter().enumerate() {
lookup.entry(entry.lookup_path.clone()).or_insert(index);
}
Self {
storage,
info,
entries,
data_offset,
lookup,
}
}
fn entry_payload<'a>(&'a self, entry: &Entry) -> Result<&'a [u8]> {
let relative: usize = entry.record.offset.try_into()?;
let start = self
.data_offset
.checked_add(relative)
.ok_or(Error::OutOfBounds)?;
let len: usize = entry.record.size.try_into()?;
self.storage
.as_bytes()
.get(start..start.checked_add(len).ok_or(Error::OutOfBounds)?)
.ok_or(Error::OutOfBounds)
}
}
impl Entry {
pub(super) fn new(path: BString, record: FileRecord, hash: u64) -> Self {
let lookup_path = BString::from(normalize_lookup_path(&path));
Self {
path,
lookup_path,
record,
hash,
}
}
}
impl TryFrom<Copied<'_>> for Archive {
type Error = Error;
fn try_from(value: Copied<'_>) -> Result<Self> {
Self::from_slice(value.0)
}
}