use std::collections::BTreeSet;
use toml_edit::{ArrayOfTables, Decor, DocumentMut, Item, Key, Table, Value};
use crate::align::align_sections;
use crate::decor::{DefaultEcho, DocBlock, Marker, Prefix, PrefixLine, Sample};
use crate::error::Error;
use crate::options::{MergeOptions, ResolvedMigration};
use crate::path::DottedPath;
use crate::report::{Diagnostic, DiagnosticKind, Position, Report, SpanIndex, TomlType};
use crate::source::SourceDocument;
use crate::template::{Template, comment_out};
#[derive(Debug, Clone)]
pub struct Merged {
pub report: Report,
pub(crate) document: DocumentMut,
pub(crate) newline: Newline,
pub(crate) defaults: String,
pub(crate) options: MergeOptions,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Newline {
#[default]
Lf,
CrLf,
}
impl Newline {
pub(crate) fn of(src: &str) -> Self {
if src.contains("\r\n") {
Self::CrLf
} else {
Self::Lf
}
}
pub(crate) fn apply(self, text: String) -> String {
match self {
Self::Lf => text,
Self::CrLf => text.replace("\r\n", "\n").replace('\n', "\r\n"),
}
}
}
impl Merged {
pub fn document(&self) -> &DocumentMut {
&self.document
}
pub fn into_document(self) -> DocumentMut {
self.document
}
pub fn to_toml_string(&self) -> String {
self.newline.apply(self.document.to_string())
}
pub fn newline(&self) -> Newline {
self.newline
}
pub fn set(&mut self, path: &str, value: impl Into<Value>) -> Result<(), Error> {
let parsed = DottedPath::parse(path).map_err(|source| Error::SetPath { source })?;
let mut document = self.document.clone();
if !assign(document.as_table_mut(), &parsed, value.into()) {
return Err(Error::NotAValue {
path: path.to_owned(),
});
}
let text = self.newline.apply(document.to_string());
*self = self.options.merge(&self.defaults, &text)?;
Ok(())
}
pub fn user_set(&self, path: &str) -> bool {
let Ok(path) = DottedPath::parse(path) else {
return false;
};
lookup(self.document.as_table(), &path).is_some_and(|item| match item {
Item::None => false,
Item::Table(table) => !table.is_empty(),
Item::ArrayOfTables(array) => !array.is_empty(),
Item::Value(_) => true,
})
}
}
#[derive(Debug, Clone)]
pub struct MergeEngine {
pub(crate) defaults: SourceDocument,
pub(crate) user: SourceDocument,
pub(crate) user_src: String,
pub(crate) options: MergeOptions,
pub(crate) migrations: Vec<ResolvedMigration>,
pub(crate) spans: SpanIndex,
pub(crate) report: Report,
pub(crate) template: Template,
pub(crate) pending: Vec<String>,
pub(crate) pending_spaced: bool,
pub(crate) dotted: Vec<String>,
}
impl MergeEngine {
pub(crate) fn new(
defaults: SourceDocument,
user: SourceDocument,
user_src: &str,
options: MergeOptions,
migrations: Vec<ResolvedMigration>,
spans: SpanIndex,
) -> Self {
Self {
defaults,
user,
user_src: user_src.to_owned(),
options,
migrations,
spans,
report: Report::default(),
template: Template::default(),
pending: Vec::new(),
pending_spaced: true,
dotted: Vec::new(),
}
}
pub(crate) fn run(mut self) -> Merged {
self.apply_migrations();
self.template = Template::of(&self.defaults, self.marker());
let empty = Table::new();
let defaults = self.defaults.root().unwrap_or(&empty).clone();
let user = self.user.root().unwrap_or(&empty).clone();
let mut root = Table::new();
self.merge_table(&defaults, &user, &mut root, None);
renumber_tables(&mut root, &mut 0);
space_sections(&mut root, &mut false, false);
if self.options.align {
align_sections(&mut root);
}
let mut document = DocumentMut::new();
*document.as_table_mut() = root;
let keys = !document.as_table().is_empty();
document.set_trailing(self.merged_trailing(keys));
Merged {
report: self.report,
document,
newline: Newline::of(&self.user_src),
defaults: String::new(),
options: self.options,
}
}
fn marker(&self) -> &Marker {
&self.options.marker
}
fn position(&self, path: &DottedPath) -> Position {
self.spans.position(&self.user_src, path)
}
fn apply_migrations(&mut self) {
let migrations = std::mem::take(&mut self.migrations);
for migration in &migrations {
let Some(root) = self.user.root_mut() else {
break;
};
if lookup(root, &migration.to).is_some() {
continue;
}
let Some((key, item)) = take(root, &migration.from) else {
continue;
};
let renamed = Key::new(migration.to.leaf()).with_leaf_decor(key.leaf_decor().clone());
if !place(root, &migration.to, renamed, item) {
continue;
}
let at = self.position(&migration.from);
self.report.push(Diagnostic::new(
DiagnosticKind::Migrated {
from: migration.from.clone(),
},
migration.to.clone(),
at,
));
}
self.migrations = migrations;
}
fn merge_table(
&mut self,
defaults: &Table,
user: &Table,
out: &mut Table,
path: Option<&DottedPath>,
) {
let optional = self.template.under(path).cloned().unwrap_or_default();
let mut done: BTreeSet<String> = defaults.iter().map(|(name, _)| name.to_owned()).collect();
for (name, default_item) in defaults.iter() {
if matches!(default_item, Item::None) {
continue;
}
let default_key = defaults.key(name).expect("a name iterated has a key");
let child = child_path(path, name);
self.merge_optional(&optional, &mut done, user, out, path, Some(&child));
match user.get_key_value(name) {
None => {
if self.options.commented && !opens_section(default_item) {
self.comment_default(default_key, default_item, &child);
} else {
let first = out.is_empty();
let (key, item) =
self.default_entry(default_key, default_item, &child, first);
out.insert_formatted(&key, item);
}
}
Some((user_key, user_item)) => {
self.merge_item(default_key, default_item, user_key, user_item, out, &child);
}
}
}
self.merge_optional(&optional, &mut done, user, out, path, None);
for (name, user_item) in user.iter() {
if done.contains(name) || matches!(user_item, Item::None) {
continue;
}
let user_key = user.key(name).expect("a name iterated has a key");
let child = child_path(path, name);
if !self.template.knows(&child) {
let at = self.position(&child);
self.report.push(Diagnostic::new(
DiagnosticKind::UnknownKey,
child.clone(),
at,
));
}
let (key, item) = self.keep_unknown(user_key, user_item, &child);
out.insert_formatted(&key, item);
}
}
fn merge_optional(
&mut self,
optional: &Table,
done: &mut BTreeSet<String>,
user: &Table,
out: &mut Table,
path: Option<&DottedPath>,
above: Option<&DottedPath>,
) {
for (name, item) in optional.iter() {
if done.contains(name) || matches!(item, Item::None) {
continue;
}
let child = child_path(path, name);
let due = match above {
Some(next) => self.template.written_before(&child) == Some(next),
None => true,
};
if !due {
continue;
}
let Some(key) = optional.key(name) else {
continue;
};
done.insert(name.to_owned());
match user.get_key_value(name) {
Some((user_key, user_item)) => {
self.optional_set(key, item, user_key, user_item, out, &child);
}
None => {
if self.pending.is_empty() {
self.pending_spaced = true;
} else {
self.pending.push(String::new());
}
self.pending
.extend(comment_out(&child, key, item, self.marker()));
}
}
}
}
fn optional_set(
&mut self,
key: &Key,
item: &Item,
user_key: &Key,
user_item: &Item,
out: &mut Table,
path: &DottedPath,
) {
let first = out.is_empty();
let mut block = DocBlock::default();
block.keep_user_text(&Prefix::of(decor_of(user_key, user_item)), self.marker());
let (_, touching) = Prefix::of(decor_of(key, item)).split(self.marker());
block.take_docs(&touching);
block.floating = std::mem::take(&mut self.pending);
if !block.floating.is_empty() {
block.floating.insert(0, String::new());
block.floating.push(String::new());
}
let mut merged = match (item, user_item) {
(Item::Value(_), Item::Value(user_value)) => {
self.record_default(&mut block, key, item, Some(user_value));
Item::Value(user_value.clone())
}
(_, Item::Table(user_table)) => {
let mut merged = Table::new();
merged.set_dotted(user_table.is_dotted());
self.descend(user_key, user_table, |engine| {
engine.merge_table(&Table::new(), user_table, &mut merged, Some(path));
});
Item::Table(merged)
}
(_, Item::ArrayOfTables(user_array)) => {
let mut array = user_array.clone();
if let Some(entry) = array.get_mut(0) {
let mut merged = Table::new();
self.merge_table(&Table::new(), entry, &mut merged, Some(path));
*entry = merged;
}
let unset = std::mem::take(&mut self.pending);
for (index, entry) in array.iter_mut().enumerate().skip(1) {
let mut block = DocBlock::default();
block.keep_user_text(&Prefix::of(entry.decor()), self.marker());
if index == 1 && !unset.is_empty() {
block.floating = unset.clone();
if self.pending_spaced {
block.floating.insert(0, String::new());
}
block.floating.push(String::new());
}
entry.decor_mut().set_prefix(block.render(self.marker()));
}
if array.len() < 2 {
self.pending = unset;
}
if let Item::ArrayOfTables(template_array) = item {
for extra in template_array.iter().skip(1) {
let mut single = ArrayOfTables::new();
single.push(extra.clone());
if !self.pending.is_empty() {
self.pending.push(String::new());
}
let lines =
comment_out(path, key, &Item::ArrayOfTables(single), self.marker());
self.pending.extend(lines);
}
}
Item::ArrayOfTables(array)
}
_ => user_item.clone(),
};
let documented = !block.prose.is_empty() || !matches!(block.sample, Sample::None);
if block.leading_blanks.is_empty() && !first && documented {
block.leading_blanks = vec![String::new()];
}
let mut key = user_key.clone();
set_prefix(&mut key, &mut merged, block.render(self.marker()));
out.insert_formatted(&key, merged);
}
fn merge_item(
&mut self,
default_key: &Key,
default_item: &Item,
user_key: &Key,
user_item: &Item,
out: &mut Table,
path: &DottedPath,
) {
let first = out.is_empty();
let mut block = self.block(
decor_of(default_key, default_item),
decor_of(user_key, user_item),
);
self.flush_pending(&mut block, first);
let expected = TomlType::of(default_item);
let found = TomlType::of(user_item);
let compatible = expected == found
|| matches!(
(expected, found),
(Some(TomlType::Float), Some(TomlType::Integer))
);
let mut item = if !compatible {
if let (Some(expected), Some(found)) = (expected, found) {
let at = self.position(path);
self.report.push(Diagnostic::new(
DiagnosticKind::TypeMismatch { expected, found },
path.clone(),
at,
));
}
self.record_default(&mut block, default_key, default_item, None);
user_item.clone()
} else {
match (default_item, user_item) {
(Item::Value(_), Item::Value(user_value)) => {
self.record_default(&mut block, default_key, default_item, Some(user_value));
Item::Value(user_value.clone())
}
(Item::Table(default_table), Item::Table(user_table)) => {
let mut merged = Table::new();
merged.set_dotted(user_table.is_dotted());
merged.set_implicit(default_table.is_implicit() && user_table.is_implicit());
self.descend(user_key, user_table, |engine| {
engine.merge_table(default_table, user_table, &mut merged, Some(path));
});
Item::Table(merged)
}
(Item::ArrayOfTables(_), Item::ArrayOfTables(user_array)) => {
Item::ArrayOfTables(user_array.clone())
}
_ => unreachable!("equal TOML types have matching item shapes"),
}
};
let mut key = user_key.clone();
set_prefix(&mut key, &mut item, block.render(self.marker()));
out.insert_formatted(&key, item);
}
fn descend(&mut self, key: &Key, table: &Table, walk: impl FnOnce(&mut Self)) {
let dotted = table.is_dotted();
if dotted {
self.dotted.push(key.display_repr().into_owned());
}
walk(self);
if dotted {
self.dotted.pop();
}
}
fn flush_pending(&mut self, block: &mut DocBlock, first: bool) {
if self.pending.is_empty() {
return;
}
let mut waiting = std::mem::take(&mut self.pending);
if !first && self.pending_spaced {
waiting.insert(0, String::new());
}
if !self.options.commented || block.spaced {
waiting.push(String::new());
}
waiting.append(&mut block.floating);
block.floating = waiting;
}
fn block(&self, default_decor: &Decor, user_decor: &Decor) -> DocBlock {
let (floating, touching) = Prefix::of(default_decor).split(self.marker());
let mut block = DocBlock {
spaced: spaced(&floating),
..DocBlock::default()
};
block.keep_user_text(&Prefix::of(user_decor), self.marker());
block.take_docs(&touching);
block.floating = self.standing_text(&floating);
if block.leading_blanks.is_empty() && block.floating.is_empty() {
block.leading_blanks = leading_blanks(&floating);
}
block
}
fn standing_text(&self, floating: &[PrefixLine]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for run in standing_runs(floating, self.marker()) {
match run {
Standing::Blanks(lines) => out.extend(lines),
Standing::Block(lines) => {
let text: Vec<String> = lines
.iter()
.filter(|line| !matches!(line, PrefixLine::User { .. }))
.map(|line| line.text().to_owned())
.collect();
if self.template.read.contains(&text.join("\n")) {
while out.last().is_some_and(|line| line.trim().is_empty()) {
out.pop();
}
continue;
}
out.extend(text);
}
}
}
if out.iter().all(|line| line.trim().is_empty()) {
out.clear();
}
out
}
fn record_default(
&self,
block: &mut DocBlock,
default_key: &Key,
default_item: &Item,
user_value: Option<&Value>,
) {
let Item::Value(default_value) = default_item else {
return;
};
let default_text = rendered(default_value);
if let Some(user_value) = user_value
&& rendered(user_value) == default_text
{
return;
}
block.sample = Sample::Echo(DefaultEcho {
key: self.dotted_name(default_key),
value: default_text,
});
}
fn dotted_name(&self, key: &Key) -> String {
let mut name = String::new();
for segment in &self.dotted {
name.push_str(segment);
name.push('.');
}
name.push_str(&key.display_repr());
name
}
fn default_entry(
&mut self,
key: &Key,
item: &Item,
path: &DottedPath,
first: bool,
) -> (Key, Item) {
let prefix = Prefix::of(decor_of(key, item));
let (floating, touching) = prefix.split(self.marker());
let mut block = DocBlock {
leading_blanks: leading_blanks(&floating),
indent: prefix.indent().to_owned(),
spaced: spaced(&floating),
..DocBlock::default()
};
block.take_docs(&touching);
block.floating = self.standing_text(&floating);
self.flush_pending(&mut block, first);
let mut key = key.clone();
let mut item = self.docs_only(item, path);
set_prefix(&mut key, &mut item, block.render(self.marker()));
(key, item)
}
fn comment_default(&mut self, key: &Key, item: &Item, path: &DottedPath) {
let waiting = std::mem::take(&mut self.pending);
let commented = std::mem::replace(&mut self.options.commented, false);
let (key, item) = self.default_entry(key, item, path, true);
self.options.commented = commented;
let mut lines = comment_out(path, &key, &item, self.marker());
let inner = std::mem::take(&mut self.pending);
if !inner.is_empty() {
lines.push(String::new());
lines.extend(inner);
}
if waiting.is_empty() {
let text = lines
.iter()
.position(|line| !line.trim().is_empty())
.unwrap_or(lines.len());
self.pending_spaced = text > 0;
lines.drain(..text);
}
self.pending = waiting;
self.pending.extend(lines);
}
fn docs_only(&mut self, item: &Item, path: &DottedPath) -> Item {
match item {
Item::Table(table) => Item::Table(self.docs_only_table(table, path, true)),
Item::ArrayOfTables(array) => {
let mut out = ArrayOfTables::new();
for (index, entry) in array.iter().enumerate() {
out.push(self.docs_only_table(entry, path, index == 0));
}
Item::ArrayOfTables(out)
}
other => other.clone(),
}
}
fn docs_only_table(&mut self, table: &Table, path: &DottedPath, documented: bool) -> Table {
let mut out = Table::new();
out.set_dotted(table.is_dotted());
out.set_implicit(table.is_implicit());
if documented {
self.merge_table(table, &Table::new(), &mut out, Some(path));
return out;
}
for (name, item) in table.iter() {
let key = table.key(name).expect("a name iterated has a key");
let first = out.is_empty();
let (key, item) = self.default_entry(key, item, &path.child(name), first);
out.insert_formatted(&key, item);
}
out
}
fn keep_unknown(&self, key: &Key, item: &Item, path: &DottedPath) -> (Key, Item) {
let mut block = DocBlock::default();
block.keep_user_text(&Prefix::of(decor_of(key, item)), self.marker());
block.floating = Vec::new();
let mut key = key.clone();
let mut item = match item {
Item::Table(table) => Item::Table(self.keep_unknown_table(table, path)),
Item::ArrayOfTables(array) => {
let mut out = ArrayOfTables::new();
for entry in array.iter() {
out.push(self.keep_unknown_table(entry, path));
}
Item::ArrayOfTables(out)
}
other => other.clone(),
};
set_prefix(&mut key, &mut item, block.render(self.marker()));
(key, item)
}
fn keep_unknown_table(&self, table: &Table, path: &DottedPath) -> Table {
let mut out = Table::new();
out.set_dotted(table.is_dotted());
out.set_implicit(table.is_implicit());
*out.decor_mut() = table.decor().clone();
for (name, item) in table.iter() {
let key = table.key(name).expect("a name iterated has a key");
let (key, item) = self.keep_unknown(key, item, &path.child(name));
out.insert_formatted(&key, item);
}
out
}
fn merged_trailing(&mut self, keys: bool) -> String {
let waiting = std::mem::take(&mut self.pending);
let marker = self.marker();
let prefix = Prefix::from_text(self.defaults.trailing());
let (mut lines, touching) = prefix.split(marker);
lines.extend(touching);
let mut docs = self.standing_text(&lines);
let mut waiting = waiting;
let separated = waiting.is_empty() || self.pending_spaced;
if !waiting.is_empty() {
if !docs.is_empty() {
waiting.push(String::new());
}
waiting.append(&mut docs);
docs = waiting;
}
if separated {
let first = docs
.iter()
.position(|line| !line.trim().is_empty())
.unwrap_or(docs.len());
docs.drain(..first);
}
let user = Prefix::from_text(self.user.trailing());
let user_lines = user.lines(marker);
let first = user_lines
.iter()
.position(|line| !matches!(line, PrefixLine::Blank { .. }))
.unwrap_or(user_lines.len());
let mut mine: Vec<&str> = Vec::new();
for line in &user_lines[first..] {
if marker.owns(line.text()) {
continue;
}
let blank = line.text().trim().is_empty();
if blank && mine.last().is_none_or(|last| last.trim().is_empty()) {
continue;
}
mine.push(line.text());
}
while mine.last().is_some_and(|line| line.trim().is_empty()) {
mine.pop();
}
let content = docs.iter().any(|line| !line.trim().is_empty())
|| mine.iter().any(|line| !line.trim().is_empty());
if !content {
return String::new();
}
let mut out = String::from(if keys && separated { "\n" } else { "" });
for line in docs.iter().map(String::as_str).chain(mine) {
out.push_str(line);
out.push('\n');
}
out
}
}
pub(crate) fn blocks<'a>(lines: &'a [PrefixLine], marker: &Marker) -> Vec<&'a [PrefixLine]> {
standing_runs(lines, marker)
.into_iter()
.filter_map(|run| match run {
Standing::Block(lines) => Some(lines),
Standing::Blanks(_) => None,
})
.collect()
}
enum Standing<'a> {
Blanks(Vec<String>),
Block(&'a [PrefixLine]),
}
fn standing_runs<'a>(lines: &'a [PrefixLine], marker: &Marker) -> Vec<Standing<'a>> {
let blank = |line: &PrefixLine| matches!(line, PrefixLine::Blank { .. });
let mut out = Vec::new();
let mut at = 0;
while at < lines.len() {
let start = at;
if blank(&lines[at]) {
while at < lines.len() && blank(&lines[at]) {
at += 1;
}
out.push(Standing::Blanks(
lines[start..at]
.iter()
.map(|line| line.text().to_owned())
.collect(),
));
} else {
while at < lines.len() && !blank(&lines[at]) {
at += 1;
}
out.extend(
split_at_headers(&lines[start..at], marker)
.into_iter()
.map(Standing::Block),
);
}
}
out
}
fn split_at_headers<'a>(run: &'a [PrefixLine], marker: &Marker) -> Vec<&'a [PrefixLine]> {
let mut starts = vec![0usize];
for (at, line) in run.iter().enumerate().skip(1) {
if !opens_table(line, marker) {
continue;
}
let mut start = at;
while start > 0 && matches!(run[start - 1], PrefixLine::Prose { .. }) {
start -= 1;
}
if start > *starts.last().expect("starts is never empty") {
starts.push(start);
}
}
starts
.iter()
.enumerate()
.map(|(n, &start)| {
let end = starts.get(n + 1).copied().unwrap_or(run.len());
&run[start..end]
})
.collect()
}
fn opens_table(line: &PrefixLine, marker: &Marker) -> bool {
match line {
PrefixLine::Sample { text } => marker.undress(text).trim_start().starts_with('['),
_ => false,
}
}
fn opens_section(item: &Item) -> bool {
matches!(item, Item::Table(table) if !table.is_dotted())
}
fn spaced(floating: &[PrefixLine]) -> bool {
floating
.iter()
.any(|line| matches!(line, PrefixLine::Blank { .. }))
}
fn leading_blanks(floating: &[PrefixLine]) -> Vec<String> {
floating
.iter()
.take_while(|line| matches!(line, PrefixLine::Blank { .. }))
.map(|line| line.text().to_owned())
.collect()
}
fn child_path(path: Option<&DottedPath>, name: &str) -> DottedPath {
match path {
Some(path) => path.child(name),
None => DottedPath::new(name),
}
}
pub(crate) fn decor_of<'a>(key: &'a Key, item: &'a Item) -> &'a Decor {
match item {
Item::Table(table) if !table.is_dotted() => table.decor(),
Item::ArrayOfTables(array) => match array.get(0) {
Some(first) => first.decor(),
None => key.leaf_decor(),
},
_ => key.leaf_decor(),
}
}
fn set_prefix(key: &mut Key, item: &mut Item, prefix: String) {
match item {
Item::Table(table) if !table.is_dotted() => {
key.leaf_decor_mut().set_prefix("");
table.decor_mut().set_prefix(prefix);
}
Item::ArrayOfTables(array) => {
key.leaf_decor_mut().set_prefix("");
if let Some(first) = array.get_mut(0) {
first.decor_mut().set_prefix(prefix);
}
}
_ => {
key.leaf_decor_mut().set_prefix(prefix);
}
}
}
fn rendered(value: &Value) -> String {
let mut value = value.clone();
strip(&mut value);
value.to_string().trim().to_owned()
}
fn strip(value: &mut Value) {
match value {
Value::Array(array) => {
for element in array.iter_mut() {
strip(element);
}
array.set_trailing("");
array.set_trailing_comma(false);
}
Value::InlineTable(table) => {
for (mut key, element) in table.iter_mut() {
key.leaf_decor_mut().clear();
key.dotted_decor_mut().clear();
strip(element);
}
table.set_trailing("");
table.set_trailing_comma(false);
}
_ => {}
}
value.decor_mut().clear();
}
fn separated(raw: &str) -> bool {
let mut lines: Vec<&str> = raw.split('\n').collect();
lines.pop();
while lines.last().is_some_and(|line| !line.trim().is_empty()) {
lines.pop();
}
lines.last().is_some_and(|line| line.trim().is_empty())
}
fn space_sections(table: &mut Table, emitted: &mut bool, header: bool) {
let has_values = !table.get_values().is_empty();
if header {
if *emitted {
let prefix = Prefix::of(table.decor());
if !separated(&prefix.raw) {
table.decor_mut().set_prefix(format!("\n{}", prefix.raw));
}
}
*emitted = true;
}
*emitted |= has_values;
for (_, item) in table.iter_mut() {
match item {
Item::Table(sub) => {
let visible =
!sub.is_dotted() && (!sub.is_implicit() || !sub.get_values().is_empty());
space_sections(sub, emitted, visible);
}
Item::ArrayOfTables(array) => {
for entry in array.iter_mut() {
space_sections(entry, emitted, true);
}
}
_ => {}
}
}
}
fn renumber_tables(table: &mut Table, next: &mut isize) {
for (_, item) in table.iter_mut() {
match item {
Item::Table(sub) => {
if !sub.is_dotted() {
*next += 1;
sub.set_position(Some(*next));
}
renumber_tables(sub, next);
}
Item::ArrayOfTables(array) => {
for entry in array.iter_mut() {
*next += 1;
entry.set_position(Some(*next));
renumber_tables(entry, next);
}
}
_ => {}
}
}
}
fn lookup<'t>(root: &'t Table, path: &DottedPath) -> Option<&'t Item> {
let mut table = root;
let mut segments = path.segments().peekable();
while let Some(segment) = segments.next() {
let item = table.get(segment)?;
if segments.peek().is_none() {
return Some(item);
}
table = match item {
Item::Table(sub) => sub,
Item::ArrayOfTables(array) => array.get(0)?,
_ => return None,
};
}
None
}
fn take(root: &mut Table, path: &DottedPath) -> Option<(Key, Item)> {
let mut table = root;
let mut segments = path.segments().peekable();
while let Some(segment) = segments.next() {
if segments.peek().is_none() {
return table.remove_entry(segment);
}
table = table.get_mut(segment)?.as_table_mut()?;
}
None
}
fn assign(root: &mut Table, path: &DottedPath, value: Value) -> bool {
let mut table = root;
let mut segments = path.segments().peekable();
while let Some(segment) = segments.next() {
if segments.peek().is_none() {
return match table.get_mut(segment) {
Some(item) if matches!(item, Item::Value(_) | Item::None) => {
*item = Item::Value(value);
true
}
Some(_) => false,
None => {
table.insert(segment, Item::Value(value));
true
}
};
}
let entry = table.entry(segment).or_insert_with(|| {
let mut created = Table::new();
created.set_implicit(true);
Item::Table(created)
});
match entry.as_table_mut() {
Some(sub) => table = sub,
None => return false,
}
}
false
}
fn place(root: &mut Table, path: &DottedPath, key: Key, item: Item) -> bool {
let mut table = root;
let mut segments = path.segments().peekable();
while let Some(segment) = segments.next() {
if segments.peek().is_none() {
table.insert_formatted(&key, item);
return true;
}
let entry = table.entry(segment).or_insert_with(|| {
let mut created = Table::new();
created.set_implicit(true);
Item::Table(created)
});
match entry.as_table_mut() {
Some(sub) => table = sub,
None => return false,
}
}
false
}