html-to-markdown-rs 3.18.4

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Unit tests of the output: the places after each change, and the count of work.

use super::{Checkpoint, ControlEnds, OpenControl, OutputText, PlainOutput};

/// One change of an output.
#[derive(Clone, Copy)]
enum Step {
    Text(&'static str),
    Control(&'static str),
    Start,
    Finish,
    Options(&'static str),
    EndBlock,
    Open,
    Rollback,
    Commit,
}

/// Fails when the start of an open control is not a place in the text, or when the starts
/// do not rise.
fn assert_control_starts_are_true(output: &PlainOutput, context: &str) {
    let starts: Vec<usize> = output.open_controls.iter().map(|control| control.at).collect();
    assert!(
        starts
            .iter()
            .all(|at| *at <= output.text.whole().len() && output.text.whole().is_char_boundary(*at)),
        "{context}: the start of an open control is not a place in the text: {starts:?} in {:?}",
        output.text.whole()
    );
    assert!(
        starts.is_sorted(),
        "{context}: the starts of the open controls do not rise: {starts:?}"
    );
}

/// Fails when a control end, the start of an open control or an open checkpoint is not a
/// place in the text, or when one of the three lists does not rise.
fn assert_places_are_true(output: &PlainOutput, context: &str) {
    assert_control_starts_are_true(output, context);
    let len = output.text.whole().len();
    assert!(
        output.control_ends.as_slice().iter().all(|end| *end <= len),
        "{context}: a control end is past the text: {:?} in {:?}",
        output.control_ends.as_slice(),
        output.text.whole()
    );
    assert!(
        output.control_ends.as_slice().is_sorted(),
        "{context}: the control ends do not rise: {:?}",
        output.control_ends.as_slice()
    );
    let places: Vec<usize> = output.open_checkpoints.iter().map(|open| open.at).collect();
    assert!(
        places
            .iter()
            .all(|at| *at <= len && output.text.whole().is_char_boundary(*at)),
        "{context}: an open checkpoint is not a place in the text: {places:?} in {:?}",
        output.text.whole()
    );
    assert!(
        places.is_sorted(),
        "{context}: the open checkpoints do not rise: {places:?}"
    );
}

/// Runs `steps` on a new output, checks the places after each step and returns the text.
fn run(steps: &[Step]) -> String {
    let mut output = PlainOutput::default();
    let mut open: Vec<Checkpoint> = Vec::new();
    let mut controls: Vec<OpenControl> = Vec::new();
    for (index, step) in steps.iter().enumerate() {
        match *step {
            Step::Text(text) => output.push_text(text),
            Step::Control(text) => {
                let control = output.start_control();
                output.push_text(text);
                output.finish_control(control);
            }
            Step::Start => controls.push(output.start_control()),
            Step::Finish => output.finish_control(controls.pop().expect("the table starts before it finishes")),
            Step::Options(options) => output.write_option_list(options, false),
            Step::EndBlock => output.end_block(),
            Step::Open => open.push(output.open()),
            Step::Rollback => output.rollback(open.pop().expect("the table opens before it closes")),
            Step::Commit => output.commit(open.pop().expect("the table opens before it closes")),
        }
        assert_places_are_true(&output, &format!("step {index}"));
    }
    output.into_text()
}

#[test]
fn a_block_end_below_one_checkpoint_keeps_the_places_true() {
    use Step::{Commit, EndBlock, Open, Rollback, Text};
    let table: [(&[Step], &str); 4] = [
        // ~keep After a return the spaces are at the end again, and the next block end removes them.
        (&[Text("aa  "), Open, EndBlock, Text("b"), Rollback, EndBlock], "aa\n\n"),
        // ~keep A block end hides spaces before a checkpoint; the return makes them text again.
        (
            &[Text("aaa   "), Open, EndBlock, Text("bcd"), EndBlock, Rollback],
            "aaa   ",
        ),
        // ~keep The same with a commit: the block end stands.
        (
            &[Text("aaa   "), Open, EndBlock, Text("bcd"), EndBlock, Commit],
            "aaa\n\nbcd\n\n",
        ),
        // ~keep A checkpoint in an empty text.
        (&[Open, EndBlock, Text("b"), EndBlock, Rollback, Text("c")], "c"),
    ];
    for (steps, expected) in table {
        assert_eq!(run(steps), expected);
    }
}

#[test]
fn a_block_end_below_two_checkpoints_keeps_the_places_true() {
    use Step::{Commit, EndBlock, Open, Rollback, Text};
    let table: [(&[Step], &str); 3] = [
        // ~keep Two checkpoints, a block end below both, the inner one kept, the outer one not.
        (
            &[
                Text("aaa "),
                Open,
                Open,
                EndBlock,
                Text("b"),
                Commit,
                Text("c"),
                Rollback,
            ],
            "aaa ",
        ),
        // ~keep Two checkpoints, a block end below both, both returned to.
        (
            &[
                Text("aaa "),
                Open,
                Text("b  "),
                Open,
                EndBlock,
                Text("c"),
                Rollback,
                Rollback,
            ],
            "aaa ",
        ),
        // ~keep The inner return makes the spaces text again; a second block end removes them again.
        (
            &[
                Text("aa  "),
                Open,
                Open,
                EndBlock,
                Text("b"),
                Rollback,
                EndBlock,
                Text("c"),
                Rollback,
            ],
            "aa  ",
        ),
    ];
    for (steps, expected) in table {
        assert_eq!(run(steps), expected);
    }
}

#[test]
fn a_control_beside_a_checkpoint_keeps_the_places_true() {
    use Step::{Commit, Control, EndBlock, Open, Options, Rollback, Text};
    let table: [(&[Step], &str); 3] = [
        // ~keep A control before the checkpoint is the last control again after the return.
        (
            &[
                Text("aaa"),
                Control("X"),
                Open,
                Control("Y"),
                Options("one two"),
                Rollback,
                Text("bbb"),
            ],
            "aaa X bbb",
        ),
        // ~keep A control that ends with spaces, a block end in a checkpoint, a return.
        (
            &[
                Text("aaa"),
                Control("X   "),
                Open,
                EndBlock,
                Text("\u{e9}b"),
                EndBlock,
                Rollback,
                Text("ccc"),
            ],
            "aaa X   ccc",
        ),
        // ~keep A control that holds a checkpoint: the space before the control moves no place wrongly.
        (
            &[Text("aaa"), Open, Control("W"), Control("Y"), Commit, Text("bbb")],
            "aaa W Y bbb",
        ),
    ];
    for (steps, expected) in table {
        assert_eq!(run(steps), expected);
    }
}

#[test]
fn a_block_end_below_the_start_of_an_open_control_keeps_the_places_true() {
    use Step::{EndBlock, Finish, Open, Rollback, Start, Text};
    let table: [(&[Step], &str); 5] = [
        // ~keep A block end in a control removes the spaces before its start: the control
        // ~keep still ends at the end of its text, and the next word gets its space.
        (
            &[Text("b   "), Start, EndBlock, Text("e"), Finish, Text("ccc")],
            "b\n\ne ccc",
        ),
        // ~keep The same with a character of two bytes: the old start was inside it.
        (
            &[Text("b   "), Start, EndBlock, Text("\u{e9}"), Finish, Text("ccc")],
            "b\n\n\u{e9} ccc",
        ),
        // ~keep A control that holds a block end and no text.
        (&[Text("b   "), Start, EndBlock, Finish, Text("ccc")], "b\n\nccc"),
        // ~keep Two open controls: the block end moves the inner start, and the space of
        // ~keep the outer control is written at its own start.
        (
            &[
                Text("a"),
                Start,
                Text("x  "),
                Start,
                EndBlock,
                Text("e"),
                Finish,
                Finish,
                Text("ccc"),
            ],
            "a x\n\ne ccc",
        ),
        // ~keep A return to a checkpoint in the control makes the spaces text again.
        (
            &[
                Text("b   "),
                Start,
                Open,
                EndBlock,
                Text("e"),
                Rollback,
                Finish,
                Text("ccc"),
            ],
            "b   ccc",
        ),
    ];
    for (steps, expected) in table {
        assert_eq!(run(steps), expected);
    }
}

#[test]
fn text_written_before_the_start_of_an_open_control_moves_the_start() {
    // ~keep No path of the writer writes text before an open control. `insert_at` keeps
    // ~keep the start true all the same: the control starts at 3, then at 5.
    let mut output = PlainOutput::default();
    output.push_text("aaa");
    let control = output.start_control();
    output.push_text("W");
    output.insert_at(1, "  ");
    assert_places_are_true(&output, "after the insert");
    output.finish_control(control);
    assert_eq!(output.text.whole(), "a  aa W");
    assert_eq!(output.control_ends.as_slice(), [7]);
    assert_eq!(output.into_text(), "a  aa W");
}

#[test]
fn an_outer_checkpoint_has_its_place_again_after_an_inner_return() {
    let mut output = PlainOutput::default();
    output.push_text("aa  ");
    let outer = output.open();
    let inner = output.open();
    output.end_block();
    output.push_text("b");
    assert_eq!(output.since(&outer), "\n\nb");
    output.rollback(inner);
    assert_eq!(output.text.whole(), "aa  ");
    assert_eq!(output.since(&outer), "");
    output.push_text("c");
    assert_eq!(output.since(&outer), "c");
    output.rollback(outer);
    assert_eq!(output.into_text(), "aa  ");
}

#[test]
fn an_outer_checkpoint_keeps_the_blanks_it_wrote_after_an_inner_return() {
    // ~keep The outer element stands after two blanks, ends a block and writes two blanks
    // ~keep of its own. A removed child with a block end leaves those in its text.
    let mut output = PlainOutput::default();
    output.push_text("a");
    output.end_block();
    output.push_text("  ");
    let outer = output.open();
    output.end_block();
    output.push_text("  ");
    let inner = output.open();
    output.end_block();
    assert_eq!(output.since(&outer), "");
    output.rollback(inner);
    assert_eq!(output.since(&outer), "  ");
    output.push_text("X");
    assert_eq!(output.since(&outer), "  X");
    output.rollback(outer);
    assert_eq!(output.into_text(), "a\n\n  ");
}

#[test]
fn a_space_written_before_a_control_moves_the_places_after_it() {
    // ~keep The outer control starts at 3 and holds a control that ends at 5 and a
    // ~keep checkpoint at 5. The space of the outer control is written at 3.
    let mut output = PlainOutput::default();
    output.push_text("aaa");
    let outer = output.start_control();
    output.push_text("W");
    let inner = output.start_control();
    output.push_text("Y");
    output.finish_control(inner);
    assert_eq!(output.text.whole(), "aaaW Y");
    assert_eq!(output.control_ends.as_slice(), [6]);
    let checkpoint = output.open();
    output.push_text("zz");
    output.finish_control(outer);
    assert_eq!(output.text.whole(), "aaa W Y zz");
    assert_eq!(output.control_ends.as_slice(), [7, 10]);
    assert_places_are_true(&output, "after the space");
    assert_eq!(output.since(&checkpoint), " zz");
    output.rollback(checkpoint);
    assert_eq!(output.text.whole(), "aaa W Y");
    assert_eq!(output.control_ends.as_slice(), [7]);
    assert_eq!(output.into_text(), "aaa W Y");
}

/// The count of control ends that the output examines for `count` controls, each after a
/// word and each with a space written before it. With `block_ends`, a block ends after
/// each control.
fn ends_examined_for(count: usize, block_ends: bool) -> usize {
    let before = ControlEnds::touched();
    let mut output = PlainOutput::default();
    for _ in 0..count {
        output.push_text("z");
        let control = output.start_control();
        output.push_text("X");
        output.finish_control(control);
        if block_ends {
            output.end_block();
        }
    }
    assert_places_are_true(&output, "after the last control");
    assert_eq!(output.control_ends.as_slice().len(), count);
    let examined = ControlEnds::touched() - before;
    let line = if block_ends { "z X\n\n" } else { "z X " };
    assert_eq!(output.into_text(), line.repeat(count).trim_end_matches(' '));
    examined
}

#[test]
fn controls_one_after_the_other_examine_a_bounded_count_of_control_ends() {
    // ~keep No control end stands after the place of a space, so the binary search reads
    // ~keep ends: at most `ilog2(count) + 2` for each search, 11 and 13 here. A block end
    // ~keep makes a second search. Each control also reads the last end for its two texts,
    // ~keep writes its own end and can cut the list one time: 4 more. A scan of every end
    // ~keep reads `count * (count - 1) / 2` ends for the spaces alone: 499,500 and 7,998,000.
    for (block_ends, searches) in [(false, 1_usize), (true, 2)] {
        for (count, reads) in [(1_000_usize, 11_usize), (4_000, 13)] {
            let examined = ends_examined_for(count, block_ends);
            let bound = count * (reads * searches + 4);
            assert!(
                examined <= bound,
                "{count} controls (block ends: {block_ends}) examined {examined} control ends, over {bound}"
            );
        }
    }
}

#[test]
fn removed_elements_after_a_run_of_spaces_cost_a_bounded_count_of_bytes() {
    // ~keep Each removed element holds a block end, which removes the run before it, and
    // ~keep the return makes the run text again. Each costs two line ends and three reads.
    // ~keep A read of the run or a copy of it for each element costs `count * count`.
    for count in [1_000_usize, 4_000] {
        let mut output = PlainOutput::default();
        output.push_text("b");
        output.push_text(&" ".repeat(count));
        let written = OutputText::work();
        for _ in 0..count {
            let element = output.open();
            output.end_block();
            assert_eq!(output.since(&element), "\n\n");
            output.rollback(element);
        }
        let work = OutputText::work() - written;
        assert!(
            work <= 8 * count,
            "{count} removed elements after {count} spaces cost {work} bytes, over 8 for each"
        );
        assert_eq!(output.len(), count + 1);
        assert_eq!(output.into_text().trim_end_matches(' '), "b");
    }
}

#[test]
fn a_loop_that_takes_the_text_out_of_the_output_is_counted() {
    // ~keep `take` leaves a new text in the output. A loop that takes the text for each
    // ~keep element, reads all of it and writes it back costs `count * count`, and the
    // ~keep counter must hold all of it: the bound of 8 for each element in the test above
    // ~keep fails for this loop. A counter in the text held the last write alone.
    for count in [1_000_usize, 4_000] {
        let mut output = PlainOutput::default();
        output.push_text("b");
        output.push_text(&" ".repeat(count));
        let written = OutputText::work();
        for _ in 0..count {
            let taken = std::mem::take(&mut output.text).into_string();
            output.text.push_str(&taken);
        }
        let work = OutputText::work() - written;
        assert!(
            work >= count * count,
            "{count} rounds of a text of {count} bytes taken out and written back counted {work} bytes"
        );
        assert!(work > 8 * count, "the loop is under the bound of a block end: {work}");
        assert_eq!(output.len(), count + 1);
    }
}

#[test]
fn control_ends_taken_out_of_the_output_are_counted() {
    // ~keep The same for the control ends: the count of a search is not lost with the value.
    let mut output = PlainOutput::default();
    for _ in 0..8 {
        let control = output.start_control();
        output.push_text("X");
        output.finish_control(control);
    }
    let before = ControlEnds::touched();
    assert_eq!(output.control_ends.first_after(0), 0);
    let one_search = ControlEnds::touched() - before;
    assert!(one_search > 0, "a search reads no end");
    let taken = std::mem::take(&mut output.control_ends);
    assert_eq!(taken.first_after(0), 0);
    // ~keep The count is read while the ends are outside the output: the output then holds
    // ~keep a new list, and a counter in that list holds nothing of the two searches.
    assert_eq!(
        ControlEnds::touched(),
        before + 2 * one_search,
        "a search of ends taken out of the output is not counted"
    );
    output.control_ends = taken;
    assert_eq!(output.control_ends.as_slice().len(), 8);
}

#[test]
fn a_loop_that_moves_every_control_end_one_by_one_is_counted() {
    // ~keep A loop that takes every end from the back with `last` and `truncate` and writes
    // ~keep each back with `push`, one time for each insert, costs `count * count`. The
    // ~keep counter must hold all of it: the bound of the test of controls one after the
    // ~keep other fails for this loop.
    for (count, reads) in [(1_000_usize, 11_usize), (4_000, 13)] {
        let mut output = PlainOutput::default();
        for _ in 0..count {
            let control = output.start_control();
            output.push_text("X");
            output.finish_control(control);
        }
        assert_eq!(output.control_ends.len(), count);
        let before = ControlEnds::touched();
        for _ in 0..count {
            let mut taken = Vec::with_capacity(count);
            while let Some(end) = output.control_ends.last() {
                taken.push(end);
                output.control_ends.truncate(output.control_ends.len() - 1);
            }
            while let Some(end) = taken.pop() {
                output.control_ends.push(end);
            }
        }
        let examined = ControlEnds::touched() - before;
        assert!(
            examined >= count * count,
            "{count} rounds over {count} control ends counted {examined} ends"
        );
        assert!(
            examined > count * (reads * 2 + 4),
            "the loop is under the bound of controls one after the other: {examined}"
        );
        assert_eq!(output.control_ends.len(), count);
    }
}

#[test]
fn every_function_that_reads_or_moves_a_byte_or_an_end_is_counted() {
    for (name, call) in OutputText::COUNTED {
        let mut text = OutputText::default();
        text.push_str("abc");
        let before = OutputText::work();
        call(&mut text);
        assert!(
            OutputText::work() > before,
            "`OutputText::{name}` adds nothing to the count"
        );
    }
    for (name, call) in ControlEnds::COUNTED {
        let mut ends = ControlEnds::default();
        ends.push(3);
        ends.push(5);
        let before = ControlEnds::touched();
        call(&mut ends);
        assert!(
            ControlEnds::touched() > before,
            "`ControlEnds::{name}` adds nothing to the count"
        );
    }
}

#[test]
fn block_ends_after_line_ends_read_a_bounded_count_of_characters() {
    // ~keep A block end reads two line ends at most. A count of all of them for each block
    // ~keep end costs `count * count`.
    for count in [1_000_usize, 4_000] {
        let mut output = PlainOutput::default();
        output.push_text("b");
        for _ in 0..count {
            output.push_mark("\n");
        }
        let written = OutputText::work();
        for _ in 0..count {
            output.end_block();
        }
        let work = OutputText::work() - written;
        assert!(
            work <= 4 * count,
            "{count} block ends after {count} line ends read {work} characters, over 4 for each"
        );
        assert_eq!(output.len(), count + 1);
    }
}

#[test]
fn a_commit_removes_the_hidden_spaces_and_moves_the_places_after_them() {
    let mut output = PlainOutput::default();
    output.push_text("a  ");
    let element = output.open();
    output.end_block();
    assert_eq!(output.len(), 3);
    assert!(output.ends_with_line_end());
    let control = output.start_control();
    output.push_text("X");
    output.finish_control(control);
    assert_eq!(output.since(&element), "\n\nX");
    assert_eq!(output.len(), 4);
    output.commit(element);
    assert_eq!(output.control_ends.as_slice(), [4]);
    assert_places_are_true(&output, "after the commit");
    output.push_text("b");
    assert_eq!(output.into_text(), "a\n\nX b");
}

#[test]
fn a_space_written_before_a_control_moves_the_hidden_spaces_after_it() {
    // ~keep No path of the writer finishes a control while a checkpoint in it is open.
    // ~keep `insert_at` keeps the hole true all the same: it is at 4, then at 5.
    let mut output = PlainOutput::default();
    output.push_text("aaa");
    let control = output.start_control();
    output.push_text("W  ");
    let element = output.open();
    output.end_block();
    output.push_text("zz");
    output.finish_control(control);
    assert_eq!(output.text.whole(), "aaa W  \n\nzz");
    assert_eq!(output.len(), 9);
    assert_eq!(output.since(&element), "\n\nzz");
    output.commit(element);
    assert_eq!(output.control_ends.as_slice(), [9]);
    assert_eq!(output.into_text(), "aaa W\n\nzz");
}

#[test]
fn a_commit_moves_the_start_of_an_open_control_after_the_hidden_spaces() {
    // ~keep No path of the writer commits a checkpoint while a control in it is open. `cut`
    // ~keep keeps the start true all the same: the control starts at 5, then at 3.
    let mut output = PlainOutput::default();
    output.push_text("a  ");
    let element = output.open();
    output.end_block();
    let control = output.start_control();
    output.push_text("X");
    output.commit(element);
    assert_places_are_true(&output, "after the commit");
    output.finish_control(control);
    assert_eq!(output.control_ends.as_slice(), [4]);
    assert_eq!(output.into_text(), "a\n\nX");
}

#[test]
fn the_text_since_a_checkpoint_in_hidden_spaces_starts_after_them() {
    let mut output = PlainOutput::default();
    output.push_text("a ");
    let element = output.open();
    output.push_text(" ");
    output.end_block();
    assert_eq!(output.since(&element), "\n\n");
    output.rollback(element);
    assert_eq!(output.into_text(), "a ");
}