From 309ef6b8870e47622a283061cbda3f5514bfaf0d Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Sun, 30 Jun 2024 09:53:11 -0700 Subject: [PATCH] Add Map::shift_insert() This method inserts a key-value pair in the map at the given index. If the map did not have this key present, `None` is returned. If the map did have this key present, the key is moved to the new position, the value is updated, and the old value is returned. This is useful when you want to insert a key-value pair at a specific position in the map, and is a necessary method when writing a JSON editor that can mutate the keys in a JSON object. --- src/map.rs | 11 +++++++++++ tests/map.rs | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/map.rs b/src/map.rs index d62513daf..505be0eae 100644 --- a/src/map.rs +++ b/src/map.rs @@ -127,6 +127,17 @@ impl Map { self.map.insert(k, v) } + /// Insert a key-value pair in the map at the given index. + /// + /// If the map did not have this key present, `None` is returned. + /// + /// If the map did have this key present, the key is moved to the new + /// position, the value is updated, and the old value is returned. + #[cfg(feature = "preserve_order")] + pub fn shift_insert(&mut self, index: usize, k: String, v: Value) -> Option { + self.map.shift_insert(index, k, v) + } + /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. /// diff --git a/tests/map.rs b/tests/map.rs index 538cd16ae..c3c64d70b 100644 --- a/tests/map.rs +++ b/tests/map.rs @@ -15,6 +15,17 @@ fn test_preserve_order() { assert_eq!(keys, EXPECTED); } +#[test] +#[cfg(feature = "preserve_order")] +fn test_shift_insert() { + let mut v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap(); + let val = v.as_object_mut().unwrap(); + val.shift_insert(0, "d".to_string(), Value::Null); + + let keys: Vec<_> = val.keys().collect(); + assert_eq!(keys, &["d", "b", "a", "c"]); +} + #[test] fn test_append() { // Sorted order