Skip to main content

latexml_core/
digested.rs

1//! Interface layer for the full range of digested objects
2use std::{borrow::Cow, cell::RefCell, fmt, rc::Rc};
3
4use libxml::tree::Node;
5
6use crate::{
7  BoxOps, NO_PROPERTIES,
8  alignment::Alignment,
9  comment::Comment,
10  common::{
11    arena::{self, SymHashMap as HashMap, SymStr},
12    dimension::Dimension,
13    error::*,
14    font::Font,
15    locator::Locator,
16    numeric_ops::NumericOps,
17    object::Object,
18    store::Stored,
19  },
20  definition::register::RegisterValue,
21  document::Document,
22  keyvals::KeyVals,
23  list::List,
24  tbox::Tbox,
25  tokens::Tokens,
26  whatsit::Whatsit,
27};
28
29/// An `Rc`-guarded abstraction for any object encountered at the "digested" phase of processing
30// Each variant is wrapped in an `Rc`, for cheap(er) cloning when passing around
31// these objects to various auxiliary state (e.g. bookkeeping current box),
32// but also for repeatedly passing them as owned into binding closures
33// while also storing them in their owner Box.
34//
35// This model is incredibly hard to achieve with lifetimes, so
36// we employ reference counting instead (close to their original Perl design).
37// A strict OO-hierarchy of object ownership (with no auxiliary state metadata)
38// would allow a Rust-like redesign. But it could be too hard to achieve in practice.
39#[derive(Clone)]
40pub struct Digested(Rc<DigestedData>);
41/// These are all kinds of data which we consider officially supported
42/// as outputs from the digestion phase of TeX, i.e. from invoking a token.
43// Every `DigestedData` is `Rc`-allocated once per box and a huge document keeps
44// millions alive at once (issue #361 measured 11.5 M live at peak), so the
45// enum's size is paid per box. The oversized payloads are contained — `List.font`
46// is `Rc`-shared (M1), `KeyVals` is boxed (M2), and `Whatsit`'s reversion-cache
47// slots are boxed (M4) — bringing the ceiling to `Whatsit` (128 B), over a
48// `TBox`/`List` floor of 104 B. The `digested_data_size_budget` test guards
49// against future re-inflation.
50pub enum DigestedData {
51  /// A TeX Box
52  TBox(RefCell<Tbox>),
53  /// A TeX Whatsit (with interior mutability, for setters invoked while stored in state)
54  Whatsit(RefCell<Whatsit>),
55  /// A TeX Alignment (with interior mutability, for setters invoked while stored in state)
56  Alignment(Box<RefCell<Alignment>>),
57  /// A list of Digested data
58  List(RefCell<List>),
59  /// Raw Tokens that were postponed to the digestion phase uninvoked/undigested
60  Postponed(Tokens),
61  /// A LaTeX-like digested key-value map.
62  ///
63  /// Boxed to keep it off the hot `DigestedData` size budget: `KeyVals` is a
64  /// heavy struct (two `String`s, three `Vec`s, two `HashMap`s ≈ 208 B) but a
65  /// **rare** variant, whereas `DigestedData` is `Rc`-allocated once per box and
66  /// every box in a document pays its size. Inlining `KeyVals` made the whole
67  /// enum 208 B; boxing it took 40 B off *every* digested box (issue #361 memory
68  /// pass, M2), and the added indirection only touches the rare KeyVals
69  /// accesses. Measured at 0.83 % of live boxes on the #361 witness — the
70  /// rarity is what makes the trade pay.
71  KeyVals(Box<KeyVals>),
72  /// A TeX-like `RegisterValue` (e.g. a Dimension or Glue)
73  RegisterValue(RegisterValue),
74  /// A TeX comment
75  Comment(Comment),
76}
77
78// Digested and DigestedData are transparent for debugging -- just show the inner data
79impl fmt::Debug for Digested {
80  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.0) }
81}
82impl fmt::Debug for DigestedData {
83  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84    use DigestedData::*;
85    match self {
86      TBox(v) => write!(f, "{v:?}"),
87      Whatsit(v) => write!(f, "{v:?}"),
88      Alignment(a) => write!(f, "{a:?}"),
89      List(v) => write!(f, "{v:?}"),
90      Postponed(v) => write!(f, "{v:?}"),
91      KeyVals(v) => write!(f, "{v:?}"),
92      RegisterValue(v) => write!(f, "{v:?}"),
93      Comment(v) => write!(f, "{v:?}"),
94    }
95  }
96}
97
98impl PartialEq for Digested {
99  fn eq(&self, other: &Digested) -> bool {
100    use DigestedData::*;
101    match *self.0 {
102      TBox(ref tb) => {
103        if let TBox(ref tb2) = *other.0 {
104          tb == tb2
105        } else {
106          false
107        }
108      },
109      Whatsit(ref tb) => {
110        if let Whatsit(ref tb2) = *other.0 {
111          *tb.borrow() == *tb2.borrow()
112        } else {
113          false
114        }
115      },
116      Alignment(ref tb) => {
117        if let Alignment(ref tb2) = *other.0 {
118          *tb.borrow() == *tb2.borrow()
119        } else {
120          false
121        }
122      },
123      List(ref tb) => {
124        if let List(ref tb2) = *other.0 {
125          tb == tb2
126        } else {
127          false
128        }
129      },
130      Postponed(ref tb) => {
131        if let Postponed(ref tb2) = *other.0 {
132          tb == tb2
133        } else {
134          false
135        }
136      },
137      KeyVals(ref tb) => {
138        if let KeyVals(ref tb2) = *other.0 {
139          tb == tb2
140        } else {
141          false
142        }
143      },
144      RegisterValue(ref tb) => {
145        if let RegisterValue(ref tb2) = *other.0 {
146          tb == tb2
147        } else {
148          false
149        }
150      },
151      Comment(ref tb) => {
152        if let Comment(ref tb2) = *other.0 {
153          tb == tb2
154        } else {
155          false
156        }
157      },
158    }
159  }
160}
161
162// Important: we need to postpone the creation of a box until a time where
163// we have the most current font information
164impl<'a> From<&'a String> for Digested {
165  fn from(value: &'a String) -> Digested {
166    Digested(Rc::new(DigestedData::Postponed(Tokens::new(ExplodeText!(
167      value
168    )))))
169  }
170}
171impl From<String> for Digested {
172  fn from(value: String) -> Digested {
173    Digested(Rc::new(DigestedData::Postponed(Tokens::new(ExplodeText!(
174      value
175    )))))
176  }
177}
178impl From<SymStr> for Digested {
179  fn from(sym: SymStr) -> Digested {
180    let tks = SymExplodeText!(sym);
181    Digested(Rc::new(DigestedData::Postponed(Tokens::new(tks))))
182  }
183}
184
185impl From<Tokens> for Digested {
186  fn from(value: Tokens) -> Digested { Digested(Rc::new(DigestedData::Postponed(value))) }
187}
188impl From<Tbox> for Digested {
189  fn from(value: Tbox) -> Digested { Digested(Rc::new(DigestedData::TBox(RefCell::new(value)))) }
190}
191impl From<List> for Digested {
192  fn from(value: List) -> Digested { Digested(Rc::new(DigestedData::List(RefCell::new(value)))) }
193}
194impl From<Whatsit> for Digested {
195  fn from(value: Whatsit) -> Digested {
196    Digested(Rc::new(DigestedData::Whatsit(RefCell::new(value))))
197  }
198}
199impl From<Alignment> for Digested {
200  fn from(value: Alignment) -> Digested {
201    Digested(Rc::new(DigestedData::Alignment(Box::new(RefCell::new(
202      value,
203    )))))
204  }
205}
206impl From<KeyVals> for Digested {
207  fn from(value: KeyVals) -> Digested { Digested(Rc::new(DigestedData::KeyVals(Box::new(value)))) }
208}
209impl From<RegisterValue> for Digested {
210  fn from(value: RegisterValue) -> Digested {
211    Digested(Rc::new(DigestedData::RegisterValue(value)))
212  }
213}
214impl From<Comment> for Digested {
215  fn from(value: Comment) -> Digested { Digested(Rc::new(DigestedData::Comment(value))) }
216}
217
218impl<'a> From<&'a Digested> for Option<Digested> {
219  fn from(value: &'a Digested) -> Option<Digested> { Some(value.clone()) }
220}
221
222// impl<'a> From<&'a Digested> for Tokens {
223//   fn from(value: &'a Digested) -> Tokens { value.revert().unwrap() }
224// }
225// impl From<Digested> for Tokens {
226//   fn from(value: Digested) -> Tokens { value.revert().unwrap() }
227// }
228impl From<Digested> for Result<Digested> {
229  fn from(value: Digested) -> Result<Digested> { Ok(value) }
230}
231impl From<Digested> for Result<Vec<Digested>> {
232  fn from(value: Digested) -> Result<Vec<Digested>> { Ok(vec![value]) }
233}
234impl From<Digested> for Result<Option<Digested>> {
235  fn from(value: Digested) -> Result<Option<Digested>> { Ok(Some(value)) }
236}
237
238impl Default for Digested {
239  fn default() -> Self { Digested(Rc::new(DigestedData::TBox(RefCell::new(Tbox::default())))) }
240}
241
242impl fmt::Display for Digested {
243  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244    use DigestedData::*;
245    match *self.0 {
246      TBox(ref b) => write!(f, "{}", b.borrow()),
247      List(ref l) => write!(f, "{}", l.borrow()),
248      Whatsit(ref w) => write!(f, "{}", w.borrow()),
249      Alignment(ref a) => write!(f, "{}", a.borrow()),
250      Postponed(ref t) => write!(f, "{t}"),
251      KeyVals(ref kvs) => write!(f, "{kvs}"),
252      Comment(ref c) => write!(f, "{c}"),
253      RegisterValue(ref rv) => write!(f, "{rv}"),
254    }
255  }
256}
257impl Object for Digested {
258  fn stringify(&self) -> String {
259    use DigestedData::*;
260    match *self.0 {
261      TBox(ref b) => b.borrow().stringify(),
262      List(ref l) => l.borrow().stringify(),
263      Whatsit(ref w) => w.borrow().stringify(),
264      Alignment(ref w) => w.borrow().stringify(),
265      Postponed(ref t) => (*t).stringify(),
266      KeyVals(ref kvs) => kvs.stringify(),
267      Comment(ref c) => c.stringify(),
268      RegisterValue(ref rv) => (*rv).stringify(),
269    }
270  }
271  fn get_locator(&self) -> Option<Locator> {
272    use DigestedData::*;
273    // Defensive `try_borrow`, as in `with_properties` and `get_font`: an
274    // Alignment in `be_absorbed_mut` (an exclusive `borrow_mut`) opens its
275    // table and row elements, and `Document::append_node_box` then builds
276    // `List::new(<the node's box>, <that Alignment>)`, whose locator scan asks
277    // the Alignment for its locator; an infallible `.borrow()` panicked
278    // ("RefCell already mutably borrowed"). A re-entrant borrow has no
279    // locator to give. Witnesses 1205.0376, 2605.03048; guard
280    // `perfect_kernel_batch54::tabu_to_width_and_x_columns`.
281    match *self.0 {
282      TBox(ref b) => b.try_borrow().ok().and_then(|b| b.get_locator()),
283      List(ref l) => l.try_borrow().ok().and_then(|l| l.get_locator()),
284      Comment(ref c) => c.get_locator(),
285      Whatsit(ref w) => w.try_borrow().ok().and_then(|w| w.get_locator()),
286      Alignment(ref w) => w.try_borrow().ok().and_then(|w| w.get_locator()),
287      KeyVals(ref kvs) => kvs.get_locator(), // KeyVals locator?
288      RegisterValue(ref rv) => rv.get_locator(),
289      Postponed(ref _t) => None, // Tokens carry no locator
290    }
291  }
292  /// The source tokens this digested value came from — digestion run
293  /// backwards, delegated to whichever variant is held.
294  ///
295  /// What `\meaning`-style introspection and the `tex` attribute are built on:
296  /// a construct that has already become boxes, a whatsit or an alignment can
297  /// still show the LaTeX that produced it. A `Postponed` variant is already
298  /// tokens and reverts to itself.
299  fn revert(&self) -> Result<Tokens> {
300    use DigestedData::*;
301    match *self.0 {
302      TBox(ref b) => b.borrow().revert(),
303      List(ref l) => l.borrow().revert(),
304      Whatsit(ref w) => w.borrow().revert(),
305      // Re-entrant guard: a broken alignment (e.g. a `\matrix`/`\pmatrix` left
306      // mid-mutation by a failed mode-group close) can re-enter its own RefCell
307      // during reversion → "already mutably borrowed" panic. Perl has no
308      // borrow-checker, so its `$alignment->revert` is plain re-entrant data
309      // access. `try_borrow` + an empty reversion on the re-entrant cycle,
310      // mirroring the base_xmath fix (75c452843d) and `compute_size`/`with_properties`.
311      Alignment(ref w) => match w.try_borrow() {
312        Ok(al) => al.revert(),
313        Err(_) => {
314          Error!(
315            "unexpected",
316            "self_referential_alignment",
317            "Reverting a re-entrant alignment to empty tokens (source text is lost)"
318          );
319          Ok(Tokens::default())
320        },
321      },
322      Postponed(ref t) => Ok(t.clone()),
323      KeyVals(ref kvs) => kvs.revert(),
324      Comment(ref c) => c.revert(),
325      RegisterValue(ref rv) => rv.revert(),
326    }
327  }
328}
329
330impl BoxOps for Digested {
331  fn unlist(&self) -> Vec<Digested> {
332    use DigestedData::*;
333    match *self.0 {
334      TBox(_) | Whatsit(_) | Alignment(_) | KeyVals(_) | Comment(_) | Postponed(_)
335      | RegisterValue(_) => {
336        vec![self.clone()]
337      },
338      List(ref l) => l.borrow().unlist(),
339    }
340  }
341  fn unlist_ref(&self) -> Vec<Cow<'_, Digested>> {
342    use DigestedData::*;
343    match *self.0 {
344      TBox(_) | Whatsit(_) | Alignment(_) | KeyVals(_) | Comment(_) | Postponed(_)
345      | RegisterValue(_) => {
346        vec![Cow::Borrowed(self)]
347      },
348      List(ref l) => l.borrow().unlist().into_iter().map(Cow::Owned).collect(),
349    }
350  }
351
352  fn be_absorbed(&self, document: &mut Document) -> Result<Vec<Node>> {
353    use DigestedData::*;
354    match &*self.0 {
355      TBox(b) => b.borrow().be_absorbed(document),
356      List(l) => l.borrow().be_absorbed(document),
357      Comment(c) => c.be_absorbed(document),
358      Whatsit(w) => w.borrow().be_absorbed(document),
359      // Re-entrant guard: a broken alignment mid-`be_absorbed_mut` (which holds
360      // an exclusive borrow) can be re-absorbed by recursive document
361      // construction → "already borrowed" panic. Absorb nothing on the
362      // re-entrant cycle (the alignment is mid-mutation; producing no nodes is
363      // the safe degradation, like `Postponed`). Mirrors `with_properties` /
364      // `compute_size` / the base_xmath fix (75c452843d).
365      Alignment(w) => match w.try_borrow_mut() {
366        Ok(mut al) => al.be_absorbed_mut(document),
367        Err(_) => {
368          Error!(
369            "unexpected",
370            "self_referential_alignment",
371            "Skipping absorption of a re-entrant alignment (its cells are lost)"
372          );
373          Ok(Vec::new())
374        },
375      },
376      KeyVals(kvs) => kvs.be_absorbed(document),
377      Postponed(_) => Ok(Vec::new()), // Postponed items absorbed silently
378      RegisterValue(_rv) => Ok(Vec::new()), // Register values not absorbable
379    }
380  }
381
382  fn with_properties<R, FnR>(&self, caller: FnR) -> R
383  where FnR: FnOnce(&HashMap<Stored>) -> R {
384    use DigestedData::*;
385    // Defensive `try_borrow`: when a Digested wrapper is mid-`be_absorbed_mut`
386    // (which holds an exclusive `borrow_mut`) and document construction
387    // recursively asks the SAME node for its properties, an infallible
388    // `.borrow()` panics with "RefCell already mutably borrowed". Fall
389    // back to NO_PROPERTIES instead — property access during the
390    // mid-absorption window is read-only and a missing-properties result
391    // is benign (matches Perl: properties default to empty in this state).
392    // Witness: 1205.0376 (article + plain-TeX `\AND`/`\at` redefs +
393    // align environment) — previously FATAL_101 panic at digested.rs:329,
394    // now succeeds.
395    match &*self.0 {
396      TBox(b) => match b.try_borrow() {
397        Ok(b) => caller(b.get_properties()),
398        Err(_) => caller(NO_PROPERTIES),
399      },
400      List(l) => match l.try_borrow() {
401        Ok(l) => caller(l.get_properties()),
402        Err(_) => caller(NO_PROPERTIES),
403      },
404      Comment(c) => caller(c.get_properties()),
405      Whatsit(w) => match w.try_borrow() {
406        Ok(w) => caller(w.get_properties()),
407        Err(_) => caller(NO_PROPERTIES),
408      },
409      Alignment(w) => match w.try_borrow() {
410        Ok(w) => caller(w.get_properties()),
411        Err(_) => caller(NO_PROPERTIES),
412      },
413      KeyVals(_) | Postponed(_) | RegisterValue(_) => caller(NO_PROPERTIES),
414    }
415  }
416  // Note: get_properties_mut is not implemented, as it would generically require a RefCell
417  // around each type of DigestedData. Currently we are trying to keep some immutability guarantees.
418  // at the Digested interface
419
420  fn set_property<T: Into<Stored>>(&mut self, key: &str, value: T) {
421    if !self.try_set_property(key, value) {
422      emit_error(
423        "unexpected",
424        "reentrant_property_write",
425        &s!("Property {key} not set: its box is in use (being absorbed or sized)"),
426      );
427    }
428  }
429
430  fn set_memo_property<T: Into<Stored>>(&mut self, key: &str, value: T) {
431    let _ = self.try_set_property(key, value);
432  }
433
434  fn get_property(&self, key: &str) -> Option<Cow<'_, Stored>> {
435    use DigestedData::*;
436    match *self.0 {
437      TBox(ref b) => b
438        .borrow()
439        .get_property(key)
440        .map(|v| Cow::Owned(v.into_owned())),
441      List(ref l) => l
442        .borrow()
443        .get_property(key)
444        .map(|v| Cow::Owned(v.into_owned())),
445      Whatsit(ref w) => w
446        .borrow()
447        .get_property(key)
448        .map(|v| Cow::Owned(v.into_owned())),
449      _ => None,
450    }
451  }
452  fn get_string(&self) -> Result<Cow<'_, str>> {
453    use DigestedData::*;
454    match *self.0 {
455      TBox(ref b) => b.borrow().get_string().map(|v| Cow::Owned(v.into_owned())),
456      List(ref l) => l.borrow().get_string().map(|v| Cow::Owned(v.into_owned())),
457      Whatsit(ref w) => w.borrow().get_string().map(|v| Cow::Owned(v.into_owned())),
458      _ => Ok(Cow::Borrowed("")),
459    }
460  }
461  fn has_property(&self, key: &str) -> bool {
462    use DigestedData::*;
463    match *self.0 {
464      TBox(ref b) => b.borrow().has_property(key),
465      List(ref l) => l.borrow().has_property(key),
466      Whatsit(ref w) => w.borrow().has_property(key),
467      _ => false,
468    }
469  }
470  fn get_body(&self) -> Result<Option<Digested>> {
471    use DigestedData::*;
472    match *self.0 {
473      // Perl: Box::getBody returns $self; List::getBody returns $self
474      TBox(_) | List(_) => Ok(Some(self.clone())),
475      Whatsit(ref w) => w.borrow().get_body(),
476      _ => Ok(None),
477    }
478  }
479  fn get_property_bool(&self, key: &str) -> bool {
480    use DigestedData::*;
481    match *self.0 {
482      TBox(ref b) => b.borrow().get_property_bool(key),
483      List(ref l) => l.borrow().get_property_bool(key),
484      Whatsit(ref w) => w.borrow().get_property_bool(key),
485      Alignment(_) | KeyVals(_) | Comment(_) | Postponed(_) | RegisterValue(_) => false,
486    }
487  }
488  /// The box's font as a SHARED handle.
489  ///
490  /// This used to return `Cow<'_, Font>`, which was a false promise on exactly
491  /// the path that matters: the payloads live behind a `RefCell`, so a
492  /// `Cow::Borrowed` cannot outlive the borrow guard and every arm was forced
493  /// through `Cow::Owned(v.into_owned())` — a deep `Font` clone on every call,
494  /// even though `Tbox`/`List`/`Whatsit` all already hold an `Rc<Font>`.
495  ///
496  /// That clone was the single largest allocation in a conversion. Measured
497  /// 2026-07-29 with `--features dhat-heap` on 100k words of plain prose:
498  /// `Rc<Font>::new` accounted for **392 MB of the 840 MB peak (47 %)** across
499  /// 1,196,000 blocks of 344 B — one per box absorbed — reached via
500  /// `List::new` ← `append_node_box` ← `open_text` ← `absorb`. The digested
501  /// boxes themselves came to 164 MB, so the *font attached to* each box cost
502  /// 2.4x the box. No caller ever used `Cow`'s one advantage (`to_mut`).
503  fn get_font(&self) -> Result<Option<Rc<Font>>> {
504    use DigestedData::*;
505    match *self.0 {
506      // `try_borrow` rather than `borrow`: a re-entrant traversal (the same
507      // guard the other `Digested` walks use) degrades to "no font" instead of
508      // panicking mid-conversion.
509      TBox(ref b) => Ok(b.try_borrow().ok().map(|b| Rc::clone(&b.font))),
510      List(ref l) => Ok(l.try_borrow().ok().and_then(|l| l.font.clone())),
511      Whatsit(ref w) => match w.try_borrow() {
512        Ok(w) => w.get_font(),
513        Err(_) => Ok(None),
514      },
515      Postponed(ref _tks) => Ok(None),
516      _ => Ok(None),
517    }
518  }
519
520  /// Note the difference between calling `compute_size` on a Digested object, and calling it on a
521  /// concrete box type. When called on `Digested` it will opt for caching the computed sizes,
522  /// but when called on the concrete types it will always compute sizes fresh.
523  fn compute_size(&self, options: HashMap<Stored>) -> Result<(Dimension, Dimension, Dimension)> {
524    use DigestedData::*;
525    // A self-referential box (its size computation recurses into the SAME
526    // RefCell — e.g. a box that transitively contains itself) would re-enter
527    // `borrow_mut` and panic ("already borrowed"). The other traversals on
528    // `Digested` (fingerprint, serialization) already guard with `try_borrow`;
529    // do the same here and treat a re-entrant cycle as zero-size to break it.
530    // Witness: astro-ph0310145 (panicked at digested.rs Alignment arm).
531    let zero = (Dimension::new(0), Dimension::new(0), Dimension::new(0));
532    match *self.0 {
533      TBox(ref b) => match b.try_borrow_mut() {
534        Ok(mut x) => x.compute_size_and_cache(options),
535        Err(_) => Ok(zero),
536      },
537      List(ref l) => match l.try_borrow_mut() {
538        Ok(mut x) => x.compute_size_and_cache(options),
539        Err(_) => Ok(zero),
540      },
541      KeyVals(ref kvs) => kvs.compute_size(options),
542      Whatsit(ref w) => match w.try_borrow_mut() {
543        Ok(mut x) => x.compute_size_and_cache(options),
544        Err(_) => Ok(zero),
545      },
546      Alignment(ref w) => match w.try_borrow_mut() {
547        Ok(mut x) => x.compute_size_and_cache(options),
548        Err(_) => Ok(zero),
549      },
550      Postponed(_) | RegisterValue(_) | Comment(_) => Ok(zero),
551    }
552  }
553}
554
555/// Hard cap on the number of sub-boxes visited by [`Digested::cycle_fingerprint`].
556/// Bounds the fingerprint cost to O(1) per box while still sampling enough
557/// content (depth-first) to tell apart same-shaped boxes.
558const FP_BUDGET: u32 = 48;
559
560/// Per-box traversal cap for [`Digested::estimate_bytes`]. Larger than
561/// `FP_BUDGET` (the estimate is computed only on a small *sample* of the box
562/// list, so a deeper walk is affordable and improves accuracy for nested
563/// boxes).
564pub(crate) const EB_BUDGET: u32 = 256;
565
566impl Digested {
567  /// Set a property unless the box is borrowed — being absorbed (`Document::absorb` holds it while its constructor
568  /// runs); false then. Perl's store always lands (Box.pm:168-171).
569  pub fn try_set_property<T: Into<Stored>>(&self, key: &str, value: T) -> bool {
570    use DigestedData::*;
571    match *self.0 {
572      // TODO: This is only possible if we have interior mutability for *ALL* Digested variants
573      // i.e. Rc<RefCell<Tbox>>, Rc<RefCell<List>>, etc.
574      TBox(ref b) => b
575        .try_borrow_mut()
576        .map(|mut b| b.set_property(key, value))
577        .is_ok(),
578      List(ref l) => l
579        .try_borrow_mut()
580        .map(|mut l| l.set_property(key, value))
581        .is_ok(),
582      Whatsit(ref w) => w
583        .try_borrow_mut()
584        .map(|mut w| w.set_property(key, value))
585        .is_ok(),
586      _ => true, // no-op for Comment/Postponed/RegisterValue/KeyVals/Alignment
587    }
588  }
589
590  /// Remove a property unless the box is borrowed (false then), as [`Self::try_set_property`] sets one.
591  pub(crate) fn try_remove_property(&self, key: &str) -> bool {
592    use DigestedData::*;
593    match *self.0 {
594      TBox(ref b) => b
595        .try_borrow_mut()
596        .map(|mut b| b.get_properties_mut().remove(key))
597        .is_ok(),
598      List(ref l) => l
599        .try_borrow_mut()
600        .map(|mut l| l.get_properties_mut().remove(key))
601        .is_ok(),
602      Whatsit(ref w) => w
603        .try_borrow_mut()
604        .map(|mut w| w.get_properties_mut().remove(key))
605        .is_ok(),
606      _ => true,
607    }
608  }
609
610  /// immutably borrow the inner Digested data
611  pub fn data(&self) -> &DigestedData { &self.0 }
612
613  /// Number of live `Digested` handles sharing this box (diagnostics: a box
614  /// still referenced after its fragment was absorbed and dropped is retained
615  /// somewhere else).
616  pub fn strong_count(&self) -> usize { Rc::strong_count(&self.0) }
617
618  /// Identity of the shared allocation (diagnostics: visit each box once).
619  pub fn as_ptr(&self) -> *const DigestedData { Rc::as_ptr(&self.0) }
620
621  /// A content-aware but COST-BOUNDED fingerprint for the stomach cycle guard
622  /// ([`crate::cycle_guard`]).
623  ///
624  /// Design tension: it must (a) distinguish boxes by *content* so two
625  /// different boxes that merely share a shape (e.g. two `List`s of equal
626  /// length but different children) don't collide into a false cycle, yet
627  /// (b) be cheap on the digestion path. We reconcile both with a hard
628  /// **node budget**: at most `FP_BUDGET` sub-boxes are ever visited (a
629  /// depth-first sample of the content), so cost is O(1) per box regardless
630  /// of how large or deeply nested the structure is, while the sample is rich
631  /// enough that real content differences change the hash. (It is also only
632  /// ever invoked once `box_list` has already blown past the stomach guard's
633  /// activation size, so ordinary conversions never pay for it at all.)
634  /// NOT a stable cross-process hash — for in-run loop detection only.
635  pub fn cycle_fingerprint(&self) -> u64 {
636    use std::hash::Hasher;
637    let mut h = rustc_hash::FxHasher::default();
638    let mut budget: u32 = FP_BUDGET;
639    self.fingerprint_into(&mut h, &mut budget);
640    h.finish()
641  }
642
643  // NOTE: `fingerprint_into` and `estimate_bytes_into` are PAIRED budgeted
644  // traversals over `DigestedData` (one hashes, one sizes — different
645  // per-variant work, same walk shape). Both matches are deliberately
646  // EXHAUSTIVE (no `_` catch-all): adding a `DigestedData` variant breaks
647  // both at compile time, so the two cannot silently drift on coverage —
648  // only keep that property when editing either (PR #249 review P3-11).
649  fn fingerprint_into<H: std::hash::Hasher>(&self, h: &mut H, budget: &mut u32) {
650    use std::hash::Hash;
651    if *budget == 0 {
652      return;
653    }
654    *budget -= 1;
655    match self.data() {
656      DigestedData::TBox(b) => {
657        0u8.hash(h);
658        if let Ok(tb) = b.try_borrow() {
659          tb.text.hash(h);
660        }
661      },
662      DigestedData::Whatsit(w) => {
663        1u8.hash(h);
664        if let Ok(wb) = w.try_borrow() {
665          // The creating definition's identity distinguishes whatsits of
666          // different kinds (Rc data-pointer, stable within a run); the args
667          // distinguish their content.
668          (Rc::as_ptr(&wb.definition) as *const () as usize).hash(h);
669          wb.args.len().hash(h);
670          for arg in &wb.args {
671            if *budget == 0 {
672              break;
673            }
674            match arg {
675              Some(d) => d.fingerprint_into(h, budget),
676              None => {
677                *budget -= 1;
678                0xFEu8.hash(h);
679              },
680            }
681          }
682        }
683      },
684      DigestedData::Alignment(_) => 2u8.hash(h),
685      DigestedData::List(l) => {
686        3u8.hash(h);
687        if let Ok(lb) = l.try_borrow() {
688          lb.boxes.len().hash(h);
689          for child in &lb.boxes {
690            if *budget == 0 {
691              break;
692            }
693            child.fingerprint_into(h, budget);
694          }
695        }
696      },
697      DigestedData::Postponed(t) => {
698        4u8.hash(h);
699        t.len().hash(h);
700      },
701      DigestedData::KeyVals(_) => 5u8.hash(h),
702      DigestedData::RegisterValue(r) => {
703        6u8.hash(h);
704        std::mem::discriminant(r).hash(h);
705        // The amount tells register values apart: a PiCTeX `\plot` sets each of its dots with its own `\raise`, and
706        // hashed by kind alone a long line of them read as a loop past `STOMACH_CYCLE_ACTIVATE` (0801.0709;
707        // OXIDIZED_DESIGN_DIVERGENCES #326).
708        match r {
709          RegisterValue::Number(v) => v.0.hash(h),
710          RegisterValue::Dimension(v) => v.0.hash(h),
711          RegisterValue::MuDimension(v) => v.0.hash(h),
712          RegisterValue::Glue(v) => (v.skip, v.plus, v.minus).hash(h),
713          RegisterValue::MuGlue(v) => (v.skip, v.plus, v.minus).hash(h),
714          RegisterValue::Pair(v) => (v.x.0.to_bits(), v.y.0.to_bits()).hash(h),
715          RegisterValue::Token(_) | RegisterValue::Tokens(_) => {},
716        }
717      },
718      DigestedData::Comment(c) => {
719        7u8.hash(h);
720        c.0.hash(h);
721      },
722    }
723  }
724  /// A COST-BOUNDED estimate of the heap bytes this digested box (and its
725  /// nested content) occupies. Used by the stomach's portable
726  /// memory-budget guard ([`crate::stomach`]) to detect a runaway *by the
727  /// resource that actually matters — bytes — rather than box COUNT*, since
728  /// per-box weight varies several-fold (a bare text box vs a deeply nested
729  /// `\hbox{\raise…\hbox{…}}`). Traversal is capped at `EB_BUDGET` sub-boxes
730  /// (depth-first) so the estimate stays O(1) per box; deeply nested boxes
731  /// beyond the budget are under-counted, which is safe (the guard only needs
732  /// a monotone lower bound to catch unbounded growth).
733  pub fn estimate_bytes(&self) -> usize {
734    let mut budget: u32 = EB_BUDGET;
735    self.estimate_bytes_into(&mut budget)
736  }
737
738  // Paired with `fingerprint_into` above — keep both matches exhaustive
739  // (see the note there).
740  fn estimate_bytes_into(&self, budget: &mut u32) -> usize {
741    if *budget == 0 {
742      return 0;
743    }
744    *budget -= 1;
745    // Per-node fixed overhead: the `Rc<DigestedData>` control block + the
746    // enum discriminant + the inner `RefCell`/`Box`. Deliberately coarse.
747    const NODE: usize = 64;
748    // Note: text and the `Rc<Font>` are shared (interned / ref-counted), so they
749    // add no marginal per-box bytes. What DOES accumulate per box and dominates
750    // RSS is each box's OWNED data: the `properties` HashMap, the `tokens`
751    // source-TeX vector (`Tbox`), the args/children vectors, and — crucially —
752    // the nested children themselves.
753    //
754    // `map_bytes`: a `SymHashMap` (hashbrown) allocates a control-byte table +
755    // key/value slots at ~7/8 load; ~96 B per live entry plus the base table
756    // covers control bytes, the `Stored` value enum, and growth slack.
757    fn map_bytes(n: usize) -> usize { if n == 0 { 0 } else { 64 + n * 96 } }
758    match self.data() {
759      DigestedData::TBox(b) => {
760        let mut bytes = NODE + 48;
761        if let Ok(tb) = b.try_borrow() {
762          bytes += map_bytes(tb.properties.len());
763          bytes += tb.tokens.len() * 16; // owned source-TeX tokens
764        }
765        bytes
766      },
767      DigestedData::Whatsit(w) => {
768        let mut bytes = NODE + 64;
769        if let Ok(wb) = w.try_borrow() {
770          bytes += map_bytes(wb.properties.len());
771          bytes += wb.args.len() * 16;
772          for arg in &wb.args {
773            if *budget == 0 {
774              break;
775            }
776            if let Some(d) = arg {
777              bytes += d.estimate_bytes_into(budget);
778            }
779          }
780        }
781        bytes
782      },
783      DigestedData::List(l) => {
784        let mut bytes = NODE + 48;
785        if let Ok(lb) = l.try_borrow() {
786          bytes += map_bytes(lb.properties.len());
787          bytes += lb.boxes.len() * 8;
788          for child in &lb.boxes {
789            if *budget == 0 {
790              break;
791            }
792            bytes += child.estimate_bytes_into(budget);
793          }
794        }
795        bytes
796      },
797      DigestedData::Postponed(_) => NODE + 32,
798      DigestedData::Comment(_) => NODE + 16,
799      DigestedData::Alignment(_) | DigestedData::KeyVals(_) | DigestedData::RegisterValue(_) => {
800        NODE
801      },
802    }
803  }
804
805  // convenience subset of NumericOps, added here for now as an experiment:
806  /// Obtain the i64 value of the digested object, iff it wraps a `RegisterValue`
807  pub fn value_of(&self) -> i64 {
808    match &*self.0 {
809      DigestedData::RegisterValue(rv) => rv.clone().value_of(),
810      _ => 0,
811    }
812  }
813  /// Obtain a Dimension from the digested object, iff it wraps a `RegisterValue`
814  pub fn get_dimension(&self) -> Option<Dimension> {
815    match &*self.0 {
816      DigestedData::RegisterValue(rv) => Some(Dimension::from(rv)),
817      _ => None,
818    }
819  }
820  /// Obtain the f64 value of the digested object, iff it wraps a `RegisterValue`
821  pub fn pt_value(&self, prec: Option<u8>) -> f64 {
822    match &*self.0 {
823      DigestedData::RegisterValue(rv) => rv.clone().pt_value(prec),
824      _ => 0.0,
825    }
826  }
827  /// Predicate check - true if `any` element of the current object passes the check
828  pub fn any<F>(&self, mut check: F) -> bool
829  where F: FnMut(&Self) -> bool {
830    use DigestedData::*;
831    match &*self.0 {
832      TBox(_) | Whatsit(_) | Alignment(_) | Postponed(_) | KeyVals(_) | RegisterValue(_) => {
833        check(self)
834      },
835      Comment(_) => true,
836      List(l) => l.borrow().boxes.iter().any(check),
837    }
838  }
839
840  /// Predicate check - true if `all` elements of the current object passes the check
841  pub fn all<F>(&self, mut check: F) -> bool
842  where F: FnMut(&Self) -> bool {
843    use DigestedData::*;
844    match &*self.0 {
845      TBox(_) | Whatsit(_) | Alignment(_) | Postponed(_) | KeyVals(_) | RegisterValue(_) => {
846        check(self)
847      },
848      Comment(_) => true,
849      List(l) => l.borrow().boxes.iter().all(check),
850    }
851  }
852
853  /// Predicate check - delegates to `.is_empty()` of the underlying data
854  pub fn is_empty(&self) -> Result<bool> {
855    use DigestedData::*;
856    Ok(match *self.0 {
857      TBox(ref b) => b.borrow().is_empty(),
858      List(ref l) => l.borrow().is_empty(),
859      Whatsit(ref w) => w.borrow().is_empty()?,
860      Postponed(ref tks) => tks.is_empty(),
861      _ => false, // Comments, RegisterValues, Alignments, KeyVals are non-empty
862    })
863  }
864
865  /// A strut: something that occupies height but leaves no ink — an
866  /// `invisible` zero-width `\vrule`, or an `\hbox`/`\vbox` whatsit whose
867  /// `content_box` holds only struts and skippable material (latex.ltx:12596's
868  /// `\strutbox`, which `\strut` `\unhcopy`s into every TeXbook
869  /// `\halign{\strut#&…}` template cell — halignatt.tex). An alignment treats
870  /// a strut-only cell as empty (Perl's `isrule` test, Alignment.pm L459-462,
871  /// extended; its `isSkippable` L514 already looks through `content_box`).
872  /// Guard: `perfect_kernel_batch54::zero_width_vrule_is_a_strut_not_a_border`.
873  pub fn is_strut(&self) -> bool {
874    let DigestedData::Whatsit(w) = self.data() else {
875      return false;
876    };
877    let w = w.borrow();
878    if w.get_property_bool("alignmentPreserve") {
879      return false;
880    }
881    if w.get_property_bool("invisible") {
882      return true;
883    }
884    // A box counts only when it actually holds a strut: `\null` (`\hbox{}`)
885    // stays what Perl's peel sees, an opaque box.
886    match w.get_property("content_box") {
887      Some(prop) => matches!(
888        &*prop,
889        Stored::Digested(cb) if {
890          let inner = cb.unlist_ref();
891          inner.iter().any(|b| b.is_strut())
892            && inner.iter().all(|b| b.is_strut() || b.is_skippable())
893        }
894      ),
895      None => false,
896    }
897  }
898
899  /// A table cell's boxes that hold nothing but a paragraph cell (`p{}`/`m{}`/`b{}`, the `\lx@tabular@p@` box,
900  /// tex_tables.rs) with a skippable body, and skippable material: a cell a row span may cover, though
901  /// [`Self::is_skippable`] (Perl's `isSkippable`) counts the box as content. KNOWN_PERL_ERRORS #1015.
902  pub fn is_empty_paragraph_cell(&self) -> bool {
903    use DigestedData::*;
904    match *self.0 {
905      List(ref l) => {
906        let l = l.borrow();
907        !l.get_property_bool("alignmentPreserve")
908          && l
909            .boxes
910            .iter()
911            .all(|d| d.is_skippable() || d.is_empty_paragraph_cell())
912      },
913      Whatsit(ref w) => match w.borrow().get_property("paragraph_cell_body") {
914        Some(prop) => matches!(&*prop, Stored::Digested(body) if body.is_skippable()),
915        None => false,
916      },
917      _ => false,
918    }
919  }
920
921  /// Check if all items are "empty" or only spaces or otherwise skippable in a table cell.
922  /// Perl: isSkippable (Alignment.pm L484-508)
923  pub fn is_skippable(&self) -> bool {
924    use DigestedData::*;
925    match *self.0 {
926      Comment(_) => true,
927      TBox(ref b) => {
928        let b = b.borrow();
929        if b.get_property_bool("alignmentPreserve") {
930          // Perl PR #2767: explicitly preserved content is never skippable
931          false
932        } else if b.get_property_bool("isEmpty")
933          || b.get_property_bool("isSpace")
934          || b.get_property_bool("alignmentSkippable")
935        {
936          true
937        } else {
938          // Perl: getString, check if only whitespace
939          b.get_string()
940            .ok()
941            .map(|s| s.trim().is_empty())
942            .unwrap_or(false)
943        }
944      },
945      List(ref l) => {
946        let l = l.borrow();
947        // Perl PR #2767: explicitly preserved content is never skippable
948        !l.get_property_bool("alignmentPreserve") && l.boxes.iter().all(|d| d.is_skippable())
949      },
950      Whatsit(ref w) => {
951        let w = w.borrow();
952        if w.get_property_bool("alignmentPreserve") {
953          // Perl PR #2767: explicitly preserved content is never skippable
954          false
955        } else if w.get_property_bool("isEmpty")
956          || w.get_property_bool("isSpace")
957          || w.get_property_bool("alignmentSkippable")
958        {
959          true
960        } else {
961          match w.get_body() {
962            Ok(Some(body)) => body.is_skippable(),
963            _ => {
964              match w.get_property("content_box") {
965                Some(ref prop) => {
966                  // Perl: $thing->getProperty('content_box') — for \hbox etc.
967                  match &**prop {
968                    Stored::Digested(cb) => cb.is_skippable(),
969                    _ => false,
970                  }
971                },
972                _ => false,
973              }
974            },
975          }
976        }
977      },
978      Postponed(ref tks) => {
979        // Perl checks token catcodes: letters, others, active, CS are NOT skippable
980        tks.unlist_ref().iter().all(|t| {
981          let cc = t.get_catcode();
982          !matches!(
983            cc,
984            crate::token::Catcode::LETTER
985              | crate::token::Catcode::OTHER
986              | crate::token::Catcode::ACTIVE
987              | crate::token::Catcode::CS
988          )
989        })
990      },
991      _ => false,
992    }
993  }
994
995  /// Provide a way of emulating an `Undigested` argument, by requesting
996  /// raw tokens, only when they are preserved -- empty otherwise.
997  pub fn raw_tokens(&self) -> Option<&Tokens> {
998    match *self.0 {
999      DigestedData::Postponed(ref tks) => Some(tks),
1000      _ => None,
1001    }
1002  }
1003
1004  /// builds an attribute-friendly String form of the digested object, suitable for XML attributes
1005  /// (Perl `toAttribute`): a list joins its items' forms (List.pm:85-87); a whatsit whose definition
1006  /// gives an attribute form — carried here as its `attributeForm` property, which Perl also reads first
1007  /// (Whatsit.pm:217-228) — is that text, `\hskip`'s spaces (TeX_Glue.pool.ltxml:85) rather than the
1008  /// reverted `\enskip`; anything else is its string.
1009  pub fn to_attribute(&self) -> String {
1010    match *self.0 {
1011      DigestedData::RegisterValue(ref v) => v.to_attribute(),
1012      DigestedData::List(ref list) => list
1013        .borrow()
1014        .boxes
1015        .iter()
1016        .map(Digested::to_attribute)
1017        .collect(),
1018      DigestedData::Whatsit(ref whatsit) => {
1019        match whatsit.borrow().properties.get("attributeForm") {
1020          Some(Stored::String(form)) => arena::with(*form, str::to_string),
1021          _ => self.to_string(),
1022        }
1023      },
1024      _ => self.to_string(),
1025    }
1026  }
1027
1028  /// Reverts a digested object to `Tokens` and extracts a TeX-near string representation of its
1029  /// content
1030  pub fn untex(&self) -> Result<String> { Ok(self.revert()?.untex()) }
1031
1032  pub fn alignment_cell(&self) -> Option<&RefCell<Alignment>> {
1033    if let DigestedData::Alignment(ref alignment) = *self.0 {
1034      Some(alignment)
1035    } else {
1036      None
1037    }
1038  }
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043  use super::*;
1044
1045  /// `DigestedData` is `Rc`-allocated once per digested box, and a very large
1046  /// document holds millions of them alive at once (issue #361 measured 11.5 M
1047  /// live at peak), so every byte in this enum is paid per box. This budget
1048  /// guards against a fat variant silently re-inflating it.
1049  ///
1050  /// The ceiling is currently `Whatsit` (`RefCell<Whatsit>` = 120 B) +
1051  /// discriminant = 128 B, with the historically oversized payloads contained:
1052  /// `List.font` is `Rc`-shared (M1), `KeyVals` is boxed (M2), and `Whatsit`'s
1053  /// two reversion-cache slots are boxed (M4). Below this sit `TBox`/`List` at
1054  /// 96 B, so 104 B is the floor for any further variant boxing.
1055  ///
1056  /// Raise this only with a deliberate justification, never to paper over an
1057  /// accidental blow-up — box the offending payload instead (see the `KeyVals`
1058  /// doc for when that pays: the payload must be *rare*, or the extra
1059  /// allocation costs more than the per-box byte it saves).
1060  #[test]
1061  fn digested_data_size_budget() {
1062    let size = size_of::<DigestedData>();
1063    assert!(
1064      size <= 128,
1065      "DigestedData grew to {size} B (budget 128). A large payload re-inflated \
1066       the per-box footprint — box it (cf. KeyVals, issue #361) rather than \
1067       raising this budget."
1068    );
1069  }
1070
1071  #[test]
1072  fn digested_from_tokens_roundtrip() {
1073    let ts = Tokens::new(vec![]);
1074    let d: Digested = ts.into();
1075    // Default variant is Postponed for raw Tokens.
1076    match &*d.0 {
1077      DigestedData::Postponed(_) => {},
1078      other => panic!("expected Postponed, got {other:?}"),
1079    }
1080  }
1081
1082  #[test]
1083  fn digested_from_string_is_postponed_tokens() {
1084    let d: Digested = "abc".to_string().into();
1085    match &*d.0 {
1086      DigestedData::Postponed(_) => {},
1087      other => panic!("expected Postponed, got {other:?}"),
1088    }
1089  }
1090
1091  #[test]
1092  fn digested_from_tbox_is_tbox_variant() {
1093    let tb = Tbox::default();
1094    let d: Digested = tb.into();
1095    match &*d.0 {
1096      DigestedData::TBox(_) => {},
1097      other => panic!("expected TBox, got {other:?}"),
1098    }
1099  }
1100
1101  #[test]
1102  fn digested_from_list_is_list_variant() {
1103    let l = List::default();
1104    let d: Digested = l.into();
1105    match &*d.0 {
1106      DigestedData::List(_) => {},
1107      other => panic!("expected List, got {other:?}"),
1108    }
1109  }
1110
1111  #[test]
1112  fn digested_from_whatsit_is_whatsit_variant() {
1113    let w = Whatsit::default();
1114    let d: Digested = w.into();
1115    match &*d.0 {
1116      DigestedData::Whatsit(_) => {},
1117      other => panic!("expected Whatsit, got {other:?}"),
1118    }
1119  }
1120
1121  #[test]
1122  fn digested_from_keyvals_is_keyvals_variant() {
1123    let kv = KeyVals::default();
1124    let d: Digested = kv.into();
1125    match &*d.0 {
1126      DigestedData::KeyVals(_) => {},
1127      other => panic!("expected KeyVals, got {other:?}"),
1128    }
1129  }
1130
1131  #[test]
1132  fn digested_clone_shares_rc() {
1133    // Digested is Rc-wrapped; clone should share the same underlying
1134    // RefCell, not a deep copy.
1135    let tb = Tbox::default();
1136    let a: Digested = tb.into();
1137    let b = a.clone();
1138    // Rc strong count is at least 2 now.
1139    assert!(Rc::strong_count(&a.0) >= 2);
1140    assert!(Rc::strong_count(&b.0) >= 2);
1141  }
1142
1143  #[test]
1144  fn digested_ref_to_option_some() {
1145    let d: Digested = Tbox::default().into();
1146    let o: Option<Digested> = (&d).into();
1147    assert!(o.is_some());
1148  }
1149
1150  fn tbox_with(text: &str) -> Digested {
1151    Tbox {
1152      text: arena::pin(text),
1153      ..Default::default()
1154    }
1155    .into()
1156  }
1157  fn list_of(items: Vec<Digested>) -> Digested {
1158    List {
1159      boxes: items,
1160      ..Default::default()
1161    }
1162    .into()
1163  }
1164
1165  /// Iteratively dismantle a deeply-nested `Digested` so its `Drop` does NOT
1166  /// recurse once per nesting level. A deep singly-owned `Rc<DigestedData>`
1167  /// chain otherwise overflows the small per-test-thread stack under CI's
1168  /// `--test-threads=2` (a SIGABRT that passes locally on the larger default
1169  /// stack). Descends into the FIRST child of each `List`, dropping the
1170  /// shallow remainder (leaf boxes + the now-childless outer) as it goes, so
1171  /// teardown is O(1) in stack depth. (The analogous PRODUCTION concern — a
1172  /// boxing-depth-cap Fatal unwinding a deep structure — is tracked
1173  /// separately; the real box-list runaway is a WIDE `Vec`, already
1174  /// iteratively dropped.)
1175  fn drain_nest(mut cur: Digested) {
1176    loop {
1177      let child = if let DigestedData::List(l) = &*cur.0 {
1178        let mut boxes = std::mem::take(&mut l.borrow_mut().boxes);
1179        (!boxes.is_empty()).then(|| boxes.swap_remove(0))
1180      } else {
1181        None
1182      };
1183      match child {
1184        Some(c) => cur = c,
1185        None => break,
1186      }
1187    }
1188  }
1189
1190  #[test]
1191  fn cycle_fingerprint_is_content_aware_for_lists() {
1192    // The whole point of recursing into a List (rather than hashing its length
1193    // alone): two lists of the SAME length but DIFFERENT content must not
1194    // collide, or the stomach cycle guard would false-positive.
1195    let ab = list_of(vec![tbox_with("a"), tbox_with("b")]);
1196    let ac = list_of(vec![tbox_with("a"), tbox_with("c")]);
1197    assert_ne!(
1198      ab.cycle_fingerprint(),
1199      ac.cycle_fingerprint(),
1200      "same-length lists with different content must NOT share a fingerprint"
1201    );
1202    // ...while structurally identical lists DO (so real cycles are still caught).
1203    let ab2 = list_of(vec![tbox_with("a"), tbox_with("b")]);
1204    assert_eq!(ab.cycle_fingerprint(), ab2.cycle_fingerprint());
1205  }
1206
1207  #[test]
1208  fn cycle_fingerprint_distinguishes_register_amounts() {
1209    // Two dots of a PiCTeX line differ only by their `\raise` (0801.0709): equal kinds, different amounts.
1210    let raise = |sp: i64| Digested::from(RegisterValue::Dimension(Dimension(sp)));
1211    assert_ne!(
1212      raise(65536).cycle_fingerprint(),
1213      raise(131072).cycle_fingerprint()
1214    );
1215    assert_eq!(
1216      raise(65536).cycle_fingerprint(),
1217      raise(65536).cycle_fingerprint()
1218    );
1219  }
1220
1221  #[test]
1222  fn cycle_fingerprint_distinguishes_text_and_is_bounded() {
1223    assert_ne!(
1224      tbox_with("a").cycle_fingerprint(),
1225      tbox_with("b").cycle_fingerprint()
1226    );
1227    // A pathologically deep/wide nest must still return (budget-bounded) — and
1228    // remain distinguishable from a shallow one.
1229    let mut deep = tbox_with("z");
1230    for _ in 0..10_000 {
1231      deep = list_of(vec![deep, tbox_with("z")]);
1232    }
1233    let _ = deep.cycle_fingerprint(); // must not hang / overflow
1234    assert_ne!(deep.cycle_fingerprint(), tbox_with("z").cycle_fingerprint());
1235    drain_nest(deep); // O(1)-stack teardown — see `drain_nest`.
1236  }
1237
1238  #[test]
1239  fn estimate_bytes_is_positive_and_nesting_increases_it() {
1240    // Every box has some positive footprint.
1241    assert!(tbox_with("a").estimate_bytes() > 0);
1242    // A list of N boxes weighs more than a single box (the children count).
1243    let one = list_of(vec![tbox_with("a")]);
1244    let many = list_of(vec![
1245      tbox_with("a"),
1246      tbox_with("b"),
1247      tbox_with("c"),
1248      tbox_with("d"),
1249    ]);
1250    assert!(
1251      many.estimate_bytes() > one.estimate_bytes(),
1252      "a wider list must estimate heavier than a narrow one"
1253    );
1254  }
1255
1256  #[test]
1257  fn estimate_bytes_is_cost_bounded_for_deep_nests() {
1258    // A pathologically deep nest must terminate (EB_BUDGET) without hanging /
1259    // overflowing, and still return a finite positive estimate.
1260    let mut deep = tbox_with("z");
1261    for _ in 0..100_000 {
1262      deep = list_of(vec![deep]);
1263    }
1264    let est = deep.estimate_bytes();
1265    assert!(est > 0);
1266    // Budget-bounded: the walk visits at most EB_BUDGET nodes, so a 100k-deep
1267    // nest cannot estimate more than roughly EB_BUDGET node-overheads.
1268    assert!(
1269      est < (EB_BUDGET as usize) * 4096,
1270      "estimate must stay bounded regardless of nest depth (got {est})"
1271    );
1272    drain_nest(deep); // O(1)-stack teardown — see `drain_nest`.
1273  }
1274}