Skip to content

Commit c17e63f

Browse files
authored
Merge pull request #1149 from joshka/master
Add Map::shift_insert()
2 parents a9e089a + 309ef6b commit c17e63f

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/map.rs

Lines changed: 11 additions & 0 deletions
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

Lines changed: 11 additions & 0 deletions
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)