1use 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#[derive(Clone, Default)]
29pub struct CompactOutput {
30 blocks: Vec<String>,
33 spans: Vec<Span>,
35 sequence: Vec<u32>,
37 len: usize,
39}
40
41#[derive(Debug, Clone, Copy)]
43struct Span {
44 block: u32,
45 start: u32,
46 end: u32,
47}
48
49const BLOCK: usize = 64 << 10;
51
52impl CompactOutput {
53 #[must_use]
55 pub const fn len(&self) -> usize {
56 self.len
57 }
58
59 #[must_use]
61 pub const fn is_empty(&self) -> bool {
62 self.len == 0
63 }
64
65 pub fn pieces(&self) -> impl Iterator<Item = &str> {
67 self.sequence.iter().map(|&id| self.piece(id))
68 }
69
70 #[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 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 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 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 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 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 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 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#[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#[derive(Debug, Default)]
255pub(crate) struct CompactBuilder {
256 output: CompactOutput,
257 index: HashMap<u64, u32, BuildHasherDefault<HashKey>>,
260}
261
262impl CompactBuilder {
263 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 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
291pub trait ResultObserver {
302 fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]);
306 fn end_element(&mut self);
308 fn text(&mut self, text: &str);
310 fn comment(&mut self, text: &str);
312 fn processing_instruction(&mut self, target: &str, data: &str) {
314 let _ = (target, data);
315 }
316}
317
318impl 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#[derive(Debug, Clone, PartialEq, Eq)]
328#[non_exhaustive]
329pub struct CompactTransformation {
330 pub output: CompactOutput,
332 pub warnings: Vec<String>,
334 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 assert_eq!(output.spans.len(), 101);
372 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}