mbook 0.3.7

Read, edit and create mbook files: Markdown chapters and AVIF pictures in one indexed container
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Files that follow or break the rules of RFC 0001, built by hand so that
//! they do not depend on the writer of this crate.

use crate::raw::{ANCHORS, Column, META, RESOURCES, Raw, TOC};
use crate::texts::{CH01, CH02, DIAGRAM, FORMULA, figure_offset, station_offset};
use mbook::{
    Book, BookReader, Destination, Error, ResolveError, ResourceKind, Result, Size, Toc, Version,
};
use std::io::Cursor;

type Reader = BookReader<Cursor<Vec<u8>>>;

fn bytes(raw: &Raw) -> Result<Vec<u8>> {
    raw.build().map_err(Error::Container)
}

fn open(raw: &Raw) -> Result<Reader> {
    BookReader::new(Cursor::new(bytes(raw)?))
}

/// The example with one change.
fn changed(change: impl FnOnce(&mut Raw)) -> Raw {
    Raw::example().with(change)
}

/// The number of the table a changed example is rejected for.
fn rejected_table(change: impl FnOnce(&mut Raw)) -> Result<u32> {
    match open(&changed(change)) {
        Err(Error::Malformed { resource, .. }) => Ok(resource),
        Ok(_) => panic!("the file must be rejected"),
        Err(other) => Err(other),
    }
}

#[test]
fn a_file_built_by_hand_reads_like_one_written_by_this_crate() -> Result<()> {
    let mut reader = open(&Raw::example())?;
    let ids: Vec<_> = reader.chapters().map(|chapter| chapter.id).collect();
    let mut texts = Vec::new();
    for id in ids {
        texts.push(reader.read_chapter(id)?);
    }
    assert_eq!(texts, [CH01, CH02]);
    assert_eq!(reader.toc().len(), 3);
    Ok(())
}

#[test]
fn a_newer_minor_version_is_accepted() -> Result<()> {
    let reader = open(&changed(|raw| raw.header[7] = 9))?;
    assert_eq!(reader.version(), Version { major: 1, minor: 9 });
    Ok(())
}

#[test]
fn a_newer_major_version_is_refused_by_name() -> Result<()> {
    let raw = changed(|raw| raw.header[6] = 2);
    let refused = Version { major: 2, minor: 0 };
    assert!(matches!(open(&raw), Err(Error::UnsupportedVersion(version)) if version == refused));
    assert!(matches!(
        Book::read(bytes(&raw)?.as_slice()),
        Err(Error::UnsupportedVersion(version)) if version == refused
    ));
    Ok(())
}

#[test]
fn major_version_zero_is_malformed() -> Result<()> {
    assert_eq!(rejected_table(|raw| raw.header[6] = 0)?, 0);
    Ok(())
}

#[test]
fn a_container_without_the_format_header_is_not_an_mbook() {
    let wrong_prefix = changed(|raw| raw.header[0] = b'X');
    let short = changed(|raw| raw.header.truncate(7));
    let long = changed(|raw| raw.header.push(0));
    for raw in [wrong_prefix, short, long] {
        assert!(matches!(open(&raw), Err(Error::NotMbook)));
    }
}

#[test]
fn a_file_with_fewer_than_five_resources_is_malformed() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables.truncate(2);
        raw.contents.clear();
    })?;
    assert_eq!(table, 0);
    Ok(())
}

#[test]
fn a_table_with_a_missing_column_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables[TOC].pop();
    })?;
    assert_eq!(table, 3);
    Ok(())
}

#[test]
fn a_column_of_another_type_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables[ANCHORS][2] = Column::Words(vec![1, 2, 3]);
    })?;
    assert_eq!(table, 4);
    Ok(())
}

#[test]
fn a_numeric_column_of_another_width_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables[RESOURCES][0] = Column::Words(vec![0, 0, 0, 0, 0, 2, 1, 1, 2]);
    })?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn columns_of_different_lengths_are_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables[META][1].text_mut().pop();
    })?;
    assert_eq!(table, 1);
    Ok(())
}

