Skip to content

Commit 309ef6b

Browse files
committed
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.
1 parent a9e089a commit 309ef6b

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/map.rs

+11
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,17 @@ impl Map<String, Value> {
127127
self.map.insert(k, v)
128128
}
129129

130+
/// Insert a key-value pair in the map at the given index.
131+
///
132+
/// If the map did not have this key present, `None` is returned.
133+
///
134+
/// If the map did have this key present, the key is moved to the new
135+
/// position, the value is updated, and the old value is returned.
136+
#[cfg(feature = "preserve_order")]
137+
pub fn shift_insert(&mut self, index: usize, k: String, v: Value) -> Option<Value> {
138+
self.map.shift_insert(index, k, v)
139+
}
140+
130141
/// Removes a key from the map, returning the value at the key if the key
131142
/// was previously in the map.
132143
///

tests/map.rs

+11
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ fn test_preserve_order() {
1515
assert_eq!(keys, EXPECTED);
1616
}
1717

18+
#[test]
19+
#[cfg(feature = "preserve_order")]
20+
fn test_shift_insert() {
21+
let mut v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap();
22+
let val = v.as_object_mut().unwrap();
23+
val.shift_insert(0, "d".to_string(), Value::Null);
24+
25+
let keys: Vec<_> = val.keys().collect();
26+
assert_eq!(keys, &["d", "b", "a", "c"]);
27+
}
28+
1829
#[test]
1930
fn test_append() {
2031
// Sorted order

0 commit comments

Comments
 (0)