stratum-node-config 0.1.0-alpha.1

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! Change previews: comment-preserving edits, diffs and change lists.

use std::collections::{HashMap, VecDeque};
use std::fmt;

use serde::ser::{Serialize, SerializeStruct, Serializer};
use toml_edit::{DocumentMut, Item, Table};

use crate::document::{analyse, parse_toml, ConfigDocument, MAX_DOCUMENT_BYTES};
use crate::error::{PreviewError, ValidationError};
use crate::schema::{schema, ApplyClass, FieldDescriptor};
use crate::value::Value;

/// The text that stands in for a secret-reference value in change lists and
/// `Debug` output.
pub const REDACTED: &str = "<redacted>";

/// File name used in both headers of the unified diff.
const DIFF_FILE_NAME: &str = "stratum.toml";

/// Lines of unchanged context around each hunk of the unified diff.
const DIFF_CONTEXT_LINES: usize = 3;

/// A requested edit: set the field at `path` to `value`.
///
/// Deserialises from `{"path": "...", "value": ...}`, the shape of each entry
/// in the HTTP `changes` array. The path is checked by [`preview`], not here.
///
/// # Serialisation and redaction
///
/// `Serialize` writes the same shape back with the value **verbatim**, a
/// secret reference included, so a request round-trips unchanged. `Debug`
/// redacts the value of a secret-reference field to [`REDACTED`], so a
/// change can be logged with `{:?}`. Do not log or persist the serialised
/// form where secret references must not appear; build a [`FieldChange`]
/// list through [`preview`] instead, which is redacted. A reference names a
/// secret held by a custody service and is not the secret itself, but it
/// still tells a reader where to look, so it stays out of logs by default.
///
/// # Examples
///
/// ```
/// use stratum_node_config::Change;
///
/// let change = Change::new("limits.max_body_bytes", 65_536);
/// assert_eq!(change.path(), "limits.max_body_bytes");
/// ```
#[derive(Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Change {
    path: String,
    value: Value,
}

impl Change {
    /// Creates a change.
    pub fn new(path: impl Into<String>, value: impl Into<Value>) -> Self {
        Self {
            path: path.into(),
            value: value.into(),
        }
    }

    /// Returns the dotted path the change targets.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the requested value.
    pub fn value(&self) -> &Value {
        &self.value
    }
}

/// Redacts the value when the path names a secret-reference field.
impl fmt::Debug for Change {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let secret = schema()
            .field(&self.path)
            .is_some_and(FieldDescriptor::is_secret_ref);
        let mut s = f.debug_struct("Change");
        s.field("path", &self.path);
        if secret {
            s.field("value", &REDACTED);
        } else {
            s.field("value", &self.value);
        }
        s.finish()
    }
}

/// One entry of a preview's change list: a field whose effective value the
/// edit changes.
///
/// For secret-reference fields both values are replaced by
/// `Value::String("<redacted>")` (see [`REDACTED`]) when the entry is built,
/// so the reference never enters the change list.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldChange {
    path: &'static str,
    apply_class: ApplyClass,
    old: Option<Value>,
    new: Value,
    redacted: bool,
}

impl FieldChange {
    fn new(field: &'static FieldDescriptor, old: Option<Value>, new: Value) -> Self {
        let redacted = field.is_secret_ref();
        let hide = |v: Value| if redacted { Value::from(REDACTED) } else { v };
        Self {
            path: field.path(),
            apply_class: field.apply_class(),
            old: old.map(hide),
            new: hide(new),
            redacted,
        }
    }

    /// Returns the dotted path of the changed field.
    pub fn path(&self) -> &'static str {
        self.path
    }

    /// Returns when this change takes effect.
    pub fn apply_class(&self) -> ApplyClass {
        self.apply_class
    }

    /// Returns the effective value before the edit (the default when the
    /// base omitted the field), or `None` when the base held a value of a
    /// type that has no [`Value`] shape, such as a float.
    pub fn old(&self) -> Option<&Value> {
        self.old.as_ref()
    }

    /// Returns the value after the edit.
    pub fn new_value(&self) -> &Value {
        &self.new
    }

    /// Returns `true` if the values were replaced by [`REDACTED`].
    pub fn is_redacted(&self) -> bool {
        self.redacted
    }
}