#[test]
fn a_column_added_by_a_later_minor_version_is_ignored() -> Result<()> {
    let reader = open(&changed(|raw| {
        raw.tables[TOC].push(Column::text(&["a", "b", "c"]));
        raw.tables[META].push(Column::Bytes(vec![0; 5]));
    }))?;
    assert_eq!(
        (reader.toc().len(), reader.meta().title()),
        (3, "The Example")
    );
    Ok(())
}

#[test]
fn a_meta_key_this_version_does_not_define_is_kept() -> Result<()> {
    let reader = open(&changed(|raw| {
        raw.tables[META][0].text_mut().push("narrator".to_owned());
        raw.tables[META][1].text_mut().push("N. Reader".to_owned());
    }))?;
    assert_eq!(reader.meta().get("narrator"), Some("N. Reader"));
    Ok(())
}

#[test]
fn a_resource_of_an_unknown_kind_is_listed_and_skipped() -> Result<()> {
    let raw = changed(|raw| raw.push_resource(9, "data/index.bin", b"\x01\x02\x03"));
    let mut reader = open(&raw)?;
    let last = reader.resources().last().map(|r| (r.kind, r.path));
    assert_eq!(last, Some((ResourceKind::Unknown(9), "data/index.bin")));
    assert_eq!((reader.chapters().len(), reader.pictures().len()), (2, 2));
    let Some(from) = reader.chapter_id(6) else {
        panic!("resource 6 is the first chapter");
    };
    assert_eq!(
        reader.resolve(from, "data/index.bin"),
        Err(ResolveError::NotFound)
    );
    // A loaded book leaves the resource behind.
    let book = reader.load()?;
    assert_eq!((book.chapters().len(), book.pictures().len()), (2, 2));
    Ok(())
}

#[test]
fn a_resource_table_shorter_than_the_container_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| raw.contents.push(b"extra".to_vec().into()))?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn a_path_that_leaves_the_book_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.tables[RESOURCES][1].text_mut()[6] = "../ch01.md".to_owned();
    })?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn a_contents_row_inside_a_chapter_without_an_anchor_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        let anchors = &mut raw.tables[ANCHORS];
        anchors[0].words_mut().remove(1);
        anchors[1].words_mut().remove(1);
        anchors[2].text_mut().remove(1);
    })?;
    assert_eq!(table, 3);
    Ok(())
}

#[test]
fn a_picture_without_a_size_is_still_listed() -> Result<()> {
    // The size is a rule of picture resources, not of the table, so the file
    // opens and the reader reports what the table says.
    let reader = open(&changed(|raw| {
        raw.tables[RESOURCES][2].words_mut()[5] = 0;
        raw.tables[RESOURCES][3].words_mut()[5] = 0;
    }))?;
    let size = reader.cover().map(|cover| cover.size);
    assert_eq!(
        size,
        Some(Size {
            width: 0,
            height: 0
        })
    );
    Ok(())
}

#[test]
fn a_position_inside_a_line_fails_when_its_chapter_is_read() -> Result<()> {
    let inside = station_offset() + 1;
    let raw = changed(|raw| {
        raw.tables[TOC][3].words_mut()[1] = inside;
        raw.tables[ANCHORS][1].words_mut()[1] = inside;
    });
    // The tables cannot tell: the file opens, and the other chapter reads.
    let mut reader = open(&raw)?;
    let (Some(first), Some(second)) = (reader.chapter_id(6), reader.chapter_id(7)) else {
        panic!("the example has two chapters");
    };
    assert!(matches!(
        reader.read_chapter(first),
        Err(Error::Malformed { resource: 6, .. })
    ));
    assert_eq!(reader.read_chapter(second)?, CH02);
    assert!(matches!(
        Book::read(bytes(&raw)?.as_slice()),
        Err(Error::Malformed { resource: 6, .. })
    ));
    Ok(())
}

