Skip to main content

telegram_rich/document/
measure.rs

1//! Measuring a [`Document`] against [`Limits`](crate::Limits).
2
3use super::{Block, Document, Inline, ListItem, Media, Table};
4use crate::limits::Stats;
5
6impl Document {
7    /// Measures the document.
8    ///
9    /// Counting is conservative: list items, table rows and the content blocks
10    /// of containers are all counted as blocks, and every formatting wrapper
11    /// adds one nesting level.
12    pub fn stats(&self) -> Stats {
13        let mut s = Stats::default();
14        for b in &self.blocks {
15            block_stats(b, 1, &mut s);
16        }
17        s
18    }
19}
20
21/// Cost of a single block in the dimensions that truncation trades off.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23pub(crate) struct Cost {
24    pub chars: usize,
25    pub blocks: usize,
26    pub media: usize,
27}
28
29impl Cost {
30    pub fn of_block(b: &Block) -> Cost {
31        let mut s = Stats::default();
32        block_stats(b, 1, &mut s);
33        Cost {
34            chars: s.chars,
35            blocks: s.blocks,
36            media: s.media,
37        }
38    }
39
40    pub fn of_blocks(bs: &[Block]) -> Cost {
41        bs.iter()
42            .map(Cost::of_block)
43            .fold(Cost::default(), |a, b| a + b)
44    }
45
46    pub fn fits_in(&self, budget: &Cost) -> bool {
47        self.chars <= budget.chars && self.blocks <= budget.blocks && self.media <= budget.media
48    }
49
50    pub fn saturating_sub(&self, other: &Cost) -> Cost {
51        Cost {
52            chars: self.chars.saturating_sub(other.chars),
53            blocks: self.blocks.saturating_sub(other.blocks),
54            media: self.media.saturating_sub(other.media),
55        }
56    }
57}
58
59impl std::ops::Add for Cost {
60    type Output = Cost;
61    fn add(self, o: Cost) -> Cost {
62        Cost {
63            chars: self.chars + o.chars,
64            blocks: self.blocks + o.blocks,
65            media: self.media + o.media,
66        }
67    }
68}
69
70fn bump_depth(s: &mut Stats, d: usize) {
71    s.depth = s.depth.max(d);
72}
73
74fn block_stats(b: &Block, depth: usize, s: &mut Stats) {
75    s.blocks += 1;
76    bump_depth(s, depth);
77    match b {
78        Block::Paragraph(inl) | Block::Footer(inl) | Block::Heading { content: inl, .. } => {
79            inlines_stats(inl, depth, s)
80        }
81        Block::Preformatted { text, .. } | Block::MathBlock(text) => {
82            s.chars += text.chars().count()
83        }
84        Block::Divider | Block::Anchor(_) => {}
85        Block::List { items, .. } => {
86            for it in items {
87                item_stats(it, depth + 1, s);
88            }
89        }
90        Block::Quote { blocks, credit } => {
91            for c in blocks {
92                block_stats(c, depth + 1, s);
93            }
94            opt_inlines_stats(credit, depth, s);
95        }
96        Block::ExpandableQuote { content, credit } | Block::PullQuote { content, credit } => {
97            inlines_stats(content, depth, s);
98            opt_inlines_stats(credit, depth, s);
99        }
100        Block::Media(m) => media_stats(m, depth, s),
101        Block::Table(t) => table_stats(t, depth, s),
102        Block::Details {
103            summary, blocks, ..
104        } => {
105            inlines_stats(summary, depth, s);
106            for c in blocks {
107                block_stats(c, depth + 1, s);
108            }
109        }
110        Block::Buttons { buttons, .. } => {
111            for btn in buttons {
112                s.chars += btn.text.chars().count();
113            }
114        }
115    }
116}
117
118fn item_stats(it: &ListItem, depth: usize, s: &mut Stats) {
119    s.blocks += 1;
120    bump_depth(s, depth);
121    for c in &it.blocks {
122        block_stats(c, depth + 1, s);
123    }
124}
125
126fn media_stats(m: &Media, depth: usize, s: &mut Stats) {
127    s.media += 1;
128    opt_inlines_stats(&m.caption, depth, s);
129    opt_inlines_stats(&m.credit, depth, s);
130}
131
132fn table_stats(t: &Table, depth: usize, s: &mut Stats) {
133    opt_inlines_stats(&t.caption, depth, s);
134    for row in &t.rows {
135        s.blocks += 1;
136        bump_depth(s, depth + 1);
137        let cols: usize = row
138            .iter()
139            .map(|c| c.colspan.unwrap_or(1).max(1) as usize)
140            .sum();
141        s.max_table_columns = s.max_table_columns.max(cols);
142        for cell in row {
143            inlines_stats(&cell.content, depth + 1, s);
144        }
145    }
146}
147
148fn opt_inlines_stats(inl: &Option<Vec<Inline>>, depth: usize, s: &mut Stats) {
149    if let Some(i) = inl {
150        inlines_stats(i, depth, s);
151    }
152}
153
154pub(crate) fn inlines_stats(inl: &[Inline], depth: usize, s: &mut Stats) {
155    for i in inl {
156        match i {
157            Inline::Text(t) | Inline::Code(t) | Inline::Math(t) => s.chars += t.chars().count(),
158            Inline::LineBreak => s.chars += 1,
159            Inline::Bold(c)
160            | Inline::Italic(c)
161            | Inline::Underline(c)
162            | Inline::Strikethrough(c)
163            | Inline::Spoiler(c)
164            | Inline::Marked(c)
165            | Inline::Subscript(c)
166            | Inline::Superscript(c)
167            | Inline::Link { content: c, .. } => {
168                bump_depth(s, depth + 1);
169                inlines_stats(c, depth + 1, s);
170            }
171        }
172    }
173}
174
175/// Number of characters of inline content.
176pub(crate) fn inline_chars(inl: &[Inline]) -> usize {
177    let mut s = Stats::default();
178    inlines_stats(inl, 0, &mut s);
179    s.chars
180}