Skip to content

Commit 11fc61c

Browse files
authored
Add OccupiedEntry::shift_remove() and swap_remove()
1 parent 0ceb9d8 commit 11fc61c

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/map.rs

+35-1
Original file line numberDiff line numberDiff line change
@@ -876,6 +876,12 @@ impl<'a> OccupiedEntry<'a> {
876876

877877
/// Takes the value of the entry out of the map, and returns it.
878878
///
879+
/// If serde_json's "preserve_order" is enabled, `.remove()` is
880+
/// equivalent to [`.swap_remove()`][Self::swap_remove], replacing this
881+
/// entry's position with the last element. If you need to preserve the
882+
/// relative order of the keys in the map, use
883+
/// [`.shift_remove()`][Self::shift_remove] instead.
884+
///
879885
/// # Examples
880886
///
881887
/// ```
@@ -896,11 +902,39 @@ impl<'a> OccupiedEntry<'a> {
896902
#[inline]
897903
pub fn remove(self) -> Value {
898904
#[cfg(feature = "preserve_order")]
899-
return self.occupied.swap_remove();
905+
return self.swap_remove();
900906
#[cfg(not(feature = "preserve_order"))]
901907
return self.occupied.remove();
902908
}
903909

910+
/// Takes the value of the entry out of the map, and returns it.
911+
///
912+
/// Like [`Vec::remove`], the entry is removed by shifting all of the
913+
/// elements that follow it, preserving their relative order. This perturbs
914+
/// the index of all of those elements!
915+
///
916+
/// [`Vec::remove`]: std::vec::Vec::remove
917+
#[cfg(feature = "preserve_order")]
918+
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
919+
#[inline]
920+
pub fn shift_remove(self) -> Value {
921+
self.occupied.shift_remove()
922+
}
923+
924+
/// Takes the value of the entry out of the map, and returns it.
925+
///
926+
/// Like [`Vec::swap_remove`], the entry is removed by swapping it with the
927+
/// last element of the map and popping it off. This perturbs the position
928+
/// of what used to be the last element!
929+
///
930+
/// [`Vec::swap_remove`]: std::vec::Vec::swap_remove
931+
#[cfg(feature = "preserve_order")]
932+
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
933+
#[inline]
934+
pub fn swap_remove(self) -> Value {
935+
self.occupied.swap_remove()
936+
}
937+
904938
/// Removes the entry from the map, returning the stored key and value.
905939
///
906940
/// If serde_json's "preserve_order" is enabled, `.remove_entry()` is

0 commit comments

Comments
 (0)