#[test]
fn a_chapter_that_is_not_utf8_fails_alone() -> Result<()> {
    let raw = changed(|raw| raw.contents[1] = vec![0xff; CH01.len()].into());
    let mut reader = open(&raw)?;
    let (Some(first), Some(second)) = (reader.chapter_id(6), reader.chapter_id(7)) else {
        panic!("the example has two chapters");
    };
    assert!(matches!(
        reader.read_chapter(first),
        Err(Error::Malformed {
            resource: 6,
            reason: "the text is not UTF-8"
        })
    ));
    assert_eq!(reader.read_chapter(second)?, CH02);
    Ok(())
}

#[test]
fn a_book_without_contents_or_anchors_is_valid() -> Result<()> {
    let raw = changed(|raw| {
        for table in [TOC, ANCHORS] {
            for column in &mut raw.tables[table] {
                *column = match column {
                    Column::Bytes(_) => Column::Bytes(Vec::new()),
                    Column::Words(_) => Column::Words(Vec::new()),
                    Column::Text(_) => Column::Text(Vec::new()),
                };
            }
        }
    });
    let book = Book::read(bytes(&raw)?.as_slice())?;
    assert_eq!(book.toc(), &Toc::Explicit(Vec::new()));
    assert!(
        book.chapters()
            .iter()
            .all(|chapter| chapter.anchors().is_empty())
    );
    Ok(())
}

#[test]
fn a_compressed_picture_is_read_like_a_stored_one() -> Result<()> {
    // The hand-built file compresses every resource, pictures included.
    let mut reader = open(&Raw::example())?;
    assert_eq!(reader.read_cover()?.as_deref(), Some(crate::texts::PLAIN));
    Ok(())
}

/// The example with an anchor table in front of the first chapter. The table
/// is resource 6; the chapters move to 7 and 8.
fn with_anchor_table(offsets: &[u32], names: &[&str]) -> Raw {
    changed(|raw| raw.insert_anchor_table(6, offsets, names))
}

/// The rule the anchor table of the first chapter is refused for, and
/// whether the rest of the file can still be read.
fn refused_anchor_table(raw: &Raw) -> Result<&'static str> {
    let mut reader = open(raw)?;
    let (Some(first), Some(second)) = (reader.chapter_id(7), reader.chapter_id(8)) else {
        panic!("the chapters are resources 7 and 8");
    };
    let reason = match reader.read_extra_anchors(first) {
        Err(Error::Malformed {
            resource: 6,
            reason,
        }) => reason,
        Ok(_) => panic!("the anchor table must be refused"),
        Err(other) => return Err(other),
    };
    // The error is confined to the table: both chapters still decode.
    assert_eq!(reader.read_chapter(first)?, CH01);
    assert_eq!(reader.read_chapter(second)?, CH02);
    Ok(reason)
}

#[test]
fn an_anchor_table_built_by_hand_is_read() -> Result<()> {
    let raw = with_anchor_table(&[figure_offset()], &["fig-1"]);
    let mut reader = open(&raw)?;
    let (Some(first), Some(second)) = (reader.chapter_id(7), reader.chapter_id(8)) else {
        panic!("the chapters are resources 7 and 8");
    };
    let anchors = reader.read_extra_anchors(first)?;
    let names: Vec<_> = anchors
        .iter()
        .map(|a| (a.name.as_str(), a.offset))
        .collect();
    assert_eq!(names, [("fig-1", figure_offset())]);
    assert!(matches!(
        reader.read_resolve(second, "ch01.md#fig-1")?,
        Destination::Chapter(position) if position.offset == figure_offset()
    ));
    Ok(())
}

#[test]
fn a_book_with_an_anchor_table_built_by_hand_is_loaded() -> Result<()> {
    let raw = with_anchor_table(&[0, figure_offset()], &["top", "fig-1"]);
    let book = Book::read(bytes(&raw)?.as_slice())?;
    let extra: Vec<_> = book
        .chapters()
        .iter()
        .map(|chapter| chapter.extra_anchors().len())
        .collect();
    assert_eq!(extra, [2, 0]);
    Ok(())
}

