unityrs_core/env/registry/mod.rs
1// Ported from UnityPy 1.25.2 (MIT): UnityPy/environment.py. See THIRD_PARTY_LICENSES.
2//! The CAB registry: UnityPy's `env.cabs` dict (`environment.py:252-280`).
3//!
4//! Keys are [`crate::pystr::simplify_name`] of the registered name. As a
5//! Python dict: a repeated key replaces the value and keeps the first
6//! position, and iteration is in first-insertion order (`env.container`
7//! walks it).
8//!
9//! **Ranks.** Every registration has a rank (the crate's `Rank`): the
10//! sequence number of the load that made it, then the directory indexes from
11//! that load's top-level file to the entry (empty for the file itself, `[i]`
12//! for entry `i` of a bundle, `[i, j]` for entry `j` of the bundle that is
13//! entry `i`). UnityPy's eager load registers a bundle's entries in place, in
14//! directory order, so the order in which it registers them is the order of
15//! their ranks, and a key's position is its *least* rank and its value the
16//! registration of *greatest* rank. The registry keeps exactly that, whatever
17//! the order the registrations arrive in: a registration below the key's
18//! value's rank leaves the value, one below its position's rank moves the
19//! key there, and one of equal rank (the same entry registered again) is no
20//! change. So the registry holds what an eager load registers whatever
21//! the order its registrations arrive in, from whichever thread.
22//!
23//! **Nested containers under `LoadMode::Lazy`** (plan section 3.13,
24//! difference (b)). A lazy bundle registers every directory entry's name at
25//! open, unread, so an entry that is itself a bundle is a key of its own
26//! (its slot answers `None`) until it is *reached*: its first bytes are
27//! read and, when they are a bundle's, it is parsed and its whole subtree
28//! registered in place, at the ranks an eager load gives them (a container
29//! inside it has no key, as under `Eager`). One routine reaches
30//! (`Registry::reach`, `reach.rs`), and the invariant it keeps is: a
31//! nested container is reached before any of these returns: a lookup that
32//! resolves its slot (a `get` of its name, a pointer that names it, the
33//! container pass); a lookup from a file inside it (a dereference, a
34//! resource read: `super::Environment`'s `reach_chain`); a pointer or a
35//! resource candidate that reaches it through the asking file's own
36//! bundle; a container pass, which reaches every registered entry before
37//! it walks; and a registration that would drop its slot (replace it, or
38//! lose to a greater rank), which lists the dropped slot, and whose load
39//! reaches it before it returns (`Registry::settle`): nothing could reach
40//! it by name afterwards, and an eager load registered its entries at load
41//! (review round 4: a later load's entry of the same path dropped it
42//! unread, and its entries were never registered). Every reader settles
43//! first (a load's registration, a lookup by name, the key listing, the
44//! container pass), and every `settle` reaches every listed slot, so none
45//! returns while a slot listed before it is unreached, but for a refusal
46//! (plan section 3.16, R3; `reach.rs`). A dropped slot of a dependency the
47//! LRU evicted is not opened again by a `settle`: it waits on a list of its
48//! own for the container pass, which reopens the dependency and reaches it
49//! (plan 9, Q13, revised after review round 6). A dropped slot is not
50//! reached when the key's value stands in for it: the same entry of the
51//! same input, as every handle on the dropped entry can tell
52//! (`reach::stands_in`), which a lookup from a file inside the dropped entry
53//! then reaches, and whose reach registers the entries at the dropped
54//! slot's positions (plan 9, Q14, revised after review round 6;
55//! `register.rs`, `Stand`), until that reach closes its position, after
56//! which a dropped slot is listed (`reach.rs`, "Stand-ins").
57//! What remains of (b) is a lookup by name alone (a
58//! `get_cab`, a `find_file`, a pointer to a file that is not the asking
59//! file's sibling) of an entry of a container nothing has reached, which
60//! misses or finds an earlier registration of its key, and the container's
61//! own name, a key at its rank where an eager load registers none and keeps
62//! an earlier CAB of that path under it. Under eager loading a bundle
63//! registers its CABs as it parses them, so a later entry's failure leaves
64//! the earlier ones registered (difference (a)).
65//!
66//! **What a slot holds** (the crate's `Slot`). A file the caller loaded is never
67//! evicted, so its slot may hold its handle. A dependency's slot never
68//! holds a strong handle on it: it holds what *reopens* the dependency (its
69//! name, its [`super::Source`], its meter, and the path of directory indexes
70//! from its top-level file to the CAB, its rank's) and a `Weak` on the handle
71//! the dependency LRU keeps, so evicting the dependency (dropping the LRU's
72//! handle) frees its runs, its parsed entries, its nested bundles and, for a
73//! source that can be read again (`Path`, `Fetch`), its bytes and their
74//! charge; the next `get` opens it again from the source on
75//! [`crate::limits::Meter::reopen`] of its meter (the same memory account,
76//! the new open's own work allowance, plan section 3.13) and walks the path
77//! to the CAB. Parsed entries are cached in the bundle handle's own cells
78//! ([`crate::files::BundleFile::entry`]), not in the registry, so they go
79//! with the handle. A CAB inside a nested bundle of a dependency is slotted
80//! by its path, never by a handle on the inner bundle, which would keep it,
81//! and the slice of the outer's decoded run it is made from, alive past the
82//! eviction. When the last slot of a dependency goes (every key it
83//! registered was registered again by another file), nothing can reach it
84//! any more and the LRU drops it. Its slots are counted on it
85//! (`DepSlot`), so of two dropped at once exactly one is the last, and a
86//! load whose every key was replaced before it reached the LRU lets go of
87//! it itself (review round 2: a test of the `Arc` count saw both slots'
88//! handles, and neither let go).
89//!
90//! **Cells.** A slot's parse is published with
91//! [`crate::once::get_or_publish_result`]: a budget or meter refusal is
92//! returned and not kept, so a shared dependency refused once (while other
93//! jobs held the pool) is parsed again on the next `get`. A parse has no side
94//! effect but its charges. A nested container's entries are registered from
95//! the parsed value by every reach that finds them not yet all registered,
96//! and the slot is marked once they all are; a second registration of an
97//! entry has the rank of the first and changes nothing, so two threads that
98//! reach one container at once both return with every entry registered.
99//!
100//! **Memory.** Every registration is charged to the meter of the input its
101//! slot belongs to (plan section 3.16, R2): a dependency's slots, those a
102//! reach through another open's handle registers included, to the
103//! dependency's own meter, any other to the registering file's: the key ([`crate::raw::RawStr::charged`]), the slot's
104//! `Arc` and its rank's path, an element of the `order` B-tree and four
105//! buckets of the `slots` hash table (a bucket is a key, a slot handle and a
106//! control byte). Every node of std's `BTreeMap` but the root holds at least
107//! 5 of its 11 elements, and every internal node but the root at least 6
108//! children, so a fifth of a leaf and a thirtieth of an internal node per
109//! element cover the tree; a doubling hash table holds up to 16/7 buckets per
110//! key at rest and 24/7 while it grows (the crate's `HASH_TABLE_SHARES`), so
111//! the tables' spare capacity and every growth are paid for. The first key
112//! also pays for the B-tree's root leaf. A lazy entry's slot also pays for
113//! its share of a node of the lists of dropped slots waiting to be reached
114//! (`pending.rs`); each list's root, one node at most and none once it
115//! empties, is a constant of the registry, as the hash table's control
116//! tail is (plan section 3.13). A dependency's `Lazy` load holds what it
117//! staged until it publishes it (below, "A failed dependency load"): the
118//! list, charged to the dependency's meter, and each registration's
119//! charges, a key new when staged paying its copy and share even when an
120//! earlier row of the same load takes the key first (returned at the
121//! commit). `tests/env_memory.rs` measures the heap against the charge, a
122//! lazy dependency's load included. A refused charge registers nothing and
123//! is the registering load's error.
124//!
125//! **A failed dependency load** (plan section 3.13; `docs/plans/batch.md`
126//! section 6, CR1). Under `LoadMode::Lazy` a dependency's load
127//! (`Environment::load_dependency`, or a resolver's load made as a
128//! dependency) publishes nothing when it fails. It stages its
129//! registrations (`register.rs`, `Stage`): the list that holds them, room
130//! for a bundle's whole directory charged before any entry, then each
131//! registration charged as any is (`prepare`: its key, its slot, a new
132//! key's share and copy, its position's path); then the LRU's entry, and a
133//! `find_file` load's `files` entry under `keep_resolver_loads`, are
134//! charged; only then are the registrations published, one key at a time
135//! and in the order they were staged, each as any load's registration is
136//! (`apply`, then the load's `settle`), and nothing in that can fail the
137//! load: the `settle` reaches the lazy slots a registration dropped and
138//! charges what it reads, and keeps a refusal there to itself, the slot
139//! left listed for a later call, as every `settle` does. A refusal before
140//! the commit drops the stage, which returns every charge and was never in
141//! the registry: no lookup, on this thread or another, can have found any
142//! of it, no slot was dropped or listed, and no generation or walk's flag
143//! moved, so the registry is as it was before the load. It does not cover
144//! a caller's load (`Environment::load`, and a resolver's load made as a
145//! caller's under `keep_resolver_loads`), which registers one key at a
146//! time under either mode and keeps, when it fails, those registered
147//! before. Under `LoadMode::Eager` a dependency's CABs are registered as
148//! they are parsed, as UnityPy's `load_file(..., is_dependency=True)`
149//! registers them (`files/File.py:76-90` registers each entry whatever the
150//! flag), so a load that fails keeps those registered before its failure
151//! (the partial registration above, difference (a)).
152//!
153//! Owner: package D.
154
155mod cab;
156mod dependency;
157mod lru;
158mod pending;
159mod rank;
160mod reach;
161mod register;
162mod slot;
163
164use std::cell::Cell;
165use std::collections::{BTreeMap, HashMap};
166use std::mem::size_of;
167use std::ops::Bound;
168#[cfg(test)]
169use std::sync::Mutex;
170use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
171use std::sync::{Arc, RwLock};
172
173pub use cab::{Cab, HeldCab, RawCab};
174#[cfg(test)]
175pub(crate) use dependency::open_bare;
176pub(crate) use dependency::{
177 DepSlot, Dependency, Open, PoolRefusal, from_callers, open_source, pool_refused, with_room,
178};
179pub(crate) use lru::DepCache;
180#[cfg(test)]
181pub(crate) use lru::{Hook, HookFn};
182pub(crate) use rank::Rank;
183pub(crate) use reach::{Through, entry_of, probe_bundle_entry};
184pub(crate) use register::Stage;
185use register::{By, Loads};
186pub(crate) use slot::{Slot, SlotKind};
187
188use super::held::{self, Held, lock};
189use super::watch::{Table, Under, Watches};
190
191use crate::error::Error;
192use crate::files::{BundleFile, File};
193use crate::limits::{Charge, HASH_TABLE_SHARES, Meter, heap_cost};
194use crate::raw::RawStr;
195
196/// One key: the slot of greatest rank, the key's position (the least rank
197/// registered under it), and the charges for its share of the two tables
198/// and for its position's path.
199#[derive(Debug)]
200struct Entry {
201 slot: Arc<Slot>,
202 first: Rank,
203 _share: Charge,
204 /// The charge for `first`'s path.
205 first_charge: Charge,
206}
207
208/// The registry.
209#[derive(Debug)]
210pub struct Registry {
211 inner: RwLock<RegistryInner>,
212 /// The next load's sequence number.
213 loads: AtomicU64,
214 /// How many lazy slots `RegistryInner::pending` lists for every
215 /// `settle` ([`pending::List::Listed`]).
216 pending_len: AtomicUsize,
217 /// How many it keeps for the container pass
218 /// ([`pending::List::Evicted`]).
219 evicted_len: AtomicUsize,
220 /// The generation the last finished container pass started at (0: none).
221 built: AtomicU64,
222 /// Entries parsed through slots, for `EnvStats`.
223 parsed: AtomicU64,
224 /// The running container preload walks' watches on keys.
225 watches: Watches,
226 /// Where a test stops a thread ([`Hook`]).
227 #[cfg(test)]
228 pub(crate) hook: Mutex<Option<HookFn>>,
229}
230
231impl Default for Registry {
232 fn default() -> Self {
233 Self {
234 inner: RwLock::default(),
235 loads: AtomicU64::new(0),
236 pending_len: AtomicUsize::new(0),
237 evicted_len: AtomicUsize::new(0),
238 built: AtomicU64::new(0),
239 parsed: AtomicU64::new(0),
240 watches: Watches::default(),
241 #[cfg(test)]
242 hook: Mutex::new(None),
243 }
244 }
245}
246
247impl Under for Registry {
248 /// Under the registry's write lock, which publishes every key's change
249 /// (`register.rs`).
250 fn with_table(&self, f: &mut dyn FnMut(&mut Table)) {
251 f(&mut self.write().watched);
252 }
253}
254
255#[derive(Debug)]
256struct RegistryInner {
257 /// Each key at its position.
258 order: BTreeMap<Rank, RawStr>,
259 slots: HashMap<RawStr, Entry>,
260 /// The lazy slots dropped unreached ([`Registry::settle`]).
261 pending: pending::Pending,
262 /// The running container preload walks' flags under registry keys,
263 /// set in the step that publishes a key's change (`super::watch`).
264 watched: Table,
265 /// The container index generation: a new one starts in the step that
266 /// publishes a load's change to the dict ([`Self::publish`]), as
267 /// UnityPy's `register_cab` clears `_container_index_built` in the
268 /// statement after the one that sets the key (`environment.py:263-264`),
269 /// and in the step in which a load's registration that changes no key
270 /// lists the lazy slot it dropped (`register.rs`), whose reach registers
271 /// what an eager load registered at that load.
272 generation: u64,
273}
274
275impl Default for RegistryInner {
276 fn default() -> Self {
277 Self {
278 order: BTreeMap::new(),
279 slots: HashMap::new(),
280 pending: pending::Pending::default(),
281 watched: Table::default(),
282 generation: 1,
283 }
284 }
285}
286
287impl RegistryInner {
288 /// The step that publishes a change to the key hashed `hash`, under the
289 /// write lock that made it: the walks' flags under it set
290 /// (`super::watch`, W1) and, for a load's (`load`), a new container
291 /// index generation started (plan section 3.16, P1), so a thread that
292 /// finds the change also finds every answer read under the key's old
293 /// value invalidated (review round 15: the generation was bumped after
294 /// the lock, so a thread that found a new key could still read the old
295 /// generation's built index).
296 fn publish(&mut self, hash: u64, load: bool) {
297 self.watched.notify(hash);
298 if load {
299 self.start_generation();
300 }
301 }
302
303 /// A new container index generation, under the write lock: for a
304 /// load's change ([`Self::publish`]), or for a load's listing of a slot
305 /// it dropped (`register.rs`), whose reach registers what no pass
306 /// marked built before it has walked.
307 fn start_generation(&mut self) {
308 self.generation = self.generation.saturating_add(1);
309 }
310}
311
312/// A B-tree node of `order`: its header, 11 keys and 11 values; an internal
313/// node adds 12 edges (std's `BTreeMap`, `B = 6`).
314const ORDER_ELEMENT: usize = size_of::<Rank>() + size_of::<RawStr>();
315const ORDER_LEAF: u64 = heap_cost((16 + 11 * ORDER_ELEMENT) as u64);
316const ORDER_INTERNAL: u64 = heap_cost((16 + 11 * ORDER_ELEMENT + 12 * size_of::<usize>()) as u64);
317
318/// What one more key costs the two tables: its share of the `order` B-tree
319/// (a fifth of a leaf, a thirtieth of an internal node) and
320/// [`HASH_TABLE_SHARES`] buckets of `slots` (module docs).
321const SHARE: u64 = ORDER_LEAF / 5
322 + 1
323 + ORDER_INTERNAL / 30
324 + 1
325 + HASH_TABLE_SHARES * (size_of::<RawStr>() + size_of::<Entry>() + 1) as u64;
326
327/// A slot's own allocation: the `Slot` in its `Arc`.
328const SLOT_ARC: u64 = heap_cost((size_of::<Slot>() + 2 * size_of::<usize>()) as u64);
329
330/// A lazy slot's share of the lists of dropped slots waiting to be reached
331/// (`pending.rs`).
332const PENDING_SHARE: u64 = pending::SHARE;
333
334thread_local! {
335 /// New keys loads made on this thread: the container pass counts the
336 /// ones its own dereferences make (UnityPy's `RuntimeError: dictionary
337 /// changed size during iteration`), never another thread's.
338 static LOAD_KEYS_HERE: Cell<u64> = const { Cell::new(0) };
339}
340
341/// New keys loads have made on this thread so far.
342pub(crate) fn load_keys_here() -> u64 {
343 LOAD_KEYS_HERE.with(Cell::get)
344}
345
346impl Registry {
347 /// Runs the test's hook at `at`, with no lock held.
348 #[cfg(test)]
349 pub(crate) fn hook(&self, at: Hook) {
350 let hook = lock(&self.hook).clone();
351 if let Some(HookFn(f)) = hook {
352 f(at);
353 }
354 }
355
356 fn read(&self) -> Held<std::sync::RwLockReadGuard<'_, RegistryInner>> {
357 held::read(&self.inner)
358 }
359
360 fn write(&self) -> Held<std::sync::RwLockWriteGuard<'_, RegistryInner>> {
361 held::write(&self.inner)
362 }
363
364 /// The slot under `simplify_name(name)`, the key built charged to `meter`
365 /// in a transient fallible vector and dropped on return,
366 /// after the dropped lazy slots are reached ([`Self::settle`]).
367 pub(crate) fn slot(
368 &self,
369 name: &RawStr,
370 meter: &Arc<Meter>,
371 ) -> Result<Option<Arc<Slot>>, Error> {
372 self.slot_bytes(name.as_bytes(), meter)
373 }
374
375 /// Borrowed transient lookup name; no infallible shared-owner allocation.
376 pub(crate) fn slot_bytes(
377 &self,
378 name: &[u8],
379 meter: &Arc<Meter>,
380 ) -> Result<Option<Arc<Slot>>, Error> {
381 self.settle().ok();
382 let key = crate::pystr::simplify_name_vec(name, meter)?;
383 Ok(self
384 .read()
385 .slots
386 .get(key.as_slice())
387 .map(|e| e.slot.clone()))
388 }
389
390 /// The first key after `after` in the order (the first of all for
391 /// `None`), its position and its slot: a cursor that keys registered
392 /// meanwhile do not disturb.
393 pub(crate) fn slot_after(&self, after: Option<&Rank>) -> Option<(Rank, Arc<Slot>)> {
394 let inner = self.read();
395 let lower = after.map_or(Bound::Unbounded, Bound::Excluded);
396 let (rank, key) = inner.order.range((lower, Bound::Unbounded)).next()?;
397 let slot = inner.slots.get(key.as_bytes())?.slot.clone();
398 Some((rank.clone(), slot))
399 }
400
401 /// The first key after `after` in the order, and its position.
402 fn key_after(&self, after: Option<&Rank>) -> Option<(Rank, RawStr)> {
403 let inner = self.read();
404 let lower = after.map_or(Bound::Unbounded, Bound::Excluded);
405 let (rank, key) = inner.order.range((lower, Bound::Unbounded)).next()?;
406 Some((rank.clone(), key.clone()))
407 }
408
409 /// The hashing of the running container preload walks' watched keys.
410 pub(crate) fn watches(&self) -> &Watches {
411 &self.watches
412 }
413
414 /// The table of the walks' flags under registry keys, for a test.
415 #[cfg(test)]
416 pub(crate) fn watch_room(&self) -> (usize, usize, Vec<(usize, usize)>) {
417 self.read().watched.room()
418 }
419
420 /// The generation now (a new one at every load's change to the dict,
421 /// and at every load's listing of a slot it dropped, in the step that
422 /// publishes it).
423 pub(crate) fn generation(&self) -> u64 {
424 self.read().generation
425 }
426
427 /// Whether a container pass that started at `generation` has finished.
428 pub(crate) fn built(&self, generation: u64) -> bool {
429 self.built.load(Ordering::Acquire) >= generation
430 }
431
432 /// Publishes a finished container pass that started at `generation`;
433 /// [`Self::built`] answers by the greatest one published.
434 pub(crate) fn publish_built(&self, generation: u64) {
435 self.built.fetch_max(generation, Ordering::AcqRel);
436 }
437
438 fn count(&self, slot: &Slot) {
439 if !slot.counted.swap(true, Ordering::Relaxed) {
440 self.parsed.fetch_add(1, Ordering::Relaxed);
441 }
442 }
443
444 /// Entries parsed through slots so far.
445 pub(crate) fn parsed(&self) -> u64 {
446 self.parsed.load(Ordering::Relaxed)
447 }
448
449 /// `get_cab(name)`, parsing a lazy slot now, or opening an evicted
450 /// dependency again from its source. The key is `simplify_name(name)`,
451 /// built charged to `meter` (`crate::pystr::simplify_name`) and dropped
452 /// when the lookup returns; a name already in its simplified form is
453 /// looked up as it is, with no copy. The registry holds no LRU, so a
454 /// pool refusal of the key's charge, when `meter` is a dependency's, is
455 /// returned here as it is: `Environment::get_cab` is the lookup that
456 /// evicts and retries (the registry's `with_room`).
457 pub fn get(&self, name: &RawStr, meter: &Arc<Meter>) -> Result<Option<Cab>, Error> {
458 Ok(self.get_held(name, meter)?.map(|h| h.cab))
459 }
460
461 /// [`Self::get`], with the handle that keeps a dependency's CAB's
462 /// container alive ([`HeldCab`]).
463 pub(crate) fn get_held(
464 &self,
465 name: &RawStr,
466 meter: &Arc<Meter>,
467 ) -> Result<Option<HeldCab>, Error> {
468 match self.slot(name, meter)? {
469 Some(slot) => self.resolve_held(&slot),
470 None => Ok(None),
471 }
472 }
473
474 /// What a slot answers: its CAB, parsed through its bundle's own cell
475 /// (`Lazy`) or reached from its dependency's open handle (reopened from
476 /// its source after an eviction); `None` for a nested container, which
477 /// is reached then (module docs). A dependency read the pool refuses
478 /// evicts the others and retries once ([`with_room`]).
479 pub(crate) fn resolve(&self, slot: &Arc<Slot>) -> Result<Option<Cab>, Error> {
480 Ok(self.resolve_held(slot)?.map(|h| h.cab))
481 }
482
483 /// [`Self::resolve`], with the dependency's top-level file ([`HeldCab`]).
484 pub(crate) fn resolve_held(&self, slot: &Arc<Slot>) -> Result<Option<HeldCab>, Error> {
485 let held = |cab: Option<Cab>| cab.map(|cab| HeldCab { cab, hold: None });
486 match &slot.kind {
487 SlotKind::Ready(cab) => Ok(held(Some(cab.clone()))),
488 SlotKind::Entry { bundle, dir_index } => {
489 let file = bundle.entry(*dir_index)?;
490 self.count(slot);
491 self.answer(slot, file, Some((bundle, *dir_index)))
492 .map(held)
493 }
494 SlotKind::Dependency { dep } => dep.with_room(|| self.resolve_dependency(slot, dep)),
495 }
496 }
497
498 fn resolve_dependency(
499 &self,
500 slot: &Arc<Slot>,
501 dep: &Arc<Dependency>,
502 ) -> Result<Option<HeldCab>, Error> {
503 let top = dep.handle()?;
504 let mut file = top.clone();
505 let mut at: Option<(Arc<BundleFile>, usize)> = None;
506 let path = slot.rank.path();
507 for &i in path {
508 match file {
509 File::Bundle(b) => {
510 file = b.entry(i)?;
511 at = Some((b, i));
512 }
513 File::Web(w) => {
514 file = w.entry(i)?;
515 at = None;
516 }
517 _ => return Ok(None),
518 }
519 }
520 if !path.is_empty() {
521 self.count(slot);
522 }
523 // The walk's parse charged after the touch: count it now.
524 if let Some(cache) = dep.cache.upgrade() {
525 cache.refresh(dep);
526 }
527 let at = at.as_ref().map(|(b, i)| (b, *i));
528 let cab = self.answer(slot, file, at)?;
529 Ok(cab.map(|cab| HeldCab {
530 cab,
531 hold: Some(top),
532 }))
533 }
534
535 /// The CAB a slot's file is: a `SerializedFile`, or a raw reader (read
536 /// through its bundle when it is an entry); a nested container is none,
537 /// and is reached then ([`Self::reach`]).
538 fn answer(
539 &self,
540 slot: &Arc<Slot>,
541 file: File,
542 at: Option<(&Arc<BundleFile>, usize)>,
543 ) -> Result<Option<Cab>, Error> {
544 let cab = match file {
545 File::Serialized(sf) => Some(Cab::Serialized(sf)),
546 File::Raw(raw) => Some(Cab::Raw(match at {
547 Some((bundle, dir_index)) => RawCab::InBundle {
548 bundle: bundle.clone(),
549 dir_index,
550 },
551 None => RawCab::File(raw),
552 })),
553 File::Bundle(nested) => {
554 self.reach(slot, Some(&nested))?;
555 return Ok(None);
556 }
557 File::Web(w) => {
558 self.reach_web(slot, &w)?;
559 return Ok(None);
560 }
561 };
562 slot.mark_reached();
563 Ok(cab)
564 }
565
566 /// Keys in dict order, as an iterator that takes the read lock briefly
567 /// per key (no snapshot of the registry), after the dropped lazy slots
568 /// are reached (`settle`, module docs).
569 #[must_use]
570 pub fn keys(&self) -> Keys<'_> {
571 // A refusal leaves it for the next call (`settle`).
572 self.settle().ok();
573 Keys {
574 registry: self,
575 after: None,
576 }
577 }
578
579 /// Number of keys.
580 #[must_use]
581 pub fn len(&self) -> usize {
582 self.read().order.len()
583 }
584
585 /// Whether it is empty.
586 #[must_use]
587 pub fn is_empty(&self) -> bool {
588 self.len() == 0
589 }
590}
591
592/// The iterator [`Registry::keys`] returns.
593#[derive(Debug)]
594pub struct Keys<'a> {
595 registry: &'a Registry,
596 after: Option<Rank>,
597}
598
599impl Iterator for Keys<'_> {
600 type Item = RawStr;
601
602 fn next(&mut self) -> Option<RawStr> {
603 let (rank, key) = self.registry.key_after(self.after.as_ref())?;
604 self.after = Some(rank);
605 Some(key)
606 }
607}
608
609#[cfg(test)]
610mod pass_tests;
611#[cfg(test)]
612mod reach_tests;
613#[cfg(test)]
614mod room_tests;
615#[cfg(test)]
616mod tests;
617
618pub(crate) use dependency::read_source;