gedcomkit 0.1.9

A byte-preserving GEDCOM document model: decoding, parsing, readings, version conversion, plausibility checks, and the GEDZIP container, for GEDCOM 5.5 through 7.x.
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
//! Writing a document from a producer's own data.
//!
//! Everything else in this crate starts from a file. This module is for the
//! other direction: a program that holds its family data in its own shape
//! and wants to write it as GEDCOM. [`NodeSpec`] is that shape at its
//! plainest — a tag, an optional identifier and payload, and substructures —
//! which is what a language binding hands across. [`Document::append_records`]
//! adds finished records, and [`Document::wrap_long_lines`] fits a 5.5.1 file
//! to the specification's 255-character line.
//!
//! ```
//! use gedcomkit::{Document, build::NodeSpec};
//!
//! let mut person = NodeSpec::record("@I1@", "INDI");
//! person.children.push(NodeSpec::with_value("NAME", "Ada /Example/"));
//! let mut document = Document::new_v551("EXAMPLE");
//! document.append_records(vec![person.into_node(gedcomkit::Limits::DEFAULT)?])?;
//! assert!(document.to_text().contains("0 @I1@ INDI\n1 NAME Ada /Example/\n0 TRLR\n"));
//! # Ok::<(), gedcomkit::GedcomError>(())
//! ```

use crate::{Document, GedcomError, GedcomErrorKind, Limits, Node, fault, is_tag, is_xref};
use std::collections::HashSet;

/// One structure described by the caller: what a producer builds before it
/// becomes a [`Node`].
///
/// Where [`Node::new`] panics on a tag the parser would not read back,
/// [`NodeSpec::into_node`] refuses it with an error, which is what input
/// from another language needs. With the `serde` feature it deserializes
/// from `{"tag": …, "xref": …, "value": …, "children": […]}`, every key but
/// `tag` optional and any other key refused — a misspelled `childs` is an
/// error, not a silently empty record.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct NodeSpec {
    /// The `@XREF@` identifier. Only a record — a structure at level zero —
    /// may carry one.
    #[cfg_attr(feature = "serde", serde(default))]
    pub xref: Option<String>,
    /// The tag: ASCII letters, digits, or underscore.
    pub tag: String,
    /// The logical payload. A newline in it becomes a `CONT` line; an empty
    /// payload is the same as none, since GEDCOM cannot tell them apart.
    #[cfg_attr(feature = "serde", serde(default))]
    pub value: Option<String>,
    /// Substructures, in the order they are to be written.
    #[cfg_attr(feature = "serde", serde(default))]
    pub children: Vec<Self>,
}

impl NodeSpec {
    /// A structure with a tag and nothing else.
    #[must_use]
    pub fn new(tag: impl Into<String>) -> Self {
        Self {
            tag: tag.into(),
            ..Self::default()
        }
    }

    /// A structure with a tag and a payload.
    #[must_use]
    pub fn with_value(tag: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            value: Some(value.into()),
            ..Self::new(tag)
        }
    }

    /// A record: a structure with an identifier.
    #[must_use]
    pub fn record(xref: impl Into<String>, tag: impl Into<String>) -> Self {
        Self {
            xref: Some(xref.into()),
            ..Self::new(tag)
        }
    }

    /// Checks the description and builds the node it describes.
    ///
    /// # Errors
    ///
    /// A [`GedcomErrorKind::Syntax`] error names the first tag or identifier
    /// the parser would not read back — including an identifier below level
    /// zero, where GEDCOM has none — and a [`GedcomErrorKind::Limit`] error
    /// a description nested deeper than `limits.depth` or larger than
    /// `limits.structures`.
    pub fn into_node(self, limits: Limits) -> Result<Node, GedcomError> {
        let mut structures = 0;
        self.build(0, limits, &mut structures)
    }

    /// As [`NodeSpec::into_node`], for a substructure rather than a record:
    /// an identifier on it is refused too.
    ///
    /// # Errors
    ///
    /// As [`NodeSpec::into_node`].
    pub fn into_substructure(self, limits: Limits) -> Result<Node, GedcomError> {
        let mut structures = 0;
        self.build(1, limits, &mut structures)
    }

    fn build(
        self,
        level: u16,
        limits: Limits,
        structures: &mut usize,
    ) -> Result<Node, GedcomError> {
        if level > limits.depth {
            return Err(fault(
                0,
                GedcomErrorKind::Limit,
                "the structure is nested deeper than the limit",
            ));
        }
        *structures += 1;
        if *structures > limits.structures {
            return Err(fault(
                0,
                GedcomErrorKind::Limit,
                "the record has too many structures",
            ));
        }
        if !is_tag(&self.tag) {
            return Err(fault(
                0,
                GedcomErrorKind::Syntax,
                format!(
                    "{:?} is not a GEDCOM tag: ASCII letters, digits, or underscore",
                    self.tag
                ),
            ));
        }
        let mut node = match self.xref {
            Some(xref) if level > 0 => {
                return Err(fault(
                    0,
                    GedcomErrorKind::Syntax,
                    format!(
                        "{xref} is on a {} below level zero, where only records carry identifiers",
                        self.tag
                    ),
                ));
            }
            Some(xref) if !is_xref(&xref) || xref.contains(' ') => {
                return Err(fault(
                    0,
                    GedcomErrorKind::Syntax,
                    format!("{xref:?} is not a cross-reference identifier: the @I1@ shape"),
                ));
            }
            Some(xref) => Node::record(xref, self.tag),
            None => Node::new(self.tag),
        };
        if let Some(value) = self.value.filter(|value| !value.is_empty()) {
            node.set_logical_value(&value);
        }
        for child in self.children {
            node.push(child.build(level + 1, limits, structures)?);
        }
        Ok(node)
    }
}

