#[cfg(feature = "raw")]
use crate::raw::RawTable;
use crate::{Equivalent, TryReserveError};
use alloc::borrow::ToOwned;
use core::fmt;
use core::hash::{BuildHasher, Hash};
use core::iter::{Chain, FusedIterator};
use core::ops::{BitAnd, BitOr, BitXor, Sub};
use super::map::{self, DefaultHashBuilder, HashMap, Keys};
use crate::raw::{Allocator, Global, RawExtractIf};
pub struct HashSet<T, S = DefaultHashBuilder, A: Allocator = Global> {
pub(crate) map: HashMap<T, (), S, A>,
}
impl<T: Clone, S: Clone, A: Allocator + Clone> Clone for HashSet<T, S, A> {
fn clone(&self) -> Self {
HashSet {
map: self.map.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.map.clone_from(&source.map);
}
}
#[cfg(feature = "ahash")]
impl<T> HashSet<T, DefaultHashBuilder> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity(capacity: usize) -> Self {
Self {
map: HashMap::with_capacity(capacity),
}
}
}
#[cfg(feature = "ahash")]
impl<T: Hash + Eq, A: Allocator> HashSet<T, DefaultHashBuilder, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn new_in(alloc: A) -> Self {
Self {
map: HashMap::new_in(alloc),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
Self {
map: HashMap::with_capacity_in(capacity, alloc),
}
}
}
impl<T, S, A: Allocator> HashSet<T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn capacity(&self) -> usize {
self.map.capacity()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<'_, T> {
Iter {
iter: self.map.keys(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn len(&self) -> usize {
self.map.len()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn drain(&mut self) -> Drain<'_, T, A> {
Drain {
iter: self.map.drain(),
}
}
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&T) -> bool,
{
self.map.retain(|k, _| f(k));
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, T, F, A>
where
F: FnMut(&T) -> bool,
{
ExtractIf {
f,
inner: RawExtractIf {
iter: unsafe { self.map.table.iter() },
table: &mut self.map.table,
},
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn clear(&mut self) {
self.map.clear();
}
}
impl<T, S> HashSet<T, S, Global> {
#[cfg_attr(feature = "inline-more", inline)]
pub const fn with_hasher(hasher: S) -> Self {
Self {
map: HashMap::with_hasher(hasher),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
Self {
map: HashMap::with_capacity_and_hasher(capacity, hasher),
}
}
}
impl<T, S, A> HashSet<T, S, A>
where
A: Allocator,
{
#[inline]
pub fn allocator(&self) -> &A {
self.map.allocator()
}
#[cfg_attr(feature = "inline-more", inline)]
pub const fn with_hasher_in(hasher: S, alloc: A) -> Self {
Self {
map: HashMap::with_hasher_in(hasher, alloc),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> Self {
Self {
map: HashMap::with_capacity_and_hasher_in(capacity, hasher, alloc),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn hasher(&self) -> &S {
self.map.hasher()
}
}
impl<T, S, A> HashSet<T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
#[cfg_attr(feature = "inline-more", inline)]
pub fn reserve(&mut self, additional: usize) {
self.map.reserve(additional);
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.map.try_reserve(additional)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to_fit(&mut self) {
self.map.shrink_to_fit();
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.map.shrink_to(min_capacity);
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T, S, A> {
Difference {
iter: self.iter(),
other,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T, S, A> {
SymmetricDifference {
iter: self.difference(other).chain(other.difference(self)),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T, S, A> {
let (smaller, larger) = if self.len() <= other.len() {
(self, other)
} else {
(other, self)
};
Intersection {
iter: smaller.iter(),
other: larger,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T, S, A> {
let (smaller, larger) = if self.len() <= other.len() {
(self, other)
} else {
(other, self)
};
Union {
iter: larger.iter().chain(smaller.difference(larger)),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where
Q: Hash + Equivalent<T>,
{
self.map.contains_key(value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
where
Q: Hash + Equivalent<T>,
{
match self.map.get_key_value(value) {
Some((k, _)) => Some(k),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_or_insert(&mut self, value: T) -> &T {
self.map
.raw_entry_mut()
.from_key(&value)
.or_insert(value, ())
.0
}
#[inline]
pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
where
Q: Hash + Equivalent<T> + ToOwned<Owned = T>,
{
self.map
.raw_entry_mut()
.from_key(value)
.or_insert_with(|| (value.to_owned(), ()))
.0
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
where
Q: Hash + Equivalent<T>,
F: FnOnce(&Q) -> T,
{
self.map
.raw_entry_mut()
.from_key(value)
.or_insert_with(|| (f(value), ()))
.0
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry(&mut self, value: T) -> Entry<'_, T, S, A> {
match self.map.entry(value) {
map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { inner: entry }),
map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { inner: entry }),
}
}
pub fn is_disjoint(&self, other: &Self) -> bool {
self.iter().all(|v| !other.contains(v))
}
pub fn is_subset(&self, other: &Self) -> bool {
self.len() <= other.len() && self.iter().all(|v| other.contains(v))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn is_superset(&self, other: &Self) -> bool {
other.is_subset(self)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, value: T) -> bool {
self.map.insert(value, ()).is_none()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked(&mut self, value: T) -> &T {
self.map.insert_unique_unchecked(value, ()).0
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace(&mut self, value: T) -> Option<T> {
match self.map.entry(value) {
map::Entry::Occupied(occupied) => Some(occupied.replace_key()),
map::Entry::Vacant(vacant) => {
vacant.insert(());
None
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
where
Q: Hash + Equivalent<T>,
{
self.map.remove(value).is_some()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
where
Q: Hash + Equivalent<T>,
{
match self.map.remove_entry(value) {
Some((k, _)) => Some(k),
None => None,
}
}
}
impl<T, S, A: Allocator> HashSet<T, S, A> {
#[cfg(feature = "raw")]
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_table(&self) -> &RawTable<(T, ()), A> {
self.map.raw_table()
}
#[cfg(feature = "raw")]
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_table_mut(&mut self) -> &mut RawTable<(T, ()), A> {
self.map.raw_table_mut()
}
}
impl<T, S, A> PartialEq for HashSet<T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().all(|key| other.contains(key))
}
}
impl<T, S, A> Eq for HashSet<T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
}
impl<T, S, A> fmt::Debug for HashSet<T, S, A>
where
T: fmt::Debug,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<T, S, A> From<HashMap<T, (), S, A>> for HashSet<T, S, A>
where
A: Allocator,
{
fn from(map: HashMap<T, (), S, A>) -> Self {
Self { map }
}
}
impl<T, S, A> FromIterator<T> for HashSet<T, S, A>
where
T: Eq + Hash,
S: BuildHasher + Default,
A: Default + Allocator,
{
#[cfg_attr(feature = "inline-more", inline)]
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut set = Self::with_hasher_in(Default::default(), Default::default());
set.extend(iter);
set
}
}
#[cfg(feature = "ahash")]
impl<T, A, const N: usize> From<[T; N]> for HashSet<T, DefaultHashBuilder, A>
where
T: Eq + Hash,
A: Default + Allocator,
{
fn from(arr: [T; N]) -> Self {
arr.into_iter().collect()
}
}
impl<T, S, A> Extend<T> for HashSet<T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
#[cfg_attr(feature = "inline-more", inline)]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.map.extend(iter.into_iter().map(|k| (k, ())));
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_one(&mut self, k: T) {
self.map.insert(k, ());
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_reserve(&mut self, additional: usize) {
Extend::<(T, ())>::extend_reserve(&mut self.map, additional);
}
}
impl<'a, T, S, A> Extend<&'a T> for HashSet<T, S, A>
where
T: 'a + Eq + Hash + Copy,
S: BuildHasher,
A: Allocator,
{
#[cfg_attr(feature = "inline-more", inline)]
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().copied());
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_one(&mut self, k: &'a T) {
self.map.insert(*k, ());
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_reserve(&mut self, additional: usize) {
Extend::<(T, ())>::extend_reserve(&mut self.map, additional);
}
}
impl<T, S, A> Default for HashSet<T, S, A>
where
S: Default,
A: Default + Allocator,
{
#[cfg_attr(feature = "inline-more", inline)]
fn default() -> Self {
Self {
map: HashMap::default(),
}
}
}
impl<T, S, A> BitOr<&HashSet<T, S, A>> for &HashSet<T, S, A>
where
T: Eq + Hash + Clone,
S: BuildHasher + Default,
A: Allocator,
{
type Output = HashSet<T, S>;
fn bitor(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S> {
self.union(rhs).cloned().collect()
}
}
impl<T, S, A> BitAnd<&HashSet<T, S, A>> for &HashSet<T, S, A>
where
T: Eq + Hash + Clone,
S: BuildHasher + Default,
A: Allocator,
{
type Output = HashSet<T, S>;
fn bitand(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S> {
self.intersection(rhs).cloned().collect()
}
}
impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
where
T: Eq + Hash + Clone,
S: BuildHasher + Default,
{
type Output = HashSet<T, S>;
fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.symmetric_difference(rhs).cloned().collect()
}
}
impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
where
T: Eq + Hash + Clone,
S: BuildHasher + Default,
{
type Output = HashSet<T, S>;
fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.difference(rhs).cloned().collect()
}
}
pub struct Iter<'a, K> {
iter: Keys<'a, K, ()>,
}
pub struct IntoIter<K, A: Allocator = Global> {
iter: map::IntoIter<K, (), A>,
}
pub struct Drain<'a, K, A: Allocator = Global> {
iter: map::Drain<'a, K, (), A>,
}
#[must_use = "Iterators are lazy unless consumed"]
pub struct ExtractIf<'a, K, F, A: Allocator = Global>
where
F: FnMut(&K) -> bool,
{
f: F,
inner: RawExtractIf<'a, (K, ()), A>,
}
pub struct Intersection<'a, T, S, A: Allocator = Global> {
iter: Iter<'a, T>,
other: &'a HashSet<T, S, A>,
}
pub struct Difference<'a, T, S, A: Allocator = Global> {
iter: Iter<'a, T>,
other: &'a HashSet<T, S, A>,
}
pub struct SymmetricDifference<'a, T, S, A: Allocator = Global> {
iter: Chain<Difference<'a, T, S, A>, Difference<'a, T, S, A>>,
}
pub struct Union<'a, T, S, A: Allocator = Global> {
iter: Chain<Iter<'a, T>, Difference<'a, T, S, A>>,
}
impl<'a, T, S, A: Allocator> IntoIterator for &'a HashSet<T, S, A> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<T, S, A: Allocator> IntoIterator for HashSet<T, S, A> {
type Item = T;
type IntoIter = IntoIter<T, A>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> IntoIter<T, A> {
IntoIter {
iter: self.map.into_iter(),
}
}
}
impl<K> Clone for Iter<'_, K> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Iter {
iter: self.iter.clone(),
}
}
}
impl<'a, K> Iterator for Iter<'a, K> {
type Item = &'a K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a K> {
self.iter.next()
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, f)
}
}
impl<'a, K> ExactSizeIterator for Iter<'a, K> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.iter.len()
}
}
impl<K> FusedIterator for Iter<'_, K> {}
impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<K, A: Allocator> Iterator for IntoIter<K, A> {
type Item = K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<K> {
match self.iter.next() {
Some((k, _)) => Some(k),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, |acc, (k, ())| f(acc, k))
}
}
impl<K, A: Allocator> ExactSizeIterator for IntoIter<K, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.iter.len()
}
}
impl<K, A: Allocator> FusedIterator for IntoIter<K, A> {}
impl<K: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<K, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let entries_iter = self.iter.iter().map(|(k, _)| k);
f.debug_list().entries(entries_iter).finish()
}
}
impl<K, A: Allocator> Iterator for Drain<'_, K, A> {
type Item = K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<K> {
match self.iter.next() {
Some((k, _)) => Some(k),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, |acc, (k, ())| f(acc, k))
}
}
impl<K, A: Allocator> ExactSizeIterator for Drain<'_, K, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.iter.len()
}
}
impl<K, A: Allocator> FusedIterator for Drain<'_, K, A> {}
impl<K: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, K, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let entries_iter = self.iter.iter().map(|(k, _)| k);
f.debug_list().entries(entries_iter).finish()
}
}
impl<K, F, A: Allocator> Iterator for ExtractIf<'_, K, F, A>
where
F: FnMut(&K) -> bool,
{
type Item = K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next(|&mut (ref k, ())| (self.f)(k))
.map(|(k, ())| k)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.inner.iter.size_hint().1)
}
}
impl<K, F, A: Allocator> FusedIterator for ExtractIf<'_, K, F, A> where F: FnMut(&K) -> bool {}
impl<T, S, A: Allocator> Clone for Intersection<'_, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Intersection {
iter: self.iter.clone(),
..*self
}
}
}
impl<'a, T, S, A> Iterator for Intersection<'a, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
type Item = &'a T;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a T> {
loop {
let elt = self.iter.next()?;
if self.other.contains(elt) {
return Some(elt);
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper)
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, |acc, elt| {
if self.other.contains(elt) {
f(acc, elt)
} else {
acc
}
})
}
}
impl<T, S, A> fmt::Debug for Intersection<'_, T, S, A>
where
T: fmt::Debug + Eq + Hash,
S: BuildHasher,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<T, S, A> FusedIterator for Intersection<'_, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
}
impl<T, S, A: Allocator> Clone for Difference<'_, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Difference {
iter: self.iter.clone(),
..*self
}
}
}
impl<'a, T, S, A> Iterator for Difference<'a, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
type Item = &'a T;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a T> {
loop {
let elt = self.iter.next()?;
if !self.other.contains(elt) {
return Some(elt);
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper)
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, |acc, elt| {
if self.other.contains(elt) {
acc
} else {
f(acc, elt)
}
})
}
}
impl<T, S, A> FusedIterator for Difference<'_, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
}
impl<T, S, A> fmt::Debug for Difference<'_, T, S, A>
where
T: fmt::Debug + Eq + Hash,
S: BuildHasher,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<T, S, A: Allocator> Clone for SymmetricDifference<'_, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
SymmetricDifference {
iter: self.iter.clone(),
}
}
}
impl<'a, T, S, A> Iterator for SymmetricDifference<'a, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
type Item = &'a T;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a T> {
self.iter.next()
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, f)
}
}
impl<T, S, A> FusedIterator for SymmetricDifference<'_, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
}
impl<T, S, A> fmt::Debug for SymmetricDifference<'_, T, S, A>
where
T: fmt::Debug + Eq + Hash,
S: BuildHasher,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<T, S, A: Allocator> Clone for Union<'_, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Union {
iter: self.iter.clone(),
}
}
}
impl<T, S, A> FusedIterator for Union<'_, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
}
impl<T, S, A> fmt::Debug for Union<'_, T, S, A>
where
T: fmt::Debug + Eq + Hash,
S: BuildHasher,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<'a, T, S, A> Iterator for Union<'a, T, S, A>
where
T: Eq + Hash,
S: BuildHasher,
A: Allocator,
{
type Item = &'a T;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a T> {
self.iter.next()
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.iter.fold(init, f)
}
}
pub enum Entry<'a, T, S, A = Global>
where
A: Allocator,
{
Occupied(OccupiedEntry<'a, T, S, A>),
Vacant(VacantEntry<'a, T, S, A>),
}
impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for Entry<'_, T, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
}
}
}
pub struct OccupiedEntry<'a, T, S, A: Allocator = Global> {
inner: map::OccupiedEntry<'a, T, (), S, A>,
}
impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for OccupiedEntry<'_, T, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntry")
.field("value", self.get())
.finish()
}
}
pub struct VacantEntry<'a, T, S, A: Allocator = Global> {
inner: map::VacantEntry<'a, T, (), S, A>,
}
impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for VacantEntry<'_, T, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("VacantEntry").field(self.get()).finish()
}
}
impl<'a, T, S, A: Allocator> Entry<'a, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self) -> OccupiedEntry<'a, T, S, A>
where
T: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => entry,
Entry::Vacant(entry) => entry.insert_entry(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert(self)
where
T: Hash,
S: BuildHasher,
{
if let Entry::Vacant(entry) = self {
entry.insert();
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &T {
match *self {
Entry::Occupied(ref entry) => entry.get(),
Entry::Vacant(ref entry) => entry.get(),
}
}
}
impl<T, S, A: Allocator> OccupiedEntry<'_, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &T {
self.inner.key()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> T {
self.inner.remove_entry().0
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace(self) -> T {
self.inner.replace_key()
}
}
impl<'a, T, S, A: Allocator> VacantEntry<'a, T, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &T {
self.inner.key()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_value(self) -> T {
self.inner.into_key()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self)
where
T: Hash,
S: BuildHasher,
{
self.inner.insert(());
}
#[cfg_attr(feature = "inline-more", inline)]
fn insert_entry(self) -> OccupiedEntry<'a, T, S, A>
where
T: Hash,
S: BuildHasher,
{
OccupiedEntry {
inner: self.inner.insert_entry(()),
}
}
}
#[allow(dead_code)]
fn assert_covariance() {
fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
v
}
fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
v
}
fn into_iter<'new, A: Allocator>(v: IntoIter<&'static str, A>) -> IntoIter<&'new str, A> {
v
}
fn difference<'a, 'new, A: Allocator>(
v: Difference<'a, &'static str, DefaultHashBuilder, A>,
) -> Difference<'a, &'new str, DefaultHashBuilder, A> {
v
}
fn symmetric_difference<'a, 'new, A: Allocator>(
v: SymmetricDifference<'a, &'static str, DefaultHashBuilder, A>,
) -> SymmetricDifference<'a, &'new str, DefaultHashBuilder, A> {
v
}
fn intersection<'a, 'new, A: Allocator>(
v: Intersection<'a, &'static str, DefaultHashBuilder, A>,
) -> Intersection<'a, &'new str, DefaultHashBuilder, A> {
v
}
fn union<'a, 'new, A: Allocator>(
v: Union<'a, &'static str, DefaultHashBuilder, A>,
) -> Union<'a, &'new str, DefaultHashBuilder, A> {
v
}
fn drain<'new, A: Allocator>(d: Drain<'static, &'static str, A>) -> Drain<'new, &'new str, A> {
d
}
}
#[cfg(test)]
mod test_set {
use super::super::map::DefaultHashBuilder;
use super::HashSet;
use std::vec::Vec;
#[test]
fn test_zero_capacities() {
type HS = HashSet<i32>;
let s = HS::new();
assert_eq!(s.capacity(), 0);
let s = HS::default();
assert_eq!(s.capacity(), 0);
let s = HS::with_hasher(DefaultHashBuilder::default());
assert_eq!(s.capacity(), 0);
let s = HS::with_capacity(0);
assert_eq!(s.capacity(), 0);
let s = HS::with_capacity_and_hasher(0, DefaultHashBuilder::default());
assert_eq!(s.capacity(), 0);
let mut s = HS::new();
s.insert(1);
s.insert(2);
s.remove(&1);
s.remove(&2);
s.shrink_to_fit();
assert_eq!(s.capacity(), 0);
let mut s = HS::new();
s.reserve(0);
assert_eq!(s.capacity(), 0);
}
#[test]
fn test_disjoint() {
let mut xs = HashSet::new();
let mut ys = HashSet::new();
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(5));
assert!(ys.insert(11));
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(7));
assert!(xs.insert(19));
assert!(xs.insert(4));
assert!(ys.insert(2));
assert!(ys.insert(-11));
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(ys.insert(7));
assert!(!xs.is_disjoint(&ys));
assert!(!ys.is_disjoint(&xs));
}
#[test]
fn test_subset_and_superset() {
let mut a = HashSet::new();
assert!(a.insert(0));
assert!(a.insert(5));
assert!(a.insert(11));
assert!(a.insert(7));
let mut b = HashSet::new();
assert!(b.insert(0));
assert!(b.insert(7));
assert!(b.insert(19));
assert!(b.insert(250));
assert!(b.insert(11));
assert!(b.insert(200));
assert!(!a.is_subset(&b));
assert!(!a.is_superset(&b));
assert!(!b.is_subset(&a));
assert!(!b.is_superset(&a));
assert!(b.insert(5));
assert!(a.is_subset(&b));
assert!(!a.is_superset(&b));
assert!(!b.is_subset(&a));
assert!(b.is_superset(&a));
}
#[test]
fn test_iterate() {
let mut a = HashSet::new();
for i in 0..32 {
assert!(a.insert(i));
}
let mut observed: u32 = 0;
for k in &a {
observed |= 1 << *k;
}
assert_eq!(observed, 0xFFFF_FFFF);
}
#[test]
fn test_intersection() {
let mut a = HashSet::new();
let mut b = HashSet::new();
assert!(a.insert(11));
assert!(a.insert(1));
assert!(a.insert(3));
assert!(a.insert(77));
assert!(a.insert(103));
assert!(a.insert(5));
assert!(a.insert(-5));
assert!(b.insert(2));
assert!(b.insert(11));
assert!(b.insert(77));
assert!(b.insert(-9));
assert!(b.insert(-42));
assert!(b.insert(5));
assert!(b.insert(3));
let mut i = 0;
let expected = [3, 5, 11, 77];
for x in a.intersection(&b) {
assert!(expected.contains(x));
i += 1;
}
assert_eq!(i, expected.len());
}
#[test]
fn test_difference() {
let mut a = HashSet::new();
let mut b = HashSet::new();
assert!(a.insert(1));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(11));
assert!(b.insert(3));
assert!(b.insert(9));
let mut i = 0;
let expected = [1, 5, 11];
for x in a.difference(&b) {
assert!(expected.contains(x));
i += 1;
}
assert_eq!(i, expected.len());
}
#[test]
fn test_symmetric_difference() {
let mut a = HashSet::new();
let mut b = HashSet::new();
assert!(a.insert(1));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(11));
assert!(b.insert(-2));
assert!(b.insert(3));
assert!(b.insert(9));
assert!(b.insert(14));
assert!(b.insert(22));
let mut i = 0;
let expected = [-2, 1, 5, 11, 14, 22];
for x in a.symmetric_difference(&b) {
assert!(expected.contains(x));
i += 1;
}
assert_eq!(i, expected.len());
}
#[test]
fn test_union() {
let mut a = HashSet::new();
let mut b = HashSet::new();
assert!(a.insert(1));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(11));
assert!(a.insert(16));
assert!(a.insert(19));
assert!(a.insert(24));
assert!(b.insert(-2));
assert!(b.insert(1));
assert!(b.insert(5));
assert!(b.insert(9));
assert!(b.insert(13));
assert!(b.insert(19));
let mut i = 0;
let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
for x in a.union(&b) {
assert!(expected.contains(x));
i += 1;
}
assert_eq!(i, expected.len());
}
#[test]
fn test_from_map() {
let mut a = crate::HashMap::new();
a.insert(1, ());
a.insert(2, ());
a.insert(3, ());
a.insert(4, ());
let a: HashSet<_> = a.into();
assert_eq!(a.len(), 4);
assert!(a.contains(&1));
assert!(a.contains(&2));
assert!(a.contains(&3));
assert!(a.contains(&4));
}
#[test]
fn test_from_iter() {
let xs = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9];
let set: HashSet<_> = xs.iter().copied().collect();
for x in &xs {
assert!(set.contains(x));
}
assert_eq!(set.iter().len(), xs.len() - 1);
}
#[test]
fn test_move_iter() {
let hs = {
let mut hs = HashSet::new();
hs.insert('a');
hs.insert('b');
hs
};
let v = hs.into_iter().collect::<Vec<char>>();
assert!(v == ['a', 'b'] || v == ['b', 'a']);
}
#[test]
fn test_eq() {
let mut s1 = HashSet::new();
s1.insert(1);
s1.insert(2);
s1.insert(3);
let mut s2 = HashSet::new();
s2.insert(1);
s2.insert(2);
assert!(s1 != s2);
s2.insert(3);
assert_eq!(s1, s2);
}
#[test]
fn test_show() {
let mut set = HashSet::new();
let empty = HashSet::<i32>::new();
set.insert(1);
set.insert(2);
let set_str = format!("{set:?}");
assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
assert_eq!(format!("{empty:?}"), "{}");
}
#[test]
fn test_trivial_drain() {
let mut s = HashSet::<i32>::new();
for _ in s.drain() {}
assert!(s.is_empty());
drop(s);
let mut s = HashSet::<i32>::new();
drop(s.drain());
assert!(s.is_empty());
}
#[test]
fn test_drain() {
let mut s: HashSet<_> = (1..100).collect();
for _ in 0..20 {
assert_eq!(s.len(), 99);
{
let mut last_i = 0;
let mut d = s.drain();
for (i, x) in d.by_ref().take(50).enumerate() {
last_i = i;
assert!(x != 0);
}
assert_eq!(last_i, 49);
}
if !s.is_empty() {
panic!("s should be empty!");
}
s.extend(1..100);
}
}
#[test]
fn test_replace() {
use core::hash;
#[derive(Debug)]
#[allow(dead_code)]
struct Foo(&'static str, i32);
impl PartialEq for Foo {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for Foo {}
impl hash::Hash for Foo {
fn hash<H: hash::Hasher>(&self, h: &mut H) {
self.0.hash(h);
}
}
let mut s = HashSet::new();
assert_eq!(s.replace(Foo("a", 1)), None);
assert_eq!(s.len(), 1);
assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
assert_eq!(s.len(), 1);
let mut it = s.iter();
assert_eq!(it.next(), Some(&Foo("a", 2)));
assert_eq!(it.next(), None);
}
#[test]
#[allow(clippy::needless_borrow)]
fn test_extend_ref() {
let mut a = HashSet::new();
a.insert(1);
a.extend([2, 3, 4]);
assert_eq!(a.len(), 4);
assert!(a.contains(&1));
assert!(a.contains(&2));
assert!(a.contains(&3));
assert!(a.contains(&4));
let mut b = HashSet::new();
b.insert(5);
b.insert(6);
a.extend(&b);
assert_eq!(a.len(), 6);
assert!(a.contains(&1));
assert!(a.contains(&2));
assert!(a.contains(&3));
assert!(a.contains(&4));
assert!(a.contains(&5));
assert!(a.contains(&6));
}
#[test]
fn test_retain() {
let xs = [1, 2, 3, 4, 5, 6];
let mut set: HashSet<i32> = xs.iter().copied().collect();
set.retain(|&k| k % 2 == 0);
assert_eq!(set.len(), 3);
assert!(set.contains(&2));
assert!(set.contains(&4));
assert!(set.contains(&6));
}
#[test]
fn test_extract_if() {
{
let mut set: HashSet<i32> = (0..8).collect();
let drained = set.extract_if(|&k| k % 2 == 0);
let mut out = drained.collect::<Vec<_>>();
out.sort_unstable();
assert_eq!(vec![0, 2, 4, 6], out);
assert_eq!(set.len(), 4);
}
{
let mut set: HashSet<i32> = (0..8).collect();
set.extract_if(|&k| k % 2 == 0).for_each(drop);
assert_eq!(set.len(), 4, "Removes non-matching items on drop");
}
}
#[test]
fn test_const_with_hasher() {
use core::hash::BuildHasher;
use std::collections::hash_map::DefaultHasher;
#[derive(Clone)]
struct MyHasher;
impl BuildHasher for MyHasher {
type Hasher = DefaultHasher;
fn build_hasher(&self) -> DefaultHasher {
DefaultHasher::new()
}
}
const EMPTY_SET: HashSet<u32, MyHasher> = HashSet::with_hasher(MyHasher);
let mut set = EMPTY_SET;
set.insert(19);
assert!(set.contains(&19));
}
#[test]
fn rehash_in_place() {
let mut set = HashSet::new();
for i in 0..224 {
set.insert(i);
}
assert_eq!(
set.capacity(),
224,
"The set must be at or close to capacity to trigger a re hashing"
);
for i in 100..1400 {
set.remove(&(i - 100));
set.insert(i);
}
}
#[test]
fn collect() {
let mut _set: HashSet<_> = (0..3).map(|_| ()).collect();
}
}