1use 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#[derive(Clone)]
40pub struct Digested(Rc<DigestedData>);
41pub enum DigestedData {
51 TBox(RefCell<Tbox>),
53 Whatsit(RefCell<Whatsit>),
55 Alignment(Box<RefCell<Alignment>>),
57 List(RefCell<List>),
59 Postponed(Tokens),
61 KeyVals(Box<KeyVals>),
72 RegisterValue(RegisterValue),
74 Comment(Comment),
76}
77
78impl 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
162impl<'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
222impl 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 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(), RegisterValue(ref rv) => rv.get_locator(),
289 Postponed(ref _t) => None, }
291 }
292 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 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 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()), RegisterValue(_rv) => Ok(Vec::new()), }
380 }
381
382 fn with_properties<R, FnR>(&self, caller: FnR) -> R
383 where FnR: FnOnce(&HashMap<Stored>) -> R {
384 use DigestedData::*;
385 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 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 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 fn get_font(&self) -> Result<Option<Rc<Font>>> {
504 use DigestedData::*;
505 match *self.0 {
506 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 fn compute_size(&self, options: HashMap<Stored>) -> Result<(Dimension, Dimension, Dimension)> {
524 use DigestedData::*;
525 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
555const FP_BUDGET: u32 = 48;
559
560pub(crate) const EB_BUDGET: u32 = 256;
565
566impl Digested {
567 pub fn try_set_property<T: Into<Stored>>(&self, key: &str, value: T) -> bool {
570 use DigestedData::*;
571 match *self.0 {
572 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, }
588 }
589
590 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 pub fn data(&self) -> &DigestedData { &self.0 }
612
613 pub fn strong_count(&self) -> usize { Rc::strong_count(&self.0) }
617
618 pub fn as_ptr(&self) -> *const DigestedData { Rc::as_ptr(&self.0) }
620
621 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 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 (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 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 pub fn estimate_bytes(&self) -> usize {
734 let mut budget: u32 = EB_BUDGET;
735 self.estimate_bytes_into(&mut budget)
736 }
737
738 fn estimate_bytes_into(&self, budget: &mut u32) -> usize {
741 if *budget == 0 {
742 return 0;
743 }
744 *budget -= 1;
745 const NODE: usize = 64;
748 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; }
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 pub fn value_of(&self) -> i64 {
808 match &*self.0 {
809 DigestedData::RegisterValue(rv) => rv.clone().value_of(),
810 _ => 0,
811 }
812 }
813 pub fn get_dimension(&self) -> Option<Dimension> {
815 match &*self.0 {
816 DigestedData::RegisterValue(rv) => Some(Dimension::from(rv)),
817 _ => None,
818 }
819 }
820 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 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 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 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, })
863 }
864
865 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 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 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 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 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 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 !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 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 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 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 pub fn raw_tokens(&self) -> Option<&Tokens> {
998 match *self.0 {
999 DigestedData::Postponed(ref tks) => Some(tks),
1000 _ => None,
1001 }
1002 }
1003
1004 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 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 #[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 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 let tb = Tbox::default();
1136 let a: Digested = tb.into();
1137 let b = a.clone();
1138 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 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 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 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 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 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(); assert_ne!(deep.cycle_fingerprint(), tbox_with("z").cycle_fingerprint());
1235 drain_nest(deep); }
1237
1238 #[test]
1239 fn estimate_bytes_is_positive_and_nesting_increases_it() {
1240 assert!(tbox_with("a").estimate_bytes() > 0);
1242 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 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 assert!(
1269 est < (EB_BUDGET as usize) * 4096,
1270 "estimate must stay bounded regardless of nest depth (got {est})"
1271 );
1272 drain_nest(deep); }
1274}