/// A structure [`Document::wrap_long_lines`] rewrote, addressed as
/// [`crate::UnresolvedPointer`] addresses one.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct WrappedLine {
    /// The record, by cross-reference identifier — or by tag, for the header
    /// and anything else without one.
    pub record: String,
    /// The path to the structure inside that record, as [`Node::at`] reads
    /// it after the rewrite.
    pub path: Vec<usize>,
    /// That structure's tag.
    pub tag: String,
}

/// The fewest bytes a line limit may leave for level, tag, and payload.
const SMALLEST_LINE_LIMIT: usize = 32;

impl Document {
    /// Adds substructures after the existing ones of the structure at `path`
    /// in `record` — a header's `DATE` and `SUBM`, say, which
    /// [`Document::new_v551`] cannot know.
    ///
    /// `record` is a cross-reference identifier, compared without regard to
    /// case, or the tag of a record that has none: `HEAD`. Adding
    /// substructures leaves every existing line as it was, so a parsed
    /// document keeps its byte-for-byte guarantee everywhere else.
    ///
    /// ```
    /// use gedcomkit::{Document, Node};
    ///
    /// let mut document = Document::new_v551("EXAMPLE");
    /// document.append_structures("HEAD", &[], vec![Node::with_value("SUBM", "@U1@")])?;
    /// assert_eq!(document.header().and_then(|header| header.value_of("SUBM")).as_deref(), Some("@U1@"));
    /// # Ok::<(), gedcomkit::GedcomError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// A [`GedcomErrorKind::Structure`] error, with nothing added, when no
    /// record or structure answers to the address, and a
    /// [`GedcomErrorKind::Syntax`] error when a structure carries an
    /// identifier, which only a record may.
    pub fn append_structures(
        &mut self,
        record: &str,
        path: &[usize],
        structures: Vec<Node>,
    ) -> Result<(), GedcomError> {
        if let Some(named) = structures.iter().find(|node| node.xref.is_some()) {
            return Err(fault(
                0,
                GedcomErrorKind::Syntax,
                format!(
                    "a {} below level zero cannot carry an identifier",
                    named.tag
                ),
            ));
        }
        let wanted = record.to_ascii_uppercase();
        let owner = self
            .records
            .iter_mut()
            .find(|node| {
                node.xref.as_ref().map_or_else(
                    || node.tag == record,
                    |xref| xref.to_ascii_uppercase() == wanted,
                )
            })
            .ok_or_else(|| fault(0, GedcomErrorKind::Structure, format!("no record {record}")))?;
        let target = owner.at_mut(path).ok_or_else(|| {
            fault(
                0,
                GedcomErrorKind::Structure,
                format!("no structure at {path:?} in {record}"),
            )
        })?;
        target.children.extend(structures);
        Ok(())
    }

