Skip to main content

einvoice_xslt_exec/
output.rs

1//! The result of a transformation kept compactly ([`CompactOutput`]), and what reads it
2//! as it is written ([`ResultObserver`]).
3
4use std::collections::HashMap;
5use std::collections::hash_map::Entry;
6use std::fmt::{self, Write as _};
7use std::hash::{BuildHasherDefault, DefaultHasher, Hash as _, Hasher};
8
9use einvoice_xpath::QName;
10
11use crate::error::{Result, err};
12
13/// The serialized result document of
14/// [`Executable::transform_compact`](crate::Executable::transform_compact), kept as a
15/// sequence of pieces, each distinct piece stored once. A piece is what the serializer
16/// writes from one tag to the next written in full: an element with its indentation, a
17/// start tag, or text with the end tag that follows.
18///
19/// A compiled Schematron writes the same `svrl:fired-rule` element, with the same
20/// indentation, each time a rule fires, and the same message for each node an
21/// assertion fails on: on a large document, its SVRL report is mostly copies of a few
22/// hundred pieces, and kept this way takes four bytes per fired rule instead of the
23/// length of the element. The distinct pieces are kept in blocks that are never
24/// reallocated, so that the store does not grow by copying.
25///
26/// Two outputs are equal when their texts are; [`fmt::Display`] writes the text and
27/// [`fmt::Debug`] shows it as [`String`]'s does.
28#[derive(Clone, Default)]
29pub struct CompactOutput {
30    /// The distinct pieces, one after the other, in blocks of up to [`BLOCK`] bytes (or
31    /// of one larger piece); a piece is in one block.
32    blocks: Vec<String>,
33    /// Each distinct piece, by number: where it is in `blocks`.
34    spans: Vec<Span>,
35    /// The text: the numbers of its pieces, in order.
36    sequence: Vec<u32>,
37    /// The length of the text, in bytes.
38    len: usize,
39}
40
41/// Where a distinct piece is: its block, and its byte range in it.
42#[derive(Debug, Clone, Copy)]
43struct Span {
44    block: u32,
45    start: u32,
46    end: u32,
47}
48
49/// The size of the blocks of distinct pieces, once there are a few.
50const BLOCK: usize = 64 << 10;
51
52impl CompactOutput {
53    /// The length of the text, in bytes.
54    #[must_use]
55    pub const fn len(&self) -> usize {
56        self.len
57    }
58
59    /// Whether the text is empty.
60    #[must_use]
61    pub const fn is_empty(&self) -> bool {
62        self.len == 0
63    }
64
65    /// The pieces of the text, in order: their concatenation is the text.
66    pub fn pieces(&self) -> impl Iterator<Item = &str> {
67        self.sequence.iter().map(|&id| self.piece(id))
68    }
69
70    /// The text, in a string of the exact length.
71    #[must_use]
72    pub fn to_text(&self) -> String {
73        let mut text = String::with_capacity(self.len);
74        for piece in self.pieces() {
75            text.push_str(piece);
76        }
77        text
78    }
79
80    /// Releases the room its buffers have beyond what they hold.
81    pub fn shrink_to_fit(&mut self) {
82        if let Some(last) = self.blocks.last_mut() {
83            last.shrink_to_fit();
84        }
85        self.blocks.shrink_to_fit();
86        self.spans.shrink_to_fit();
87        self.sequence.shrink_to_fit();
88    }
89
90    fn piece(&self, id: u32) -> &str {
91        let span = self.spans[id as usize];
92        &self.blocks[span.block as usize][span.start as usize..span.end as usize]
93    }
94
95    /// Stores a new distinct piece: its number.
96    fn add(&mut self, piece: &str) -> Result<u32> {
97        let fits = self
98            .blocks
99            .last()
100            .is_some_and(|b| b.capacity() - b.len() >= piece.len());
101        if !fits {
102            // Blocks grow from 1 KiB to BLOCK, each as large as those before it
103            // together: a small result takes little room, a large one few blocks.
104            let before: usize = self.blocks.iter().map(String::capacity).sum();
105            let size = before.clamp(1 << 10, BLOCK).max(piece.len());
106            self.blocks.push(String::with_capacity(size));
107        }
108        let block = self.blocks.len() - 1;
109        let text = &mut self.blocks[block];
110        let start = text.len();
111        text.push_str(piece);
112        let (Ok(id), Ok(block), Ok(start), Ok(end)) = (
113            u32::try_from(self.spans.len()),
114            u32::try_from(block),
115            u32::try_from(start),
116            u32::try_from(text.len()),
117        ) else {
118            return err(
119                "INTERNAL",
120                "the result has more than 2^32 distinct pieces or a piece of 4 GiB",
121            );
122        };
123        self.spans.push(Span { block, start, end });
124        Ok(id)
125    }
126
127    /// Whether the text is `text`, compared piece by piece.
128    fn text_is(&self, text: &str) -> bool {
129        if self.len != text.len() {
130            return false;
131        }
132        let mut rest = text.as_bytes();
133        for piece in self.pieces() {
134            let (head, tail) = rest.split_at(piece.len());
135            if head != piece.as_bytes() {
136                return false;
137            }
138            rest = tail;
139        }
140        true
141    }
142}
143
144impl PartialEq for CompactOutput {
145    fn eq(&self, other: &Self) -> bool {
146        if self.len != other.len {
147            return false;
148        }
149        // Both texts walked piece by piece, the pieces cut at different places.
150        let mut left = self.pieces().map(str::as_bytes);
151        let mut right = other.pieces().map(str::as_bytes);
152        let (mut a, mut b): (&[u8], &[u8]) = (&[], &[]);
153        loop {
154            if a.is_empty() {
155                match left.next() {
156                    Some(next) => a = next,
157                    None => return b.is_empty() && right.all(<[u8]>::is_empty),
158                }
159                continue;
160            }
161            if b.is_empty() {
162                match right.next() {
163                    Some(next) => b = next,
164                    None => return false,
165                }
166                continue;
167            }
168            let n = a.len().min(b.len());
169            if a[..n] != b[..n] {
170                return false;
171            }
172            a = &a[n..];
173            b = &b[n..];
174        }
175    }
176}
177
178impl Eq for CompactOutput {}
179
180impl PartialEq<str> for CompactOutput {
181    fn eq(&self, other: &str) -> bool {
182        self.text_is(other)
183    }
184}
185
186impl PartialEq<&str> for CompactOutput {
187    fn eq(&self, other: &&str) -> bool {
188        self.text_is(other)
189    }
190}
191
192impl fmt::Display for CompactOutput {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        for piece in self.pieces() {
195            f.write_str(piece)?;
196        }
197        Ok(())
198    }
199}
200
201impl fmt::Debug for CompactOutput {
202    /// The text as [`String`]'s `Debug` shows it: quoted, each character escaped as
203    /// [`char::escape_debug`] escapes it, except the single quote.
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_char('"')?;
206        for piece in self.pieces() {
207            for c in piece.chars() {
208                if c == '\'' {
209                    f.write_char(c)?;
210                } else {
211                    for e in c.escape_debug() {
212                        f.write_char(e)?;
213                    }
214                }
215            }
216        }
217        f.write_char('"')
218    }
219}
220
221impl From<&str> for CompactOutput {
222    /// The text as a single piece (none for a text of 4 GiB or more, which the
223    /// store cannot hold).
224    fn from(text: &str) -> Self {
225        let mut builder = CompactBuilder::default();
226        if builder.push(text).is_err() {
227            return Self::default();
228        }
229        builder.finish()
230    }
231}
232
233/// A hasher for keys that are already hashes.
234#[derive(Debug, Default)]
235struct HashKey(u64);
236
237impl Hasher for HashKey {
238    fn finish(&self) -> u64 {
239        self.0
240    }
241
242    fn write(&mut self, bytes: &[u8]) {
243        for &b in bytes {
244            self.0 = self.0.rotate_left(8) ^ u64::from(b);
245        }
246    }
247
248    fn write_u64(&mut self, n: u64) {
249        self.0 = n;
250    }
251}
252
253/// Builds a [`CompactOutput`] piece by piece.
254#[derive(Debug, Default)]
255pub(crate) struct CompactBuilder {
256    output: CompactOutput,
257    /// The distinct pieces by the hash of their text. A piece whose hash is that of
258    /// another text is stored as a new distinct piece, not indexed.
259    index: HashMap<u64, u32, BuildHasherDefault<HashKey>>,
260}
261
262impl CompactBuilder {
263    /// Appends a piece.
264    pub(crate) fn push(&mut self, piece: &str) -> Result<()> {
265        if piece.is_empty() {
266            return Ok(());
267        }
268        let mut hasher = DefaultHasher::new();
269        piece.hash(&mut hasher);
270        let hash = hasher.finish();
271        let id = match self.index.entry(hash) {
272            Entry::Occupied(entry) if self.output.piece(*entry.get()) == piece => *entry.get(),
273            Entry::Occupied(_) => self.output.add(piece)?,
274            Entry::Vacant(vacant) => *vacant.insert(self.output.add(piece)?),
275        };
276        self.output.sequence.push(id);
277        self.output.len += piece.len();
278        Ok(())
279    }
280
281    /// Whether nothing was appended.
282    pub(crate) const fn is_empty(&self) -> bool {
283        self.output.is_empty()
284    }
285
286    pub(crate) fn finish(self) -> CompactOutput {
287        self.output
288    }
289}
290
291/// Reads the result document of
292/// [`Executable::transform_compact`](crate::Executable::transform_compact) as it is written, as a parser of its text
293/// would read it: the elements with their attributes, the character data (the
294/// whitespace the serializer writes to indent included, as text of the element it is
295/// in) and the comments, in document order. Nothing outside the document element but
296/// comments is reported: the serializer writes no text there but line ends.
297///
298/// The text it reads is well-formed, except in two cases a parser would refuse and the
299/// observer has to: a result with no element or more than one at its top, and a
300/// comment that contains `--` or ends with `-`.
301pub trait ResultObserver {
302    /// The start of an element: its name, and its attributes as written (namespace
303    /// declarations excluded; an attribute's prefix may differ from the one it was
304    /// constructed with, never its namespace).
305    fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]);
306    /// The end of the innermost open element.
307    fn end_element(&mut self);
308    /// Character data: adjacent calls make one text node.
309    fn text(&mut self, text: &str);
310    /// A comment.
311    fn comment(&mut self, text: &str);
312    /// A processing instruction: its target and its data. Ignored unless implemented.
313    fn processing_instruction(&mut self, target: &str, data: &str) {
314        let _ = (target, data);
315    }
316}
317
318/// Observes nothing.
319impl ResultObserver for () {
320    fn start_element(&mut self, _name: &QName, _attributes: &[(QName, String)]) {}
321    fn end_element(&mut self) {}
322    fn text(&mut self, _text: &str) {}
323    fn comment(&mut self, _text: &str) {}
324}
325
326/// The result of [`Executable::transform_compact`](crate::Executable::transform_compact).
327#[derive(Debug, Clone, PartialEq, Eq)]
328#[non_exhaustive]
329pub struct CompactTransformation {
330    /// The result document, serialized as `xsl:output` asks.
331    pub output: CompactOutput,
332    /// The warnings, as [`Transformation::warnings`](crate::Transformation::warnings).
333    pub warnings: Vec<String>,
334    /// The messages, as [`Transformation::messages`](crate::Transformation::messages).
335    pub messages: Vec<String>,
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    fn build(pieces: &[&str]) -> CompactOutput {
343        let mut builder = CompactBuilder::default();
344        for piece in pieces {
345            builder.push(piece).unwrap();
346        }
347        builder.finish()
348    }
349
350    #[test]
351    fn keeps_each_distinct_piece_once() {
352        let output = build(&["<a>", "\n <b/>", "", "\n <b/>", "x", "\n <b/>", "</a>"]);
353        assert_eq!(output.to_text(), "<a>\n <b/>\n <b/>x\n <b/></a>");
354        assert_eq!(output.len(), output.to_text().len());
355        assert_eq!(output.blocks, ["<a>\n <b/>x</a>"]);
356        assert_eq!(output.sequence, [0, 1, 1, 2, 1, 3]);
357        assert_eq!(output.to_string(), output.to_text());
358    }
359
360    #[test]
361    fn pieces_fill_blocks_and_a_larger_piece_has_its_own() {
362        let small = "x".repeat(1000);
363        let large = "y".repeat(BLOCK + 1);
364        let mut pieces: Vec<String> = (0..100).map(|i| format!("{i}{small}")).collect();
365        pieces.insert(30, large.clone());
366        pieces.push(large);
367        let refs: Vec<&str> = pieces.iter().map(String::as_str).collect();
368        let mut output = build(&refs);
369        assert_eq!(output.to_text(), pieces.concat());
370        // 101 distinct pieces: the large one is stored once.
371        assert_eq!(output.spans.len(), 101);
372        // Blocks of 1, 1, 2, 4, ... KiB, then of BLOCK.
373        let capacities: Vec<usize> = output.blocks.iter().map(String::capacity).collect();
374        assert_eq!(capacities[..4], [1 << 10, 1 << 10, 2 << 10, 4 << 10]);
375        assert!(capacities.contains(&(BLOCK + 1)), "{capacities:?}");
376        assert!(capacities.iter().all(|&c| c <= BLOCK + 1));
377        let distinct: usize = pieces.iter().take(101).map(String::len).sum();
378        assert_eq!(
379            output.blocks.iter().map(String::len).sum::<usize>(),
380            distinct
381        );
382        output.shrink_to_fit();
383        assert_eq!(output.to_text(), pieces.concat());
384    }
385
386    #[test]
387    fn equal_when_the_texts_are() {
388        let a = build(&["ab", "cd", "e"]);
389        let b = build(&["a", "bcde"]);
390        let c = build(&["ab", "cd", "f"]);
391        assert_eq!(a, b);
392        assert_ne!(a, c);
393        assert_ne!(a, build(&["ab", "cd"]));
394        assert_eq!(a, "abcde");
395        assert_ne!(a, "abcdf");
396        assert_eq!(CompactOutput::default(), "");
397        assert_eq!(CompactOutput::default(), build(&["", ""]));
398        assert_eq!(CompactOutput::from("abcde"), a);
399        assert_eq!(CompactOutput::from(""), CompactOutput::default());
400    }
401
402    #[test]
403    fn debug_as_a_string() {
404        let text = "<a b=\"'\">\n\t\\ \u{301}é\u{0}</a>";
405        let output = build(&["<a b=\"'\">", "\n\t\\ \u{301}", "é\u{0}</a>"]);
406        assert_eq!(format!("{output:?}"), format!("{text:?}"));
407    }
408}