Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2391,8 +2391,9 @@ impl<'a, T, S, A: Allocator> Entry<'a, T, S, A> {
}
}

impl<T, S, A: Allocator> OccupiedEntry<'_, T, S, A> {
/// Gets a reference to the value in the entry.
impl<'a, T, S, A: Allocator> OccupiedEntry<'a, T, S, A> {
/// Gets a reference to the value in the entry. For a reference that persists beyond the
/// lifetime of the entry, see [`into_ref`](Self::into_ref).
///
/// # Examples
///
Expand All @@ -2412,6 +2413,34 @@ impl<T, S, A: Allocator> OccupiedEntry<'_, T, S, A> {
self.inner.key()
}

/// Consumes the entry, returning a reference to the value in the [`HashSet`]. By contrast
/// with [`get`](Self::get), the reference inherits the lifetime of the parent set, so
/// will persist beyond the lifetime of the entry.
///
/// # Examples
///
/// ```
/// use hashbrown::hash_set::{Entry, HashSet};
///
/// let mut set: HashSet<&str> = HashSet::new();
/// let value = set.entry("poneyland").insert().into_ref();
///
/// assert_eq!(&"poneyland", value);
/// ```
///
/// `get` used in the same context will fail to compile:
///
/// ```compile_fail
/// # use hashbrown::hash_set::{Entry, HashSet};
/// # let mut set: HashSet<&str> = HashSet::new();
/// let value = set.entry("poneyland").insert().get();
/// assert_eq!(&"poneyland", value);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_ref(self) -> &'a T {
self.inner.into_entry().0
}

/// Takes the value out of the entry, and returns it.
/// Keeps the allocated memory for reuse.
///
Expand Down Expand Up @@ -2545,6 +2574,7 @@ fn assert_covariance() {

#[cfg(test)]
mod test_set {
use super::Entry::{Occupied, Vacant};
use super::{Equivalent, HashSet};
use crate::DefaultHashBuilder;
use crate::map::make_hash;
Expand Down Expand Up @@ -3086,4 +3116,42 @@ mod test_set {
set.get_or_insert_with(&key, |_| value);
}
}

#[test]
fn test_entry() {
let xs = [10, 20, 30, 40, 50, 60];

let mut set: HashSet<_> = xs.iter().copied().collect();

// Existing key (get)
assert_eq!(
&10,
match set.entry(10) {
Vacant(_) => unreachable!(),
Occupied(view) => {
assert_eq!(&10, view.get());
view.into_ref()
}
}
);

// Existing key (remove)
assert_eq!(
20,
match set.entry(20) {
Vacant(_) => unreachable!(),
Occupied(view) => view.remove(),
}
);

// Non-existant key (insert)
match set.entry(1000) {
Occupied(_) => unreachable!(),
Vacant(view) => {
assert_eq!(&1000, view.insert().get());
}
}
assert_eq!(set.get(&1000), Some(&1000));
assert_eq!(set.len(), 6);
}
}
Loading