Skip to content

Commit 0ceb9d8

Browse files
authored
Add OccupiedEntry::remove_entry() (and shift/swap versions)
1 parent 50c4328 commit 0ceb9d8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/map.rs

+63
Original file line numberDiff line numberDiff line change
@@ -900,6 +900,69 @@ impl<'a> OccupiedEntry<'a> {
900900
#[cfg(not(feature = "preserve_order"))]
901901
return self.occupied.remove();
902902
}
903+
904+
/// Removes the entry from the map, returning the stored key and value.
905+
///
906+
/// If serde_json's "preserve_order" is enabled, `.remove_entry()` is
907+
/// equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry],
908+
/// replacing this entry's position with the last element. If you need to
909+
/// preserve the relative order of the keys in the map, use
910+
/// [`.shift_remove_entry()`][Self::shift_remove_entry] instead.
911+
///
912+
/// # Examples
913+
///
914+
/// ```
915+
/// # use serde_json::json;
916+
/// #
917+
/// use serde_json::map::Entry;
918+
///
919+
/// let mut map = serde_json::Map::new();
920+
/// map.insert("serde".to_owned(), json!(12));
921+
///
922+
/// match map.entry("serde") {
923+
/// Entry::Occupied(occupied) => {
924+
/// let (key, value) = occupied.remove_entry();
925+
/// assert_eq!(key, "serde");
926+
/// assert_eq!(value, 12);
927+
/// }
928+
/// Entry::Vacant(_) => unimplemented!(),
929+
/// }
930+
/// ```
931+
#[inline]
932+
pub fn remove_entry(self) -> (String, Value) {
933+
#[cfg(feature = "preserve_order")]
934+
return self.swap_remove_entry();
935+
#[cfg(not(feature = "preserve_order"))]
936+
return self.occupied.remove_entry();
937+
}
938+
939+
/// Removes the entry from the map, returning the stored key and value.
940+
///
941+
/// Like [`Vec::swap_remove`], the entry is removed by swapping it with the
942+
/// last element of the map and popping it off. This perturbs the position
943+
/// of what used to be the last element!
944+
///
945+
/// [`Vec::swap_remove`]: std::vec::Vec::swap_remove
946+
#[cfg(feature = "preserve_order")]
947+
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
948+
#[inline]
949+
pub fn swap_remove_entry(self) -> (String, Value) {
950+
self.occupied.swap_remove_entry()
951+
}
952+
953+
/// Removes the entry from the map, returning the stored key and value.
954+
///
955+
/// Like [`Vec::remove`], the entry is removed by shifting all of the
956+
/// elements that follow it, preserving their relative order. This perturbs
957+
/// the index of all of those elements!
958+
///
959+
/// [`Vec::remove`]: std::vec::Vec::remove
960+
#[cfg(feature = "preserve_order")]
961+
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
962+
#[inline]
963+
pub fn shift_remove_entry(self) -> (String, Value) {
964+
self.occupied.shift_remove_entry()
965+
}
903966
}
904967

905968
//////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)