    /// Adds records before the trailer, all or none.
    ///
    /// # Errors
    ///
    /// A [`GedcomErrorKind::Structure`] error, with nothing added, when a
    /// record is a header or trailer — the document already has its own — or
    /// when an identifier repeats one the document holds or another record in
    /// the same call (compared without regard to case, as
    /// [`Document::record`] compares).
    pub fn append_records(&mut self, records: Vec<Node>) -> Result<(), GedcomError> {
        let mut seen: HashSet<String> = self.xref_index().into_keys().collect();
        for record in &records {
            if matches!(record.tag.as_str(), "HEAD" | "TRLR") {
                return Err(fault(
                    0,
                    GedcomErrorKind::Structure,
                    format!(
                        "a document has one {}, and this one already does",
                        record.tag
                    ),
                ));
            }
            if let Some(xref) = &record.xref
                && !seen.insert(xref.to_ascii_uppercase())
            {
                return Err(fault(
                    0,
                    GedcomErrorKind::Structure,
                    format!("the document already has a record {xref}"),
                ));
            }
        }
        let at = self
            .records
            .iter()
            .rposition(|record| record.tag == "TRLR")
            .unwrap_or(self.records.len());
        self.records.splice(at..at, records);
        Ok(())
    }

    /// Splits every line longer than `max_line_bytes` across `CONC` lines,
    /// the 5.5.1 way, and names each structure it rewrote.
    ///
    /// GEDCOM 5.5.1 limits a line to 255 characters, terminator included,
    /// and pass `255` for exactly that; the count here is of UTF-8 bytes,
    /// which is never fewer than characters, so a line that fits is safe
    /// under either reading. A payload is only ever cut at a character
    /// boundary, and never beside a space where a choice exists — the
    /// specification's warning, since some readers strip the space at the
    /// end of a line and lose it from the joined value.
    ///
    /// This rewrites what it touches, so it is an explicit operation with a
    /// report rather than something writing does: a structure that fits is
    /// left exactly as it is, and one that does not has its payload's
    /// continuation lines rebuilt — as [`Node::set_logical_value`] rebuilds
    /// them — and is named in the result. A line whose level, identifier,
    /// and tag alone leave no room for a payload is left as it is.
    ///
    /// ```
    /// let mut document = gedcomkit::Document::new_v551("EXAMPLE");
    /// let note = gedcomkit::Node::record("@N1@", "NOTE").child(gedcomkit::Node::with_value("CONT", "x".repeat(300)));
    /// document.append_records(vec![note])?;
    /// let wrapped = document.wrap_long_lines(255)?;
    /// assert_eq!(wrapped.len(), 1);
    /// assert!(document.to_text().lines().all(|line| line.len() < 255));
    /// assert_eq!(document.record("@N1@").map(|note| note.logical_value()), Some(format!("\n{}", "x".repeat(300))));
    /// # Ok::<(), gedcomkit::GedcomError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// A [`GedcomErrorKind::Structure`] error when the document declares
    /// version 7, which has no `CONC` and no line limit, and a
    /// [`GedcomErrorKind::Limit`] error for a limit under 32 bytes.
    pub fn wrap_long_lines(
        &mut self,
        max_line_bytes: usize,
    ) -> Result<Vec<WrappedLine>, GedcomError> {
        if self.is_version_7_or_later() {
            return Err(fault(
                0,
                GedcomErrorKind::Structure,
                "version 7 has no CONC and no line limit, so there is nothing to wrap",
            ));
        }
        if max_line_bytes < SMALLEST_LINE_LIMIT {
            return Err(fault(
                0,
                GedcomErrorKind::Limit,
                format!(
                    "a line limit under {SMALLEST_LINE_LIMIT} bytes leaves no room for a payload"
                ),
            ));
        }
        // The terminator is part of the specification's count.
        let budget = max_line_bytes - 1;
        let mut wrapped = Vec::new();
        for record in &mut self.records {
            let owner = record.xref.clone().unwrap_or_else(|| record.tag.clone());
            let mut path = Vec::new();
            wrap_node(record, 0, budget, &owner, &mut path, &mut wrapped);
        }
        Ok(wrapped)
    }
}