#[test]
fn an_anchor_table_that_no_chapter_follows_is_rejected() -> Result<()> {
    let before_a_picture = rejected_table(|raw| raw.insert_anchor_table(5, &[0], &["cover"]))?;
    let at_the_end = rejected_table(|raw| raw.push_resource(3, "", b""))?;
    assert_eq!((before_a_picture, at_the_end), (2, 2));
    Ok(())
}

#[test]
fn an_anchor_table_with_a_path_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.insert_anchor_table(6, &[0], &["top"]);
        raw.tables[RESOURCES][1].text_mut()[6] = "ch01.anchors".to_owned();
    })?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn an_anchor_table_of_another_shape_fails_alone() -> Result<()> {
    let one_column = with_anchor_table(&[0], &["top"]).with(|raw| {
        raw.table_mut(6).pop();
    });
    let swapped = with_anchor_table(&[0], &["top"]).with(|raw| raw.table_mut(6).reverse());
    let not_a_table = with_anchor_table(&[0], &["top"]).with(|raw| {
        raw.contents[1] = b"top".to_vec().into();
    });
    assert_eq!(refused_anchor_table(&one_column)?, "a column is missing");
    assert_eq!(
        refused_anchor_table(&swapped)?,
        "a numeric column has another type or width"
    );
    assert_eq!(refused_anchor_table(&not_a_table)?, "a column is missing");
    Ok(())
}

#[test]
fn an_anchor_table_that_breaks_a_rule_fails_alone() -> Result<()> {
    let past_the_end = u32::try_from(CH01.len()).unwrap_or(u32::MAX);
    let cases = [
        (with_anchor_table(&[0], &[""]), "a name is empty"),
        (
            with_anchor_table(&[past_the_end], &["end"]),
            "an offset is past the end of its chapter",
        ),
        (
            with_anchor_table(&[figure_offset(), 0], &["fig-1", "top"]),
            "the rows are not sorted",
        ),
        (
            with_anchor_table(&[0, figure_offset()], &["a", "a"]),
            "a name repeats in a chapter",
        ),
        (
            with_anchor_table(&[figure_offset()], &["the-station"]),
            "a name repeats in a chapter",
        ),
    ];
    for (raw, reason) in cases {
        assert_eq!(refused_anchor_table(&raw)?, reason);
    }
    Ok(())
}

#[test]
fn a_book_with_a_refused_anchor_table_does_not_load() -> Result<()> {
    let raw = with_anchor_table(&[0], &[""]);
    assert!(matches!(
        Book::read(bytes(&raw)?.as_slice()),
        Err(Error::Malformed { resource: 6, .. })
    ));
    assert!(matches!(
        open(&raw)?.load(),
        Err(Error::Malformed { resource: 6, .. })
    ));
    Ok(())
}

#[test]
fn an_extra_anchor_inside_a_line_is_found_when_the_book_is_loaded() -> Result<()> {
    let raw = with_anchor_table(&[figure_offset() + 2], &["inside"]);
    // The table alone cannot show it.
    let mut reader = open(&raw)?;
    let Some(first) = reader.chapter_id(7) else {
        panic!("resource 7 is the first chapter");
    };
    assert_eq!(reader.read_extra_anchors(first)?.len(), 1);
    assert!(matches!(
        reader.load(),
        Err(Error::Malformed {
            resource: 6,
            reason: "a position is not at the start of a line"
        })
    ));
    Ok(())
}

#[test]
fn a_name_missing_from_an_anchor_table_is_an_unknown_anchor() -> Result<()> {
    let mut reader = open(&with_anchor_table(&[0], &["top"]))?;
    let Some(second) = reader.chapter_id(8) else {
        panic!("resource 8 is the second chapter");
    };
    assert!(matches!(
        reader.read_resolve(second, "ch01.md#bottom"),
        Err(Error::Unresolved(ResolveError::UnknownAnchor))
    ));
    Ok(())
}

