Skip to content

Commit

Permalink
Add OccupiedEntry::shift_remove() and swap_remove()
Browse files Browse the repository at this point in the history
  • Loading branch information
GREsau authored Aug 19, 2024
1 parent 0ceb9d8 commit 11fc61c
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,12 @@ impl<'a> OccupiedEntry<'a> {

/// Takes the value of the entry out of the map, and returns it.
///
/// If serde_json's "preserve_order" is enabled, `.remove()` is
/// equivalent to [`.swap_remove()`][Self::swap_remove], replacing this
/// entry's position with the last element. If you need to preserve the
/// relative order of the keys in the map, use
/// [`.shift_remove()`][Self::shift_remove] instead.
///
/// # Examples
///
/// ```
Expand All @@ -896,11 +902,39 @@ impl<'a> OccupiedEntry<'a> {
#[inline]
pub fn remove(self) -> Value {
#[cfg(feature = "preserve_order")]
return self.occupied.swap_remove();
return self.swap_remove();
#[cfg(not(feature = "preserve_order"))]
return self.occupied.remove();
}

/// Takes the value of the entry out of the map, and returns it.
///
/// Like [`Vec::remove`], the entry is removed by shifting all of the
/// elements that follow it, preserving their relative order. This perturbs
/// the index of all of those elements!
///
/// [`Vec::remove`]: std::vec::Vec::remove
#[cfg(feature = "preserve_order")]
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
#[inline]
pub fn shift_remove(self) -> Value {
self.occupied.shift_remove()
}

/// Takes the value of the entry out of the map, and returns it.
///
/// Like [`Vec::swap_remove`], the entry is removed by swapping it with the
/// last element of the map and popping it off. This perturbs the position
/// of what used to be the last element!
///
/// [`Vec::swap_remove`]: std::vec::Vec::swap_remove
#[cfg(feature = "preserve_order")]
#[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
#[inline]
pub fn swap_remove(self) -> Value {
self.occupied.swap_remove()
}

/// Removes the entry from the map, returning the stored key and value.
///
/// If serde_json's "preserve_order" is enabled, `.remove_entry()` is
Expand Down

0 comments on commit 11fc61c

Please sign in to comment.