fn wrap_node(
    node: &mut Node,
    level: u16,
    budget: usize,
    owner: &str,
    path: &mut Vec<usize>,
    wrapped: &mut Vec<WrappedLine>,
) {
    if needs_wrapping(node, level, budget) && rewrap(node, level, budget) {
        wrapped.push(WrappedLine {
            record: owner.to_owned(),
            path: path.clone(),
            tag: node.tag.clone(),
        });
    }
    for (index, child) in node.children.iter_mut().enumerate() {
        if matches!(child.tag.as_str(), "CONT" | "CONC") {
            continue;
        }
        path.push(index);
        wrap_node(child, level + 1, budget, owner, path, wrapped);
        path.pop();
    }
}

/// The bytes a line spends before its payload: level, a space, the
/// identifier and a space when there is one, the tag, and the space that
/// introduces the payload.
fn prefix_bytes(level: u16, xref: Option<&str>, tag: &str) -> usize {
    level.to_string().len() + 1 + xref.map_or(0, |xref| xref.len() + 1) + tag.len() + 1
}

fn line_bytes(node: &Node, level: u16) -> usize {
    node.verbatim.as_deref().map_or_else(
        || {
            prefix_bytes(level, node.xref.as_deref(), &node.tag) - 1
                + node.value.as_deref().map_or(0, |value| value.len() + 1)
        },
        str::len,
    )
}

fn needs_wrapping(node: &Node, level: u16, budget: usize) -> bool {
    line_bytes(node, level) > budget
        || node
            .children
            .iter()
            .filter(|child| matches!(child.tag.as_str(), "CONT" | "CONC"))
            .any(|child| line_bytes(child, level + 1) > budget)
}

/// Rebuilds one node's payload lines to fit. Returns false, changing
/// nothing, when the first line has no room for a payload at all.
fn rewrap(node: &mut Node, level: u16, budget: usize) -> bool {
    let Some(first_room) = budget.checked_sub(prefix_bytes(level, node.xref.as_deref(), &node.tag))
    else {
        return false;
    };
    let continuation_room = budget.saturating_sub(prefix_bytes(level + 1, None, "CONC"));
    // Four bytes is the widest UTF-8 character: less and a cut may not be
    // able to make progress.
    if first_room < 4 || continuation_room < 4 {
        return false;
    }
    let logical = node.logical_value();
    let mut value = None;
    let mut continuations = Vec::new();
    for (index, line) in logical.split('\n').enumerate() {
        let room = if index == 0 {
            first_room
        } else {
            continuation_room
        };
        let mut pieces = cut(line, room, continuation_room).into_iter();
        let head = pieces.next().filter(|piece| !piece.is_empty());
        if index == 0 {
            value = head.map(str::to_owned);
        } else {
            continuations.push(
                head.map_or_else(|| Node::new("CONT"), |head| Node::with_value("CONT", head)),
            );
        }
        continuations.extend(pieces.map(|piece| Node::with_value("CONC", piece)));
    }
    node.children
        .retain(|child| !matches!(child.tag.as_str(), "CONT" | "CONC"));
    node.set_value(value);
    for (index, continuation) in continuations.into_iter().enumerate() {
        node.children.insert(index, continuation);
    }
    true
}

/// Cuts one line of payload into pieces: the first at most `first` bytes, the
/// rest at most `rest`. Cuts fall on character boundaries and, where the
/// text allows, not beside a space.
fn cut(line: &str, first: usize, rest: usize) -> Vec<&str> {
    let mut pieces = Vec::new();
    let mut remaining = line;
    let mut room = first;
    while remaining.len() > room {
        let at = best_cut(remaining, room);
        pieces.push(&remaining[..at]);
        remaining = &remaining[at..];
        room = rest;
    }
    pieces.push(remaining);
    pieces
}

/// Where to cut `text` so the first piece holds at most `room` bytes: the
/// widest boundary with no space on either side of it; failing that, one
/// that at least leaves no space at the end of the line, where a reader is
/// likeliest to strip it; failing both, the widest. The search stays in the
/// upper half of the room, so text with few such boundaries still gets
/// lines of a useful length.
fn best_cut(text: &str, room: usize) -> usize {
    let widest = floor_boundary(text, room);
    let lowest = (widest / 2).max(1);
    let boundaries = || {
        (lowest..=widest)
            .rev()
            .filter(|&at| text.is_char_boundary(at))
    };
    boundaries()
        .find(|&at| !text[..at].ends_with(' ') && !text[at..].starts_with(' '))
        .or_else(|| boundaries().find(|&at| !text[..at].ends_with(' ')))
        .unwrap_or(widest)
}

