From a9f1a44bf9a2f837ceb817e86818535f1201b218 Mon Sep 17 00:00:00 2001 From: Ed Page Date: Mon, 23 Oct 2023 08:58:15 -0500 Subject: [PATCH] feat(edit): Allow sorting Arrays --- crates/toml_edit/src/array.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/toml_edit/src/array.rs b/crates/toml_edit/src/array.rs index 045b451e..bd9ac514 100644 --- a/crates/toml_edit/src/array.rs +++ b/crates/toml_edit/src/array.rs @@ -317,6 +317,26 @@ impl Array { .retain(|item| item.as_value().map(&mut keep).unwrap_or(false)); } + /// Sorts the array with a key extraction function. + /// + /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*)) + /// worst-case, where the key function is *O*(*m*). + #[inline] + pub fn sort_by_key(&mut self, mut f: F) + where + F: FnMut(&Value) -> K, + K: Ord, + { + #[allow(clippy::manual_map)] // needed for lifetimes + self.values.sort_by_key(move |item| { + if let Some(value) = item.as_value() { + Some(f(value)) + } else { + None + } + }); + } + fn value_op( &mut self, v: Value,