1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Read-only MDD sources and retryable, all-or-error lazy volume initialization.
use std::io::Read as IoRead;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};
use memmap2::Mmap;
use crate::index::{Cache, Index, Lookup};
use crate::link::Chain;
use crate::reader::{Read, Reader};
use crate::record_block::Bytes;
use crate::{Error, Limits, Result};
/// Resource-path normalization used for MDD key lookup.
///
/// Normalization is not filesystem path validation or a traversal sandbox.
pub struct Resource<'a> {
/// Requested path before slash normalization and Unicode lowercasing.
pub path: &'a str,
}
impl Resource<'_> {
/// Return a lowercase backslash-separated key with one leading backslash.
///
/// Removes an initial `.\` after slash conversion. This does not resolve
/// parent-directory components or access the filesystem.
pub fn key(&self) -> String {
let path = self.path.replace('/', "\\");
let path = path
.strip_prefix(".\\")
.unwrap_or(&path)
.trim_start_matches('\\');
let mut key = String::with_capacity(path.len() + 1);
key.push('\\');
for character in path.chars() {
key.extend(character.to_lowercase());
}
key
}
}
impl std::fmt::Debug for Resource<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Resource")
.field("path_bytes", &self.path.len())
.finish_non_exhaustive()
}
}
/// A binary MDD resource source paired with its own immutable key index.
///
/// [`crate::Mdd::lookup`] returns raw resource bytes, not decoded article text.
/// The MDD header's text encoding describes keys, not arbitrary binary payloads.
pub struct Mdd<R = Reader<Mmap>, I = Index> {
reader: R,
index: I,
}
impl Mdd {
/// Open a memory-mapped MDD with default [`crate::Limits`].
///
/// Uses or creates a neighboring `.mdd.idx` index cache, including the
/// persistent lock sidecar and publication effects of [`crate::Cache::open`].
/// Record payloads remain lazily decoded.
///
/// # Errors
///
/// Returns source I/O, parsing or index-building errors. Cache I/O failures
/// are warned about and fall back to an in-memory index.
///
/// # Safety
/// The source must remain unmodified and untruncated while mapped.
/// Advisory locks alone do not establish this guarantee. Use
/// [`crate::Mdd::parse`] with owned bytes when immutability is uncertain.
pub unsafe fn open(path: &Path) -> Result<Self> {
let limits = Limits::default();
// SAFETY: The caller keeps the backing file immutable.
unsafe { Self::open_with(path, limits) }
}
/// Open a memory-mapped MDD with explicit component budgets.
///
/// Has the same cache-writing side effects as [`crate::Mdd::open`].
///
/// # Errors
///
/// Returns source, parsing or index-building errors, including exceeded
/// budgets. See [`crate::Mdd::open`] for cache-failure behavior.
///
/// # Safety
/// The source must remain unmodified and untruncated while mapped.
pub unsafe fn open_with(path: &Path, limits: Limits) -> Result<Self> {
// SAFETY: The caller keeps the backing file immutable.
let reader = unsafe { Reader::open_with(path, limits)? };
let index = Cache::new(path.with_extension("mdd.idx"), reader.entries(), limits).open()?;
Ok(Self { reader, index })
}
}
impl<B: AsRef<[u8]>> Mdd<Reader<B>> {
/// Parse resource bytes and build an index without filesystem I/O.
///
/// Uses default budgets and `fallback` as a missing title. For custom
/// budgets, construct a [`crate::Reader::with_limits`] reader and pass it to
/// [`crate::Mdd::new`].
///
/// # Errors
///
/// Propagates parsing and index-building errors. Damaged record blocks can
/// still fail when first accessed through [`crate::Mdd::lookup`].
///
/// ```
/// use wodix::Mdd;
///
/// let data = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/basic.mdd"));
/// let resources = Mdd::parse(data.as_slice(), "fallback")?;
/// assert_eq!(resources.lookup("HELLO.txt")?.as_ref(), b"hello resource");
/// assert_eq!(resources.lookup("/style.css")?.as_ref(), b"body { color: black; }");
/// assert!(matches!(resources.lookup("missing"), Err(wodix::Error::KeyNotFound(_))));
/// # Ok::<(), wodix::Error>(())
/// ```
pub fn parse(data: B, fallback: &str) -> Result<Self> {
let reader = Reader::parse(data, fallback)?;
Self::new(reader)
}
}
impl<R: Read, I: Lookup> Mdd<R, I> {
/// Build a resource index from this exact reader and its budgets.
///
/// # Errors
///
/// Propagates [`crate::Lookup::build`] failures.
pub fn new(reader: R) -> Result<Self> {
let index = I::build(reader.entries(), reader.limits())?;
Ok(Self { reader, index })
}
/// Borrow the source for metadata and source-order raw record access.
pub fn reader(&self) -> &R {
&self.reader
}
/// Borrow the key index whose IDs belong only to this source.
pub fn index(&self) -> &I {
&self.index
}
/// Find the first matching resource and return its raw decompressed bytes.
///
/// Converts slashes to backslashes, removes an initial `.\`, adds a leading
/// backslash and lowercases the key before index matching. Duplicate keys
/// select the first source-order ID. This performs no filesystem lookup,
/// text decoding, trimming, style expansion or resource-redirect resolution.
///
/// # Errors
///
/// Returns [`crate::Error::KeyNotFound`] for a miss, [`crate::Error::Limit`]
/// for an oversized name or record, and propagates raw read failures.
pub fn lookup(&self, path: &str) -> Result<Bytes> {
Limits::check(
"resource name",
path.len() as u64,
self.reader.limits().key_index,
)?;
let key = Resource { path }.key();
let id = self
.index
.exact(&key)
.first()
.ok_or_else(|| Error::KeyNotFound(key.clone()))?;
self.reader.read(*id)
}
}
impl<R: Read, I> std::fmt::Debug for Mdd<R, I> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Mdd")
.field("entries", &self.reader.entries().len())
.finish_non_exhaustive()
}
}
/// Associated local resources and lazily opened MDD volumes.
///
/// Obtained through [`crate::Mdx::resources`]. An empty default collection does
/// not access the filesystem. Discovered collections prefer local files and
/// initialize all known MDD volumes together on the first nonlocal load.
/// Failed initialization installs no partial set and can be retried.
#[derive(Default)]
pub struct Resources {
root: Option<PathBuf>,
paths: Vec<PathBuf>,
files: Mutex<Option<Arc<[Mdd]>>>,
limits: Limits,
}
impl std::fmt::Debug for Resources {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Resources")
.field("has_root", &self.root.is_some())
.field("volumes", &self.paths.len())
.finish_non_exhaustive()
}
}
impl Resources {
/// Discover the main MDD and consecutive numbered volumes beside an MDX.
///
/// Canonicalizes the source directory and checks neighboring paths using
/// default budgets, but does not open or map MDD payloads.
///
/// # Errors
///
/// Returns directory I/O errors or a resource-volume budget error.
///
/// # Safety
/// Discovered volumes must remain immutable until this collection is dropped,
/// including before the first lazy read. Directory paths must stay stable.
pub unsafe fn discover(source: &Path) -> Result<Self> {
let limits = Limits::default();
// SAFETY: The caller guarantees stable paths and immutable volumes.
unsafe { Self::discover_with(source, limits) }
}
/// Discover associated resources using explicit component budgets.
///
/// Performs directory/path I/O but defers volume mapping and index-cache
/// access until a resource requires the volumes.
///
/// # Errors
///
/// Returns directory I/O errors or [`crate::Error::Limit`] for volume count.
///
/// # Safety
/// Discovered volumes must remain unmodified and untruncated until this
/// collection is dropped, including before lazy opening. Directory paths
/// must remain stable for that period.
pub unsafe fn discover_with(source: &Path, limits: Limits) -> Result<Self> {
let parent = source
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let root = parent.canonicalize()?;
let mut paths = Vec::new();
if let Some(stem) = source.file_stem().and_then(|name| name.to_str()) {
let main = root.join(format!("{stem}.mdd"));
if main.is_file() {
paths.push(main);
}
for volume in 1.. {
let path = root.join(format!("{stem}.{volume}.mdd"));
if !path.is_file() {
break;
}
Limits::check("resource volumes", (paths.len() + 1) as u64, limits.blocks)?;
paths.push(path);
}
}
Ok(Self {
root: Some(root),
paths,
files: Mutex::new(None),
limits,
})
}
/// Load a local file or resolve a resource from the associated MDD volumes.
///
/// A local file under the canonical dictionary directory takes precedence.
/// Parent traversal and symlinks escaping that directory are rejected.
/// Otherwise all discovered volumes are initialized together, in discovery
/// order, and the first matching resource is selected. Volume opening can
/// read and publish index caches; see [`crate::Cache::open`].
/// MDD redirect records are followed within the redirect budget. Local file
/// bytes are returned unchanged without redirect interpretation.
///
/// # Errors
///
/// Returns [`crate::Error::KeyNotFound`] when absent. Unsafe paths, excessive
/// resource sizes, I/O, parsing and redirect errors are reported explicitly.
/// Volume initialization failures carry the path in [`crate::Error::Resource`];
/// no partially initialized volume set is retained, so a later load retries.
pub fn load(&self, resource: &str) -> Result<Bytes> {
Limits::check(
"resource name",
resource.len() as u64,
self.limits.key_index,
)?;
let key = Resource { path: resource }.key();
if let Some(root) = &self.root {
let relative = resource.replace('\\', "/");
let relative = Path::new(relative.trim_start_matches('/'));
if relative.components().any(|part| {
matches!(
part,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(Error::Corrupt(
"resource path escapes its dictionary directory".into(),
));
}
let local = root.join(relative);
if local.is_file() {
let canonical = local.canonicalize()?;
if !canonical.starts_with(root) {
return Err(Error::Corrupt(
"resource symlink escapes its dictionary directory".into(),
));
}
let file = std::fs::File::open(canonical)?;
Limits::check("resource bytes", file.metadata()?.len(), self.limits.record)?;
let maximum = (self.limits.record as u64)
.checked_add(1)
.ok_or_else(|| Error::Corrupt("resource limit overflow".into()))?;
let mut data = Vec::new();
file.take(maximum).read_to_end(&mut data)?;
Limits::check("resource bytes", data.len() as u64, self.limits.record)?;
return Ok(data.into());
}
}
let files = self.volumes()?;
let mut chain = Chain {
load: |path: &str| {
for file in files.iter() {
match file.lookup(path) {
Ok(data) => return Ok(data),
Err(Error::KeyNotFound(_)) => continue,
Err(error) => return Err(error),
}
}
Err(Error::KeyNotFound(path.to_owned()))
},
limit: self.limits.redirects,
};
chain.bytes(&key)
}
fn volumes(&self) -> Result<Arc<[Mdd]>> {
let mut state = self
.files
.lock()
.map_err(|_| Error::Corrupt("resource initialization lock poisoned".into()))?;
if let Some(files) = &*state {
return Ok(Arc::clone(files));
}
let mut opened = Vec::new();
for path in &self.paths {
// SAFETY: discover's caller keeps every associated volume immutable.
let file =
unsafe { Mdd::open_with(path, self.limits) }.map_err(|source| Error::Resource {
path: path.clone(),
source: Box::new(source),
})?;
opened.push(file);
}
let files: Arc<[Mdd]> = opened.into();
*state = Some(Arc::clone(&files));
Ok(files)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn canonical_resource_keys() {
assert_eq!(
Resource {
path: "./img/pic.png"
}
.key(),
"\\img\\pic.png"
);
assert_eq!(
Resource {
path: "/css/style.css"
}
.key(),
"\\css\\style.css"
);
assert_eq!(
Resource {
path: "\\fonts\\a.ttf"
}
.key(),
"\\fonts\\a.ttf"
);
assert_eq!(Resource { path: ".hidden" }.key(), "\\.hidden");
assert_eq!(
Resource {
path: "/IMG/Photo.PNG"
}
.key(),
"\\img\\photo.png"
);
}
#[test]
fn volume_failures_are_not_cached_as_missing_resources() {
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("dict.mdx");
fs::write(directory.path().join("dict.mdd"), b"broken").unwrap();
// SAFETY: Test inputs remain immutable throughout the resource lifetime.
let resources = unsafe { Resources::discover(&source) }.unwrap();
for _ in 0..2 {
match resources.load("missing.css") {
Err(Error::Resource { path, source }) => {
assert!(
same_file::is_same_file(&path, directory.path().join("dict.mdd")).unwrap()
);
assert!(matches!(
*source,
Error::InvalidHeader(_) | Error::Limit { .. }
));
}
other => panic!("expected volume error, got {other:?}"),
}
}
}
#[test]
fn local_resources_obey_scope_and_size_budget() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("dictionary");
fs::create_dir(&root).unwrap();
fs::write(root.join("style.css"), b"local CSS").unwrap();
fs::write(directory.path().join("private.txt"), b"private").unwrap();
let limits = Limits {
record: 9,
..Limits::default()
};
// SAFETY: No MDD volumes exist and test files remain unchanged.
let resources =
unsafe { Resources::discover_with(&root.join("dict.mdx"), limits) }.unwrap();
assert_eq!(
resources.load("./style.css").unwrap().as_ref(),
b"local CSS"
);
assert!(matches!(
resources.load("../private.txt"),
Err(Error::Corrupt(_))
));
assert!(matches!(
resources.load("missing.css"),
Err(Error::KeyNotFound(_))
));
let limits = Limits {
record: 8,
..Limits::default()
};
// SAFETY: The same immutable source set is used.
let limited = unsafe { Resources::discover_with(&root.join("dict.mdx"), limits) }.unwrap();
assert!(matches!(
limited.load("style.css"),
Err(Error::Limit { .. })
));
}
}