Skip to content

Commit

Permalink
fix: position=None keys broke key order when inserted into the table …
Browse files Browse the repository at this point in the history
…without sort_by_key
  • Loading branch information
mxndtaylor committed Nov 10, 2024
1 parent 07f82d2 commit d72ad7f
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions crates/toml_edit/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,14 +519,21 @@ fn decorate_table(table: &mut Table) {
}
}

/// sort_by_key works because we add the position to _every_ item's key during parsing,

Check failure

Code scanning / clippy

item in documentation is missing backticks Error

item in documentation is missing backticks

Check failure

Code scanning / clippy

item in documentation is missing backticks Error

item in documentation is missing backticks
/// so keys without positions would be either:
/// 1. non-leaf keys (i.e. "foo" or "bar" in dotted key "foo.bar.baz")
/// 2. custom keys added to the doc without an explicit position
/// and in the case of (1), we'd never see it since we only look at the last

Check failure

Code scanning / clippy

doc list item without indentation Error

doc list item without indentation

Check failure

Code scanning / clippy

doc list item without indentation Error

doc list item without indentation
/// key in a dotted-key. So, we can safely return a constant value for these cases.

Check failure

Code scanning / clippy

doc list item without indentation Error

doc list item without indentation

Check failure

Code scanning / clippy

doc list item without indentation Error

doc list item without indentation
///
/// To support the most intuitive behavior, we return the maximum usize, placing
/// position=None items at the end, so when you insert it without position, it
/// appends it to the end.
pub(crate) fn sort_values_by_position<'s>(values: &mut [(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
values.sort_by_key(|(left_kp, _)| {
return match left_kp.last().map(|x| x.position) {
Some(Some(pos)) => pos,
_ => usize::MAX
}
});
}
Expand Down

0 comments on commit d72ad7f

Please sign in to comment.