#[test]
fn a_refused_anchor_table_fails_the_link_that_needs_it() -> Result<()> {
    let mut reader = open(&with_anchor_table(&[0], &[""]))?;
    let Some(second) = reader.chapter_id(8) else {
        panic!("resource 8 is the second chapter");
    };
    assert!(matches!(
        reader.read_resolve(second, "ch01.md#top"),
        Err(Error::Malformed { resource: 6, .. })
    ));
    // A link to a heading of the same chapter does not need the table.
    assert!(reader.read_resolve(second, "ch01.md#the-station").is_ok());
    Ok(())
}

/// The example with a landmarks table. The table is resource 5; the cover
/// moves to 6 and the chapters to 7 and 8.
fn with_landmarks(landmarks: &[(&str, &str, u32, u32)]) -> Raw {
    changed(|raw| raw.insert_landmarks(landmarks))
}

/// The rule the landmarks of a file are refused for, and that the rest of
/// the file can still be read.
fn refused_landmarks(raw: &Raw) -> Result<&'static str> {
    let mut reader = open(raw)?;
    let reason = match reader.read_landmarks() {
        Err(Error::Malformed {
            resource: 5,
            reason,
        }) => reason,
        Ok(_) => panic!("the landmarks must be refused"),
        Err(other) => return Err(other),
    };
    // The error is confined to the landmarks: the book is still read.
    let Some(first) = reader.chapter_id(7) else {
        panic!("resource 7 is the first chapter");
    };
    assert_eq!(reader.read_chapter(first)?, CH01);
    assert_eq!(reader.toc().len(), 3);
    Ok(reason)
}

#[test]
fn landmarks_built_by_hand_are_read() -> Result<()> {
    let raw = with_landmarks(&[
        ("start", "", 7, 0),
        ("preface", "Inside", 7, station_offset()),
        ("x-letter", "The letter", 8, 0),
    ]);
    let mut reader = open(&raw)?;
    let landmarks: Vec<_> = reader
        .read_landmarks()?
        .into_iter()
        .map(|l| {
            (
                l.kind,
                l.title,
                l.position.chapter.number(),
                l.position.offset,
            )
        })
        .collect();
    assert_eq!(
        landmarks,
        [
            ("start".to_owned(), String::new(), 7, 0),
            (
                "preface".to_owned(),
                "Inside".to_owned(),
                7,
                station_offset()
            ),
            ("x-letter".to_owned(), "The letter".to_owned(), 8, 0),
        ]
    );
    let book = Book::read(bytes(&raw)?.as_slice())?;
    let named: Vec<_> = book
        .landmarks()
        .iter()
        .map(|l| (l.kind.as_str(), l.chapter.as_str(), l.anchor.as_deref()))
        .collect();
    assert_eq!(
        named,
        [
            ("start", "ch01.md", None),
            ("preface", "ch01.md", Some("the-station")),
            ("x-letter", "ch02.md", None),
        ]
    );
    Ok(())
}

#[test]
fn a_second_landmarks_table_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.insert_landmarks(&[("start", "", 7, 0)]);
        raw.push_resource(4, "", b"");
    })?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn a_landmarks_table_with_a_path_is_rejected() -> Result<()> {
    let table = rejected_table(|raw| {
        raw.insert_landmarks(&[("start", "", 7, 0)]);
        raw.tables[RESOURCES][1].text_mut()[5] = "landmarks".to_owned();
    })?;
    assert_eq!(table, 2);
    Ok(())
}

#[test]
fn landmarks_of_another_shape_fail_alone() -> Result<()> {
    let three_columns = with_landmarks(&[("start", "", 7, 0)]).with(|raw| {
        raw.table_mut(5).pop();
    });
    let swapped = with_landmarks(&[("start", "", 7, 0)]).with(|raw| raw.table_mut(5).reverse());
    assert_eq!(refused_landmarks(&three_columns)?, "a column is missing");
    assert_eq!(
        refused_landmarks(&swapped)?,
        "a string column has another type"
    );
    Ok(())
}