impl Serialize for FieldChange {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut s = serializer.serialize_struct("FieldChange", 5)?;
        s.serialize_field("path", self.path)?;
        s.serialize_field("apply_class", &self.apply_class)?;
        s.serialize_field("old", &self.old)?;
        s.serialize_field("new", &self.new)?;
        s.serialize_field("redacted", &self.redacted)?;
        s.end()
    }
}

/// The result of [`preview`]: what an edit would do, computed without side
/// effects.
///
/// Serialises as `{"text", "diff", "changes", "strictest_apply_class",
/// "errors", "valid"}`.
///
/// # Serialisation and redaction
///
/// The serialised `text` and `diff` show secret-reference values exactly as
/// they appear in the TOML: the diff must be faithful (contract E1.3), and a
/// diff that hid lines would not be one. The serialised `changes` are
/// [`FieldChange`]s, redacted when built, and `errors` never contain a
/// secret-reference value. `Debug` shows only the change list, the strictest
/// class and the errors, never the text or diff, so `{:?}` is safe to log.
/// Send the serialised form only to a caller entitled to read the whole
/// configuration file, such as the administrator previewing an edit.
#[derive(Clone, PartialEq, Eq)]
pub struct Preview {
    text: String,
    diff: String,
    changes: Vec<FieldChange>,
    errors: Vec<ValidationError>,
    document: Option<ConfigDocument>,
}

impl Preview {
    /// Returns the edited TOML text. Outside the edited values it is
    /// byte-identical to the base, comments and blank lines included, for a
    /// base that uses one line ending throughout. A base with mixed line
    /// endings is written with the ending of its first line break; see
    /// [`preview`].
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns a unified diff from the base text to [`Preview::text`], empty
    /// when nothing changed. Unlike the change list, the diff shows
    /// secret-reference values as they appear in the TOML.
    pub fn diff(&self) -> &str {
        &self.diff
    }

    /// Returns the changed fields in schema order. Requested changes that
    /// leave a field's effective value as it was are omitted.
    pub fn changes(&self) -> &[FieldChange] {
        &self.changes
    }

    /// Returns the most disruptive apply class among the changes, or `None`
    /// when there are none.
    pub fn strictest_apply_class(&self) -> Option<ApplyClass> {
        self.changes.iter().map(FieldChange::apply_class).max()
    }

    /// Returns every validation error in the edited document; empty when it
    /// is valid.
    pub fn errors(&self) -> &[ValidationError] {
        &self.errors
    }

    /// Returns `true` if the edited document passed validation.
    pub fn is_valid(&self) -> bool {
        self.document.is_some()
    }

    /// Returns the edited document when it is valid.
    pub fn document(&self) -> Option<&ConfigDocument> {
        self.document.as_ref()
    }

    /// Consumes the preview and returns the edited document when it is valid.
    pub fn into_document(self) -> Option<ConfigDocument> {
        self.document
    }
}

/// Shows the change list and errors; the text and diff are elided because
/// they may contain secret references.
impl fmt::Debug for Preview {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Preview")
            .field("changes", &self.changes)
            .field("strictest_apply_class", &self.strictest_apply_class())
            .field("errors", &self.errors)
            .finish_non_exhaustive()
    }
}

impl Serialize for Preview {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut s = serializer.serialize_struct("Preview", 6)?;
        s.serialize_field("text", &self.text)?;
        s.serialize_field("diff", &self.diff)?;
        s.serialize_field("changes", &self.changes)?;
        s.serialize_field("strictest_apply_class", &self.strictest_apply_class())?;
        s.serialize_field("errors", &self.errors)?;
        s.serialize_field("valid", &self.is_valid())?;
        s.end()
    }
}

