Skip to content

Commit

Permalink
Add Map::shift_insert()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
joshka committed Jun 30, 2024
1 parent a9e089a commit 309ef6b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,17 @@ impl Map<String, Value> {
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<Value> {
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.
///
Expand Down
11 changes: 11 additions & 0 deletions tests/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 309ef6b

Please sign in to comment.