#[test]
fn landmarks_that_break_a_rule_fail_alone() -> Result<()> {
    let past_the_end = u32::try_from(CH01.len()).unwrap_or(u32::MAX);
    let cases = [
        (
            with_landmarks(&[("The Index", "", 7, 0)]),
            "a kind is not valid",
        ),
        (
            with_landmarks(&[("start", "", 7, 0), ("start", "", 8, 0)]),
            "more than one start",
        ),
        (
            with_landmarks(&[("index", "", 6, 0)]),
            "a row does not name a chapter",
        ),
        (
            with_landmarks(&[("index", "", 7, past_the_end)]),
            "an offset is past the end of its chapter",
        ),
        (
            with_landmarks(&[("index", "", 7, figure_offset())]),
            "a row inside a chapter has no anchor",
        ),
    ];
    for (raw, reason) in cases {
        assert_eq!(refused_landmarks(&raw)?, reason);
    }
    Ok(())
}

#[test]
fn a_book_with_refused_landmarks_does_not_load() -> Result<()> {
    let raw = with_landmarks(&[("The Index", "", 7, 0)]);
    assert!(matches!(
        Book::read(bytes(&raw)?.as_slice()),
        Err(Error::Malformed { resource: 5, .. })
    ));
    Ok(())
}

#[test]
fn a_landmark_may_lead_to_an_extra_anchor() -> Result<()> {
    // Resource 7 becomes the anchor table of the first chapter, which moves
    // to 8.
    let raw = with_landmarks(&[("list-of-figures", "", 8, figure_offset())])
        .with(|raw| raw.insert_anchor_table(7, &[figure_offset()], &["fig-1"]));
    let book = Book::read(bytes(&raw)?.as_slice())?;
    let landmark = &book.landmarks()[0];
    assert_eq!(
        (landmark.chapter.as_str(), landmark.anchor.as_deref()),
        ("ch01.md", Some("fig-1"))
    );
    Ok(())
}

#[test]
fn a_landmark_without_any_anchor_is_found_when_the_book_is_loaded() -> Result<()> {
    // The chapter has an anchor table, so only loading can tell that no row
    // of it is at the offset of the landmark.
    let raw = with_landmarks(&[("index", "", 8, figure_offset())])
        .with(|raw| raw.insert_anchor_table(7, &[0], &["top"]));
    let mut reader = open(&raw)?;
    assert_eq!(reader.read_landmarks()?.len(), 1);
    assert!(matches!(
        reader.load(),
        Err(Error::Malformed {
            resource: 5,
            reason: "a row inside a chapter has no anchor"
        })
    ));
    Ok(())
}

/// The example with a diagram as resource 9 and a formula as resource 10.
fn illustrated() -> Raw {
    changed(|raw| {
        raw.push_resource(5, "dia/way.mmd", DIAGRAM.as_bytes());
        raw.push_resource(6, "math/speed.tex", FORMULA.as_bytes());
    })
}

#[test]
fn a_diagram_and_a_formula_built_by_hand_are_read() -> Result<()> {
    let mut reader = open(&illustrated())?;
    let kinds: Vec<_> = reader.resources().skip(9).map(|r| r.kind).collect();
    assert_eq!(kinds, [ResourceKind::Diagram, ResourceKind::Formula]);
    let (Some(diagram), Some(formula)) = (reader.diagram_id(9), reader.formula_id(10)) else {
        panic!("resources 9 and 10 are the diagram and the formula");
    };
    assert_eq!(reader.read_diagram(diagram)?, DIAGRAM);
    assert_eq!(reader.read_formula(formula)?, FORMULA);
    let Some(from) = reader.chapter_id(6) else {
        panic!("resource 6 is the first chapter");
    };
    assert_eq!(
        reader.resolve(from, "dia/way.mmd"),
        Ok(Destination::Diagram(diagram))
    );
    assert_eq!(
        reader.resolve(from, "math/speed.tex"),
        Ok(Destination::Formula(formula))
    );
    Ok(())
}