/// The largest character boundary at or below `index`.
fn floor_boundary(text: &str, index: usize) -> usize {
    let mut at = index.min(text.len());
    while !text.is_char_boundary(at) {
        at -= 1;
    }
    at
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spec(tag: &str) -> NodeSpec {
        NodeSpec::new(tag)
    }

    #[test]
    fn a_description_becomes_the_node_it_describes() {
        let mut record = NodeSpec::record("@I1@", "INDI");
        let mut birth = spec("BIRT");
        birth
            .children
            .push(NodeSpec::with_value("DATE", "5 JAN 1882"));
        record
            .children
            .push(NodeSpec::with_value("NAME", "Ada /Example/"));
        record.children.push(birth);
        record
            .children
            .push(NodeSpec::with_value("NOTE", "one\ntwo"));
        record.children.push(NodeSpec::with_value("SEX", ""));
        let node = record.into_node(Limits::DEFAULT).expect("valid");
        let text = Document {
            records: vec![node],
        }
        .to_text();
        assert_eq!(
            text,
            "0 @I1@ INDI\n1 NAME Ada /Example/\n1 BIRT\n2 DATE 5 JAN 1882\n1 NOTE one\n2 CONT two\n1 SEX\n"
        );
    }

    #[test]
    fn a_description_the_parser_would_not_read_back_is_refused() {
        let refused = |spec: NodeSpec| spec.into_node(Limits::DEFAULT).expect_err("refused").kind();
        assert_eq!(refused(spec("NA ME")), GedcomErrorKind::Syntax);
        assert_eq!(refused(spec("")), GedcomErrorKind::Syntax);
        assert_eq!(
            refused(NodeSpec::record("I1", "INDI")),
            GedcomErrorKind::Syntax
        );
        assert_eq!(
            refused(NodeSpec::record("@I 1@", "INDI")),
            GedcomErrorKind::Syntax
        );
        let mut nested = spec("INDI");
        nested.children.push(NodeSpec::record("@X1@", "NOTE"));
        assert_eq!(refused(nested), GedcomErrorKind::Syntax);
    }

    #[test]
    fn a_description_is_bounded() {
        let mut deep = spec("A");
        for _ in 0..10 {
            let mut parent = spec("A");
            parent.children.push(deep);
            deep = parent;
        }
        let shallow = Limits::DEFAULT.with_depth(5);
        let error = deep.into_node(shallow).expect_err("too deep");
        assert_eq!(error.kind(), GedcomErrorKind::Limit);
    }

    #[test]
    fn substructures_join_the_header_or_a_record_and_nothing_else_moves() {
        let input = "0 HEAD\n1 SOUR  ODD\n1 GEDC\n2 VERS 5.5.1\n0 @I1@ INDI\n1 NAME Ada /Example/\n0 TRLR\n";
        let mut document = Document::parse(input).expect("parses");
        document
            .append_structures("HEAD", &[], vec![Node::with_value("SUBM", "@U1@")])
            .expect("header");
        document
            .append_structures("@i1@", &[0], vec![Node::with_value("GIVN", "Ada")])
            .expect("record");
        assert_eq!(
            document.to_text(),
            "0 HEAD\n1 SOUR  ODD\n1 GEDC\n2 VERS 5.5.1\n1 SUBM @U1@\n0 @I1@ INDI\n1 NAME Ada /Example/\n2 GIVN Ada\n0 TRLR\n"
        );
        let refused = |result: Result<(), GedcomError>| result.expect_err("refused").kind();
        assert_eq!(
            refused(document.append_structures("@I9@", &[], vec![Node::new("NOTE")])),
            GedcomErrorKind::Structure
        );
        assert_eq!(
            refused(document.append_structures("@I1@", &[7], vec![Node::new("NOTE")])),
            GedcomErrorKind::Structure
        );
        assert_eq!(
            refused(document.append_structures("@I1@", &[], vec![Node::record("@N1@", "NOTE")])),
            GedcomErrorKind::Syntax
        );
        let spec = NodeSpec::record("@N1@", "NOTE");
        assert!(spec.into_substructure(Limits::DEFAULT).is_err());
    }

    #[test]
    fn records_go_before_the_trailer_all_or_none() {
        let mut document = Document::new_v551("TEST");
        document
            .append_records(vec![
                Node::record("@I1@", "INDI"),
                Node::record("@F1@", "FAM"),
            ])
            .expect("appended");
        let tags: Vec<&str> = document.records.iter().map(Node::tag).collect();
        assert_eq!(tags, ["HEAD", "INDI", "FAM", "TRLR"]);

        let before = document.clone();
        let repeated = document.append_records(vec![
            Node::record("@I2@", "INDI"),
            Node::record("@i1@", "INDI"),
        ]);
        assert_eq!(
            repeated.expect_err("a repeated identifier").kind(),
            GedcomErrorKind::Structure
        );
        let twice = document.append_records(vec![
            Node::record("@I3@", "INDI"),
            Node::record("@I3@", "INDI"),
        ]);
        assert!(twice.is_err());
        assert!(document.append_records(vec![Node::new("TRLR")]).is_err());
        assert_eq!(document, before, "a refused call adds nothing");
    }

    #[test]
    fn long_lines_are_wrapped_at_characters_not_beside_spaces() {
        let text = "Pointe-Claire, Île de Montréal, Québec ".repeat(12);
        let mut document = Document::new_v551("TEST");
        let record = Node::record("@N1@", "NOTE").child(Node::with_value("NOTE", text.trim_end()));
        document.append_records(vec![record]).expect("appended");
        let untouched = document.records[0].clone();

        let wrapped = document.wrap_long_lines(80).expect("wrapped");
        assert_eq!(
            wrapped,
            [WrappedLine {
                record: "@N1@".into(),
                path: vec![0],
                tag: "NOTE".into()
            }]
        );
        let written = document.to_text();
        for line in written.lines() {
            assert!(line.len() < 80, "{line:?}");
            assert!(!line.ends_with(' '), "{line:?}");
        }
        let reread = Document::parse(&written).expect("reads back");
        let note = reread
            .record("@N1@")
            .and_then(|note| note.first("NOTE"))
            .expect("note");
        assert_eq!(note.logical_value(), text.trim_end());
        assert_eq!(
            document.records[0], untouched,
            "the header fits and is not touched"
        );
    }

    #[test]
    fn a_long_continuation_line_is_wrapped_in_place() {
        let long = "word ".repeat(80);
        let logical = format!("short\n{}\nend", long.trim_end());
        let mut document = Document::new_v551("TEST");
        let mut note = Node::record("@N1@", "NOTE");
        note.set_logical_value(&logical);
        let note = note.child(Node::with_value("SOUR", "@S1@"));
        document.append_records(vec![note]).expect("appended");
        document.wrap_long_lines(255).expect("wrapped");
        let reread = Document::parse(&document.to_text()).expect("reads back");
        let note = reread.record("@N1@").expect("note");
        assert_eq!(note.logical_value(), logical);
        assert_eq!(note.children.last().map(Node::tag), Some("SOUR"));
        assert!(document.to_text().lines().all(|line| line.len() < 255));
    }

    #[test]
    fn a_file_that_fits_is_left_exactly_as_it_was() {
        let input = "0 HEAD\n1 GEDC\n2 VERS 5.5.1\n0  @I1@ INDI\n1 NAME Ada /Example/\n0 TRLR\n";
        let mut document = Document::parse(input).expect("parses");
        assert!(document.wrap_long_lines(255).expect("wrapped").is_empty());
        assert_eq!(document.to_text(), input);
    }

    #[test]
    fn version_seven_and_tiny_limits_are_refused() {
        let mut seven = Document::new_v7();
        assert_eq!(
            seven.wrap_long_lines(255).expect_err("7.0").kind(),
            GedcomErrorKind::Structure
        );
        let mut five = Document::new_v551("TEST");
        assert_eq!(
            five.wrap_long_lines(10).expect_err("tiny").kind(),
            GedcomErrorKind::Limit
        );
    }

    #[test]
    fn cuts_fall_on_character_boundaries() {
        let text = "ÅÅÅÅÅÅÅÅÅÅ";
        for piece in cut(text, 5, 5) {
            assert!(piece.len() <= 5);
        }
        assert_eq!(cut(text, 5, 5).concat(), text);
        assert_eq!(cut("a b", 1, 1), ["a", " ", "b"]);
        // Every boundary in `x x x` has a space beside it; the cut leaves the
        // space at the start of the next line, never at the end of this one.
        for piece in cut(&"x ".repeat(40), 9, 9).iter().rev().skip(1) {
            assert!(!piece.ends_with(' '), "{piece:?}");
        }
    }
}