/// Computes what applying `changes` to `base_text` would produce.
///
/// The function is pure: it reads only its arguments and returns the same
/// bytes for the same input. Changes are applied in schema order, whatever
/// order they are given in. Each edit replaces only the value: comments,
/// blank lines, key order and the decoration around the value (including a
/// trailing comment on the same line) are kept. A field absent from the
/// base is appended to its table, and a missing table is appended to the
/// document. A change that leaves the field's effective value unchanged
/// (counting defaults) is dropped and does not touch the text.
///
/// # Line endings
///
/// The edited text uses the base's line ending: CRLF when the first line
/// break of `base_text` is CRLF, LF otherwise (including a base with no line
/// break). Every line of the edited text, inserted or kept, ends that way, so
/// a CRLF document stays entirely CRLF and its diff shows only the lines an
/// edit changed. A base that mixes endings is the one case where unedited
/// lines can change: they are rewritten with the ending of its first line
/// break. When no change takes effect the base is returned verbatim, mixed
/// endings included.
///
/// The base need not be valid, only parseable, so a preview can repair an
/// invalid document. A change value of the wrong type for its field is
/// written as given and then reported in [`Preview::errors`].
///
/// # Editing a list
///
/// A list is edited element by element, so the comments inside it stay with
/// what they describe:
///
/// - **Ownership.** An element owns the comment lines directly above it
///   (everything between the previous element's line and itself) and the
///   comment ending its own line; when several elements share a line, that
///   comment belongs to the last of them. The list itself owns a comment on
///   the `[` line, the comment lines before the closing `]`, and everything
///   outside the brackets. In an empty list every comment is the list's.
/// - **Matching.** Old and new elements are matched by value, each new
///   element taking the first old element with the same text that is not yet
///   taken. Reordering therefore moves an element together with its
///   comments, and of two equal elements the earlier keeps its comments.
/// - **Survivors** keep their comments exactly once. A **removed** element's
///   comments are removed with it; replacing an element is removing one and
///   adding another. **New** elements own no comment and take the
///   surrounding style: in a multiline list a line of their own at the
///   existing indentation, in a single-line list the spacing of their
///   position.
/// - **The list's own comments** are always kept exactly once, including
///   when the list is cleared or filled from empty. A comment line is never
///   joined to another element's line: one that began a line still does.
/// - An **unchanged** list is left byte-identical.
/// - The trailing comma is kept; filling an empty multiline list adds one,
///   and clearing a list removes it and writes `[]` when only whitespace
///   would remain between the brackets.
///
/// # Errors
///
/// Returns [`PreviewError::TooLarge`] if `base_text`, or the text the
/// changes produce, is longer than [`MAX_DOCUMENT_BYTES`] (checked before
/// parsing the base and before diffing the result),
/// [`PreviewError::Syntax`] if `base_text` is not valid TOML,
/// [`PreviewError::UnknownPath`] if a change names a path not in the schema,
/// [`PreviewError::DuplicatePath`] if two changes name the same path, and
/// [`PreviewError::NotEditable`] if the base holds a non-table where the
/// field's table belongs, or a table where the field's value belongs.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{preview, ApplyClass, Change, Value};
///
/// let base = "schema_version = 1\n\n[limits]\n# Per-request cap.\nmax_body_bytes = 262144\n";
/// let p = preview(base, &[
///     Change::new("limits.max_body_bytes", 65_536),
///     Change::new("node.name", "alpha"),
/// ])?;
/// assert!(p.is_valid());
/// assert!(p.text().contains("# Per-request cap.\nmax_body_bytes = 65536\n"));
/// assert_eq!(p.changes()[0].path(), "node.name"); // schema order
/// assert_eq!(p.changes()[1].old(), Some(&Value::Integer(262_144)));
/// assert_eq!(p.strictest_apply_class(), Some(ApplyClass::Restart));
/// assert!(p.diff().contains("-max_body_bytes = 262144\n+max_body_bytes = 65536\n"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn preview(base_text: &str, changes: &[Change]) -> Result<Preview, PreviewError> {
    let mut resolved: Vec<(usize, &'static FieldDescriptor, &Value)> =
        Vec::with_capacity(changes.len());
    for change in changes {
        let Some(index) = schema().index_of(&change.path) else {
            return Err(PreviewError::UnknownPath {
                path: change.path.clone(),
            });
        };
        if resolved.iter().any(|(i, _, _)| *i == index) {
            return Err(PreviewError::DuplicatePath {
                path: change.path.clone(),
            });
        }
        resolved.push((index, &schema().table()[index], &change.value));
    }
    resolved.sort_by_key(|(i, _, _)| *i);

    let too_large = PreviewError::TooLarge {
        limit: MAX_DOCUMENT_BYTES,
    };
    if base_text.len() > MAX_DOCUMENT_BYTES {
        return Err(too_large);
    }
    let mut doc = parse_toml(base_text).map_err(PreviewError::Syntax)?;
    let base = analyse(&doc);

    let mut list = Vec::new();
    for (index, field, value) in resolved {
        let old = base.values.get(index).cloned().flatten();
        if old.as_ref() == Some(value) {
            continue;
        }
        set_value(&mut doc, field, value)?;
        list.push(FieldChange::new(field, old, value.clone()));
    }

    let text = if list.is_empty() {
        base_text.to_owned()
    } else {
        LineEnding::of(base_text).apply(doc.to_string())
    };
    if text.len() > MAX_DOCUMENT_BYTES {
        return Err(too_large);
    }
    let diff = unified_diff(base_text, &text);
    let (errors, document) = match parse_toml(&text) {
        Err(e) => (vec![e], None),
        Ok(edited) => match ConfigDocument::from_toml(text.clone(), &edited) {
            Ok(document) => (Vec::new(), Some(document)),
            Err(errors) => (errors.into_vec(), None),
        },
    };
    Ok(Preview {
        text,
        diff,
        changes: list,
        errors,
        document,
    })
}