#[test]
fn a_book_with_a_diagram_and_a_formula_built_by_hand_is_loaded() -> Result<()> {
    let book = Book::read(bytes(&illustrated())?.as_slice())?;
    let diagrams: Vec<_> = book
        .diagrams()
        .iter()
        .map(|d| (d.path(), d.source()))
        .collect();
    let formulas: Vec<_> = book
        .formulas()
        .iter()
        .map(|f| (f.path(), f.source()))
        .collect();
    assert_eq!(diagrams, [("dia/way.mmd", DIAGRAM)]);
    assert_eq!(formulas, [("math/speed.tex", FORMULA)]);
    assert_eq!(open(&illustrated())?.load()?, book);
    Ok(())
}

#[test]
fn a_diagram_or_a_formula_with_a_size_is_rejected() -> Result<()> {
    for kind in [5, 6] {
        let table = rejected_table(|raw| {
            raw.push_resource(kind, "x", b"x");
            raw.tables[RESOURCES][2].words_mut()[9] = 100;
        })?;
        assert_eq!(table, 2);
    }
    Ok(())
}

#[test]
fn a_diagram_or_a_formula_without_a_path_is_rejected() -> Result<()> {
    for kind in [5, 6] {
        assert_eq!(rejected_table(|raw| raw.push_resource(kind, "", b"x"))?, 2);
    }
    Ok(())
}

#[test]
fn a_diagram_that_is_not_utf8_fails_alone() -> Result<()> {
    let raw = illustrated().with(|raw| raw.contents[4] = vec![0xff; 4].into());
    let mut reader = open(&raw)?;
    let (Some(diagram), Some(formula)) = (reader.diagram_id(9), reader.formula_id(10)) else {
        panic!("resources 9 and 10 are the diagram and the formula");
    };
    assert!(matches!(
        reader.read_diagram(diagram),
        Err(Error::Malformed {
            resource: 9,
            reason: "the text is not UTF-8"
        })
    ));
    assert_eq!(reader.read_formula(formula)?, FORMULA);
    assert!(matches!(
        reader.load(),
        Err(Error::Malformed { resource: 9, .. })
    ));
    Ok(())
}

#[test]
fn a_formula_that_is_not_one_serial_output_fails_alone() -> Result<()> {
    let raw = illustrated().with(|raw| {
        raw.contents[5] = crate::raw::Content::Table(vec![Column::text(&["x"])]);
    });
    let mut reader = open(&raw)?;
    let (Some(diagram), Some(formula)) = (reader.diagram_id(9), reader.formula_id(10)) else {
        panic!("resources 9 and 10 are the diagram and the formula");
    };
    assert!(matches!(
        reader.read_formula(formula),
        Err(Error::Malformed { resource: 10, .. })
    ));
    assert_eq!(reader.read_diagram(diagram)?, DIAGRAM);
    Ok(())
}

#[cfg(feature = "write")]
#[test]
fn a_loaded_source_that_breaks_a_rule_is_reported_when_the_book_is_checked() -> Result<()> {
    use mbook::ProblemKind;

    let raw = changed(|raw| {
        raw.push_resource(5, "dia/blank.mmd", b" \n");
        raw.push_resource(6, "math/cr.tex", b"a\r\nb");
    });
    let book = Book::read(bytes(&raw)?.as_slice())?;
    let Err(problems) = book.check() else {
        panic!("the book breaks two rules");
    };
    let found: Vec<_> = problems
        .iter()
        .map(|problem| {
            (
                problem.path.as_deref(),
                problem.offset,
                problem.kind.clone(),
            )
        })
        .collect();
    assert_eq!(
        found,
        [
            (Some("dia/blank.mmd"), None, ProblemKind::EmptySource),
            (
                Some("math/cr.tex"),
                Some(1),
                ProblemKind::ForbiddenCharacter('\r')
            ),
        ]
    );
    Ok(())
}