themelios_archive/
dirdat.rs

1//! Utilities for reading ED6 PC's LB DIR files.
2
3use gospel::read::{Reader, Le as _};
4use gospel::write::{Writer, Le as _};
5
6/// A name of a file in an archive.
7///
8/// Internally this is represented as a `[u8; 12]` usually denoting a 8.3 uppercase shift-jis encoded name, but
9/// the public interface treats it like a more normal looking string.
10#[derive(Clone, Copy, PartialEq, Eq)]
11pub struct Name([u8; 12]);
12
13impl std::ops::Deref for Name {
14	type Target = [u8; 12];
15
16	fn deref(&self) -> &Self::Target {
17		&self.0
18	}
19}
20
21impl Default for Name {
22	fn default() -> Self {
23		Self(*b"/_______.___")
24	}
25}
26
27impl std::fmt::Debug for Name {
28	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
29		write!(f, "Name({:?})", self.to_string())
30	}
31}
32
33impl std::fmt::Display for Name {
34	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
35		let name = cp932::decode_lossy(&self.0);
36		let name = name.to_lowercase();
37		if let Some((name, ext)) = name.split_once('.') {
38			write!(f, "{}.{}", name.trim_end_matches(' '), ext.trim_end_matches(' '))
39		} else {
40			f.write_str(name.trim_end_matches(' '))
41		}
42	}
43}
44
45impl TryFrom<String> for Name {
46	type Error = NameError;
47
48	fn try_from(value: String) -> Result<Self, Self::Error> {
49		Name::try_from(value.as_str())
50	}
51}
52
53impl TryFrom<&str> for Name {
54	type Error = NameError;
55
56	fn try_from(name: &str) -> Result<Self, Self::Error> {
57		let (_, name) = name.rsplit_once(['/', '\\']).unwrap_or(("", name));
58		let name = name.to_uppercase();
59		let (name, ext) = name.split_once('.').unwrap_or((&name, ""));
60		let name = cp932::encode(name).map_err(|_| NameError)?;
61		let ext = cp932::encode(ext).map_err(|_| NameError)?;
62		if name.len() > 8 || ext.len() > 3 { return Err(NameError); }
63		let mut o = *b"        .   ";
64		o[..name.len()].copy_from_slice(&name);
65		o[9..][..ext.len()].copy_from_slice(&ext);
66		Ok(Name(o))
67	}
68}
69
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct NameError;
73
74impl std::fmt::Display for NameError {
75	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
76		f.write_str("cannot convert to archive name")
77	}
78}
79
80impl std::error::Error for NameError {}
81
82/// An entry in a .dir file,
83///
84/// Only three of the fields are actually used by the games: `name`, `size`, and `offset`.
85#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub struct DirEntry {
87	/// The name of the file.
88	pub name: Name,
89	/// There are only three files in 3rd/dt29 where this field is nonzero.
90	/// In those cases, it looks like a timestamp pointing to 2009-08-12 21:58:33.
91	pub unk1: u32,
92	/// The size of the file data in the archive.
93	pub size: usize,
94	/// Unknown. In many cases it is equal to `size`, but not always.
95	/// In other cases it is a power of two that is often fairly consistent with adjacent files, but is wholly uncorrelated with any file sizes.
96	pub unk2: usize,
97	/// Usually equal to `size`, but in SC/dt31 it is bigger. The difference is filled with null bytes.
98	pub reserved_size: usize,
99	/// A unix timestamp, presumably when the file was last edited. Timezone is unknown.
100	pub timestamp: u32,
101	/// Offset in the .dat file where the data starts.
102	pub offset: usize,
103}
104
105/// Read the list of entries from a .dir file.
106///
107/// In many cases, .dir files contain a number of trailing entries named `/_______.___`.
108/// These entries are retained as well.
109pub fn read_dir(data: &[u8]) -> Result<Vec<DirEntry>, gospel::read::Error> {
110	let mut f = Reader::new(data);
111	f.check(b"LB DIR\x1A\0")?;
112	let count = f.u64()? as usize;
113
114	let mut items = Vec::with_capacity(count);
115
116	for _ in 0..count {
117		items.push(DirEntry {
118			name: Name(f.array::<12>()?),
119			unk1: f.u32()?,
120			size: f.u32()? as usize,
121			unk2: f.u32()? as usize,
122			reserved_size: f.u32()? as usize,
123			timestamp: f.u32()?,
124			offset: f.u32()? as usize,
125		});
126	}
127
128	Ok(items)
129}
130
131/// Writes a list of entries into a .dir file.
132pub fn write_dir(entries: &[DirEntry]) -> Vec<u8> {
133	let mut f = Writer::new();
134	f.slice(b"LB DIR\x1A\0");
135	f.u64(entries.len() as u64);
136
137	for e in entries {
138		f.array::<12>(e.name.0);
139		f.u32(e.unk1);
140		f.u32(e.size as u32);
141		f.u32(e.unk2 as u32);
142		f.u32(e.reserved_size as u32);
143		f.u32(e.timestamp);
144		f.u32(e.offset as u32);
145	}
146
147	f.finish().unwrap()
148}