/// The line break an edited document is written with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LineEnding {
    Lf,
    CrLf,
}

impl LineEnding {
    /// The ending of the first line break in `text`, or LF when it has none.
    fn of(text: &str) -> Self {
        match text.find('\n') {
            Some(i) if text[..i].ends_with('\r') => Self::CrLf,
            _ => Self::Lf,
        }
    }

    /// Rewrites every line break of `text` with this ending.
    ///
    /// `toml_edit` writes LF after every key, table header and decoration it
    /// emits, whatever the source used, so its output is LF apart from any
    /// CRLF kept inside the raw text of a multi-line string. Both kinds are
    /// first folded to LF and then expanded. A carriage return can only
    /// appear in valid TOML as part of a CRLF line break, so nothing else is
    /// touched; and no string field of the schema accepts a line break inside
    /// its value, so the conversion cannot change a valid document's values.
    fn apply(self, text: String) -> String {
        let lf = if text.contains('\r') {
            text.replace("\r\n", "\n")
        } else {
            text
        };
        match self {
            Self::Lf => lf,
            Self::CrLf => lf.replace('\n', "\r\n"),
        }
    }
}

/// Writes `value` into the document, keeping the old value's decoration.
fn set_value(
    doc: &mut DocumentMut,
    field: &'static FieldDescriptor,
    value: &Value,
) -> Result<(), PreviewError> {
    let section = field.section();
    if doc.get(section).is_none() {
        doc.insert(section, Item::Table(Table::new()));
    }
    let table = doc
        .get_mut(section)
        .and_then(Item::as_table_like_mut)
        .ok_or_else(|| PreviewError::NotEditable {
            path: section.to_owned(),
        })?;
    let mut new = value.to_toml();
    match table.get_mut(field.key()) {
        None => {
            table.insert(field.key(), Item::Value(new));
        }
        Some(item) => {
            let old = item
                .as_value_mut()
                .ok_or_else(|| PreviewError::NotEditable {
                    path: field.path().to_owned(),
                })?;
            match (old, value) {
                (toml_edit::Value::Array(array), Value::StringList(list)) => {
                    edit_array(array, list);
                }
                (old, _) => {
                    *new.decor_mut() = old.decor().clone();
                    *old = new;
                }
            }
        }
    }
    Ok(())
}

