From b2378f29415ebfbb204812228ed7479071ff6ea9 Mon Sep 17 00:00:00 2001 From: mxt Date: Sat, 9 Nov 2024 17:23:28 -0600 Subject: [PATCH] fix: Preserve dotted-key ordering Fixes #163 --- crates/toml_edit/src/inline_table.rs | 3 ++- crates/toml_edit/src/table.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/toml_edit/src/inline_table.rs b/crates/toml_edit/src/inline_table.rs index 9b8e9c42..ccf77212 100644 --- a/crates/toml_edit/src/inline_table.rs +++ b/crates/toml_edit/src/inline_table.rs @@ -2,7 +2,7 @@ use std::iter::FromIterator; use crate::key::Key; use crate::repr::Decor; -use crate::table::{Iter, IterMut, KeyValuePairs, TableLike}; +use crate::table::{Iter, IterMut, KeyValuePairs, TableLike, sort_values_by_position}; use crate::{InternalString, Item, KeyMut, RawString, Table, Value}; /// Type representing a TOML inline table, @@ -75,6 +75,7 @@ impl InlineTable { _ => {} } } + sort_values_by_position(values); } /// Auto formats the table. diff --git a/crates/toml_edit/src/table.rs b/crates/toml_edit/src/table.rs index 1ae02310..0d0c5b73 100644 --- a/crates/toml_edit/src/table.rs +++ b/crates/toml_edit/src/table.rs @@ -96,6 +96,7 @@ impl Table { _ => {} } } + sort_values_by_position(values); } /// Auto formats the table. @@ -518,6 +519,18 @@ fn decorate_table(table: &mut Table) { } } +pub(crate) fn sort_values_by_position<'s>(values: &mut Vec<(Vec<&'s Key>, &'s Value)>) { + values.sort_by(|(left_kp, _), (right_kp, _)| { + return match (left_kp.last().map(|x| x.position), + right_kp.last().map(|x| x.position)) { + // first if both have Some() position, its easy + (Some(Some(p1)), Some(Some(p2))) => p1.cmp(&p2), + // if one or more do not, preserve order + _ => std::cmp::Ordering::Equal + } + }); +} + // `key1 = value1` pub(crate) const DEFAULT_ROOT_DECOR: (&str, &str) = ("", ""); pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");