/// Rewrites `array` in place to hold `list`, keeping its comments.
///
/// The ownership model, which [`preview`] documents for callers:
///
/// - **Elements.** An element owns its *head*, every line between the end of
///   the previous element's line (or the `[` line) and itself, which holds
///   the comment lines written above it and its indentation; the text between
///   its value and its comma; and its *tail*, the rest of its own line after
///   the comma, which holds a comment on that line. When elements share a
///   line, the comment ending it belongs to the last of them.
/// - **The array.** The array owns the rest of the `[` line (a comment on
///   it), everything after the last element's line up to `]` (comments
///   before the closing bracket), and its decoration outside the brackets.
///   In an empty array, the first line inside the brackets is the `[` line
///   and the rest is the closing part.
/// - **Matching.** Old and new elements are matched by value: each new
///   element takes the first unmatched old element with the same string, so
///   a reordered element moves with everything it owns. Unmatched old
///   elements are removed with everything they own; unmatched new elements
///   own nothing.
/// - **Layout.** A head or closing part that began a line still begins one:
///   a newline is inserted before it when the text before it no longer ends
///   a line, so a comment is never joined to another element's line. In a
///   multiline array a new element starts a line at the existing
///   indentation and the line ends after it; in a single-line array it
///   takes the spacing of its position. Whitespace that separates elements
///   on one line belongs to the position, not the element, so an unchanged
///   list is rebuilt byte for byte.
/// - **Commas.** The trailing comma is kept as it was. Filling an empty
///   multiline array adds one; clearing an array removes it, and clearing
///   collapses the brackets to `[]` when nothing but whitespace is left.
fn edit_array(array: &mut toml_edit::Array, list: &[String]) {
    let layout = ArrayLayout::parse(array);
    let rendered = layout.render(list);
    let decor = array.decor().clone();
    *array = rendered;
    *array.decor_mut() = decor;
}

/// A run of text that precedes an element's value or the closing `]`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Lead {
    text: String,
    /// The text began a line in the old array.
    starts_line: bool,
}

/// An old element and the text it owns.
#[derive(Debug, Clone)]
struct Element {
    value: toml_edit::Value,
    head: Lead,
    before_comma: String,
    tail: String,
}

/// An array split into the text each element and the array itself own.
#[derive(Debug, Clone)]
struct ArrayLayout {
    opening: String,
    elements: Vec<Element>,
    closing: Lead,
    trailing_comma: bool,
    multiline: bool,
}

impl ArrayLayout {
    fn parse(array: &toml_edit::Array) -> Self {
        let values: Vec<&toml_edit::Value> = array.iter().collect();
        let n = values.len();
        let trailing_comma = n > 0 && array.trailing_comma();
        let mut opening = String::new();
        let mut elements: Vec<Element> = Vec::with_capacity(n);
        for (i, v) in values.iter().enumerate() {
            let (line_end, rest) = split_first_line(raw(v.decor().prefix()));
            match elements.last_mut() {
                Some(previous) => line_end.clone_into(&mut previous.tail),
                None => line_end.clone_into(&mut opening),
            }
            let before_comma = if i + 1 < n || trailing_comma {
                raw(v.decor().suffix()).to_owned()
            } else {
                String::new()
            };
            let mut value = (*v).clone();
            value.decor_mut().clear();
            elements.push(Element {
                value,
                head: Lead {
                    text: rest.to_owned(),
                    starts_line: !line_end.is_empty(),
                },
                before_comma,
                tail: String::new(),
            });
        }
        // The text after the last element's comma, or, without a trailing
        // comma, after its value (stored as its suffix).
        let last_gap = match values.last() {
            Some(last) if !trailing_comma => raw(last.decor().suffix()),
            _ => raw(Some(array.trailing())),
        };
        let (line_end, rest) = split_first_line(last_gap);
        match elements.last_mut() {
            Some(last) => line_end.clone_into(&mut last.tail),
            None => line_end.clone_into(&mut opening),
        }
        let closing = Lead {
            text: rest.to_owned(),
            starts_line: !line_end.is_empty(),
        };
        let multiline = opening.contains('\n')
            || closing.text.contains('\n')
            || elements.iter().any(|e| {
                e.head.text.contains('\n') || e.before_comma.contains('\n') || e.tail.contains('\n')
            });
        Self {
            opening,
            elements,
            closing,
            trailing_comma,
            multiline,
        }
    }

    /// Builds the array for `list` (without the decoration outside the
    /// brackets, which the caller keeps).
    fn render(&self, list: &[String]) -> toml_edit::Array {
        let mut unmatched: HashMap<&str, VecDeque<&Element>> = HashMap::new();
        for e in &self.elements {
            if let Some(s) = e.value.as_str() {
                unmatched.entry(s).or_default().push_back(e);
            }
        }
        let indent = self.indent();
        let mut out = toml_edit::Array::new();
        let mut pending = self.opening.clone();
        let mut last_before_comma = String::new();
        for (position, s) in list.iter().enumerate() {
            let survivor = unmatched.get_mut(s.as_str()).and_then(VecDeque::pop_front);
            let (mut value, head, before_comma, tail) = if let Some(e) = survivor {
                (
                    e.value.clone(),
                    e.head.clone(),
                    e.before_comma.as_str(),
                    e.tail.as_str(),
                )
            } else {
                let head = Lead {
                    text: if self.multiline {
                        indent.clone()
                    } else {
                        String::new()
                    },
                    starts_line: self.multiline,
                };
                let tail = if self.multiline { "\n" } else { "" };
                (toml_edit::Value::from(s.as_str()), head, "", tail)
            };
            self.place_head(&mut pending, &head, position, &indent);
            value.decor_mut().set_prefix(std::mem::take(&mut pending));
            value.decor_mut().set_suffix(before_comma);
            out.push_formatted(value);
            before_comma.clone_into(&mut last_before_comma);
            tail.clone_into(&mut pending);
        }

        place_after_line_break(&mut pending, &self.closing);
        if list.is_empty() {
            if !self.elements.is_empty() && is_blank(&pending) {
                pending.clear();
            }
            out.set_trailing(pending);
            out.set_trailing_comma(false);
            return out;
        }
        let trailing_comma = if self.elements.is_empty() {
            self.multiline
        } else {
            self.trailing_comma
        };
        if trailing_comma {
            out.set_trailing(pending);
        } else if let Some(last) = out.iter_mut().last() {
            last.decor_mut()
                .set_suffix(format!("{last_before_comma}{pending}"));
        }
        out.set_trailing_comma(trailing_comma);
        out
    }

    /// Appends an element's head to `pending`, the text since the previous
    /// comma (or the `[`), applying the layout rules.
    fn place_head(&self, pending: &mut String, head: &Lead, position: usize, indent: &str) {
        let spacing_only = !head.text.contains('\n') && is_blank(&head.text);
        if !spacing_only {
            place_after_line_break(pending, head);
        } else if pending.ends_with('\n') {
            pending.push_str(if head.starts_line { &head.text } else { indent });
        } else if head.starts_line {
            pending.push('\n');
            pending.push_str(&head.text);
        } else {
            pending.push_str(self.spacing(position));
        }
    }

    /// The whitespace before the value at `position` on a shared line: the
    /// old array's spacing at that position, else the spacing of its last
    /// position after the first, else none for the first and one space for
    /// the rest.
    fn spacing(&self, position: usize) -> &str {
        fn same_line(e: &Element) -> Option<&str> {
            (!e.head.starts_line).then_some(e.head.text.as_str())
        }
        if let Some(s) = self.elements.get(position).and_then(same_line) {
            return s;
        }
        if position == 0 {
            return "";
        }
        self.elements
            .iter()
            .skip(1)
            .rev()
            .find_map(same_line)
            .unwrap_or(" ")
    }

    /// The indentation for a new element in a multiline array: that of the
    /// first old element that begins a line, else that of a comment before
    /// `]`, else four spaces.
    fn indent(&self) -> String {
        let after_newline = |s: &str| s.rfind('\n').map_or(s, |i| &s[i + 1..]).to_owned();
        if let Some(e) = self.elements.iter().find(|e| e.head.starts_line) {
            return after_newline(&e.head.text);
        }
        let first_line = self.closing.text.split('\n').next().unwrap_or_default();
        if self.closing.starts_line && !is_blank(first_line) {
            return first_line
                .chars()
                .take_while(|c| *c == ' ' || *c == '\t')
                .collect();
        }
        "    ".to_owned()
    }
}

/// Appends `lead` to `pending`, first ending the current line if `lead`
/// began a line in the old array and `pending` does not end one now.
fn place_after_line_break(pending: &mut String, lead: &Lead) {
    if lead.starts_line && !pending.ends_with('\n') {
        pending.push('\n');
    }
    pending.push_str(&lead.text);
}

/// Splits `s` after its first newline: the end of the current line
/// (including the newline) and the rest. Without a newline the whole of `s`
/// is the rest.
fn split_first_line(s: &str) -> (&str, &str) {
    match s.find('\n') {
        Some(i) => s.split_at(i + 1),
        None => ("", s),
    }
}

/// The text of a parsed decoration, or `""` when it is unset.
fn raw(s: Option<&toml_edit::RawString>) -> &str {
    s.and_then(toml_edit::RawString::as_str).unwrap_or_default()
}

fn is_blank(s: &str) -> bool {
    s.chars().all(char::is_whitespace)
}

fn unified_diff(old: &str, new: &str) -> String {
    if old == new {
        return String::new();
    }
    similar::TextDiff::from_lines(old, new)
        .unified_diff()
        .context_radius(DIFF_CONTEXT_LINES)
        .header(DIFF_FILE_NAME, DIFF_FILE_NAME)
        .to_string()
}

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

    use super::*;

    /// Parses `a = <array>` and returns the document.
    fn doc_of(array: &str) -> DocumentMut {
        format!("a = {array}\n").parse().expect("test input parses")
    }

    fn array_mut(doc: &mut DocumentMut) -> &mut toml_edit::Array {
        doc["a"]
            .as_value_mut()
            .and_then(toml_edit::Value::as_array_mut)
            .expect("an array")
    }

    fn strings(doc: &DocumentMut) -> Vec<String> {
        doc["a"]
            .as_array()
            .expect("an array")
            .iter()
            .map(|v| v.as_str().expect("a string").to_owned())
            .collect()
    }

    /// Edits the array in `a = <array>` to `list` and returns the text.
    fn edited(array: &str, list: &[String]) -> String {
        let mut doc = doc_of(array);
        edit_array(array_mut(&mut doc), list);
        doc.to_string()
    }

    #[test]
    fn unchanged_list_is_rebuilt_byte_for_byte() {
        for array in [
            "[ \"A\",\t\"B\" ]",
            "[]",
            "[ ]",
            "[\n]",
            "[ # opening\n # closing\n]",
            "[\"A\", \"B\",\n# C head\n\"C\",\n]",
            "[\n    # head\n    \"A\" , # tail\n\n    \"B\"\n    # closing\n] # outer",
            "[\"A\" # before the comma\n, \"B\"]",
        ] {
            let doc = doc_of(array);
            let list = strings(&doc);
            assert_eq!(edited(array, &list), doc.to_string(), "{array:?}");
        }
    }

    /// Gaps that can stand between tokens of an array, comments and blank
    /// lines included.
    fn gap() -> impl Strategy<Value = String> {
        prop_oneof![
            Just(String::new()),
            Just(" ".to_owned()),
            Just("\t".to_owned()),
            Just("\n".to_owned()),
            Just("\n\n  ".to_owned()),
            (0u8..100).prop_map(|n| format!(" # c{n}\n")),
            (0u8..100).prop_map(|n| format!("\n  # c{n}\n  ")),
        ]
    }

    /// Arbitrary layouts: a gap before each value, between each value and its
    /// comma, and before `]`, with an optional trailing comma.
    fn any_array() -> impl Strategy<Value = String> {
        (
            proptest::collection::vec(((0u8..4), gap(), gap()), 0..6),
            any::<bool>(),
            gap(),
        )
            .prop_map(|(items, trailing_comma, closing)| {
                let mut out = String::from("[");
                let n = items.len();
                for (i, (v, before, after)) in items.iter().enumerate() {
                    out.push_str(before);
                    out.push_str(&toml_edit::Value::from(format!("v{v}")).to_string());
                    out.push_str(after);
                    if i + 1 < n || trailing_comma {
                        out.push(',');
                    }
                }
                out.push_str(&closing);
                out.push(']');
                out
            })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(4096))]

        #[test]
        fn any_layout_rebuilds_unchanged_and_edits_to_valid_toml(
            array in any_array(),
            list in proptest::collection::vec((0u8..5).prop_map(|v| format!("v{v}")), 0..7),
        ) {
            let doc = doc_of(&array);
            let same = strings(&doc);
            prop_assert_eq!(edited(&array, &same), doc.to_string(), "identity");

            let text = edited(&array, &list);
            let reparsed: DocumentMut = text
                .parse()
                .map_err(|e| TestCaseError::fail(format!("{e}: {text:?}")))?;
            prop_assert_eq!(strings(&reparsed), list, "values of {:?}", text);
        }
    }
}