Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement owned ops for HashSet and BTreeSet #109402

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
116 changes: 116 additions & 0 deletions library/alloc/src/collections/btree/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,37 @@ impl<T: Ord + Clone, A: Allocator + Clone> Sub<&BTreeSet<T, A>> for &BTreeSet<T,
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T: Ord, A: Allocator + Clone> Sub<&BTreeSet<T, A>> for BTreeSet<T, A> {
type Output = BTreeSet<T, A>;

/// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a = BTreeSet::from([1, 2, 3]);
/// let b = BTreeSet::from([3, 4, 5]);
///
/// let result = a - &b;
/// assert_eq!(result, BTreeSet::from([1, 2]));
/// ```
fn sub(mut self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
// Iterate the smaller set, removing elements that are in `rhs` from `self`
if self.len() <= rhs.len() {
self.retain(|e| !rhs.contains(e));
} else {
rhs.iter().for_each(|e| {
self.remove(e);
})
}

self
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord + Clone, A: Allocator + Clone> BitXor<&BTreeSet<T, A>> for &BTreeSet<T, A> {
type Output = BTreeSet<T, A>;
Expand All @@ -1429,6 +1460,37 @@ impl<T: Ord + Clone, A: Allocator + Clone> BitXor<&BTreeSet<T, A>> for &BTreeSet
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T: Ord, A: Allocator + Clone> BitXor<BTreeSet<T, A>> for BTreeSet<T, A> {
type Output = BTreeSet<T, A>;

/// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a = BTreeSet::from([1, 2, 3]);
/// let b = BTreeSet::from([2, 3, 4]);
///
/// let result = a ^ b;
/// assert_eq!(result, BTreeSet::from([1, 4]));
/// ```
fn bitxor(self, rhs: BTreeSet<T, A>) -> BTreeSet<T, A> {
// Iterate through the smaller set
let [mut a, mut b] = minmax_by_key(self, rhs, BTreeSet::len);

// This is essentially
// a = a - b (retain elements that are *not* in b)
// b = b - a (remove all elements that are in a)
a.retain(|e| !b.remove(e));

// Union of the differences
a | b
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord + Clone, A: Allocator + Clone> BitAnd<&BTreeSet<T, A>> for &BTreeSet<T, A> {
type Output = BTreeSet<T, A>;
Expand All @@ -1454,6 +1516,29 @@ impl<T: Ord + Clone, A: Allocator + Clone> BitAnd<&BTreeSet<T, A>> for &BTreeSet
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T: Ord, A: Allocator + Clone> BitAnd<&BTreeSet<T, A>> for BTreeSet<T, A> {
type Output = BTreeSet<T, A>;

/// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a = BTreeSet::from([1, 2, 3]);
/// let b = BTreeSet::from([2, 3, 4]);
///
/// let result = a & &b;
/// assert_eq!(result, BTreeSet::from([2, 3]));
/// ```
fn bitand(mut self, rhs: &BTreeSet<T, A>) -> BTreeSet<T, A> {
self.retain(|e| rhs.contains(e));
self
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord + Clone, A: Allocator + Clone> BitOr<&BTreeSet<T, A>> for &BTreeSet<T, A> {
type Output = BTreeSet<T, A>;
Expand All @@ -1479,6 +1564,33 @@ impl<T: Ord + Clone, A: Allocator + Clone> BitOr<&BTreeSet<T, A>> for &BTreeSet<
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T: Ord, A: Allocator + Clone> BitOr<BTreeSet<T, A>> for BTreeSet<T, A> {
type Output = BTreeSet<T, A>;

/// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeSet;
///
/// let a = BTreeSet::from([1, 2, 3]);
/// let b = BTreeSet::from([3, 4, 5]);
///
/// let result = a | b;
/// assert_eq!(result, BTreeSet::from([1, 2, 3, 4, 5]));
/// ```
fn bitor(self, rhs: BTreeSet<T, A>) -> BTreeSet<T, A> {
// Try to avoid unnecessary moves, by keeping set with the bigger length
let [a, mut b] = minmax_by_key(self, rhs, BTreeSet::len);

b.extend(a);

b
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug, A: Allocator + Clone> Debug for BTreeSet<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down Expand Up @@ -1789,5 +1901,9 @@ impl<'a, T: Ord> Iterator for Union<'a, T> {
#[stable(feature = "fused", since = "1.26.0")]
impl<T: Ord> FusedIterator for Union<'_, T> {}

fn minmax_by_key<T, K: Ord>(a: T, b: T, k: impl Fn(&T) -> K) -> [T; 2] {
if k(&a) <= k(&b) { [a, b] } else { [b, a] }
}

#[cfg(test)]
mod tests;
177 changes: 141 additions & 36 deletions library/std/src/collections/hash/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,21 +1138,46 @@ where
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let set = &a | &b;
///
/// let mut i = 0;
/// let expected = [1, 2, 3, 4, 5];
/// for x in &set {
/// assert!(expected.contains(x));
/// i += 1;
/// }
/// assert_eq!(i, expected.len());
/// let result = &a | &b;
/// assert_eq!(result, HashSet::from([1, 2, 3, 4, 5]));
/// ```
fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.union(rhs).cloned().collect()
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T, S> BitOr<HashSet<T, S>> for HashSet<T, S>
where
T: Eq + Hash,
S: BuildHasher,
{
type Output = HashSet<T, S>;

/// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let result = a | b;
/// assert_eq!(result, HashSet::from([1, 2, 3, 4, 5]));
/// ```
fn bitor(self, rhs: HashSet<T, S>) -> HashSet<T, S> {
// Try to avoid allocations by keeping set with the bigger capacity,
// try to avoid unnecessary moves, by keeping set with the bigger length
let [a, mut b] = minmax_by_key(self, rhs, |set| (set.capacity(), set.len()));

b.extend(a);

b
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
where
Expand All @@ -1171,21 +1196,41 @@ where
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([2, 3, 4]);
///
/// let set = &a & &b;
///
/// let mut i = 0;
/// let expected = [2, 3];
/// for x in &set {
/// assert!(expected.contains(x));
/// i += 1;
/// }
/// assert_eq!(i, expected.len());
/// let result = &a & &b;
/// assert_eq!(result, HashSet::from([2, 3]));
/// ```
fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.intersection(rhs).cloned().collect()
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T, S> BitAnd<&HashSet<T, S>> for HashSet<T, S>
where
T: Eq + Hash,
S: BuildHasher,
{
type Output = HashSet<T, S>;

/// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([2, 3, 4]);
///
/// let result = a & &b;
/// assert_eq!(result, HashSet::from([2, 3]));
/// ```
fn bitand(mut self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.retain(|e| rhs.contains(e));
self
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
where
Expand All @@ -1204,21 +1249,49 @@ where
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let set = &a ^ &b;
///
/// let mut i = 0;
/// let expected = [1, 2, 4, 5];
/// for x in &set {
/// assert!(expected.contains(x));
/// i += 1;
/// }
/// assert_eq!(i, expected.len());
/// let result = &a ^ &b;
/// assert_eq!(result, HashSet::from([1, 2, 4, 5]));
/// ```
fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.symmetric_difference(rhs).cloned().collect()
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T, S> BitXor<HashSet<T, S>> for HashSet<T, S>
where
T: Eq + Hash,
S: BuildHasher,
{
type Output = HashSet<T, S>;

/// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let result = a ^ b;
/// assert_eq!(result, HashSet::from([1, 2, 4, 5]));
/// ```
fn bitxor(self, rhs: HashSet<T, S>) -> HashSet<T, S> {
// Iterate through the smaller set
let [mut a, mut b] = minmax_by_key(self, rhs, HashSet::len);

// This is essentially
// a = a - b (retain elements that are *not* in b)
// b = b - a (remove all elements that are in a)
a.retain(|e| !b.remove(e));

// Union of the differences
a | b
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
where
Expand All @@ -1237,21 +1310,49 @@ where
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let set = &a - &b;
///
/// let mut i = 0;
/// let expected = [1, 2];
/// for x in &set {
/// assert!(expected.contains(x));
/// i += 1;
/// }
/// assert_eq!(i, expected.len());
/// let result = &a - &b;
/// assert_eq!(result, HashSet::from([1, 2]));
/// ```
fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
self.difference(rhs).cloned().collect()
}
}

#[stable(feature = "set_owned_ops", since = "CURRENT_RUSTC_VERSION")]
impl<T, S> Sub<&HashSet<T, S>> for HashSet<T, S>
where
T: Eq + Hash,
S: BuildHasher,
{
type Output = HashSet<T, S>;

/// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let a = HashSet::from([1, 2, 3]);
/// let b = HashSet::from([3, 4, 5]);
///
/// let result = a - &b;
/// assert_eq!(result, HashSet::from([1, 2]));
/// ```
fn sub(mut self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
// Iterate the smaller set, removing elements that are in `rhs` from `self`
if self.len() <= rhs.len() {
self.retain(|e| !rhs.contains(e));
} else {
rhs.iter().for_each(|e| {
self.remove(e);
})
}

self
}
}

/// An iterator over the items of a `HashSet`.
///
/// This `struct` is created by the [`iter`] method on [`HashSet`].
Expand Down Expand Up @@ -1843,3 +1944,7 @@ fn assert_covariance() {
d
}
}

fn minmax_by_key<T, K: Ord>(a: T, b: T, k: impl Fn(&T) -> K) -> [T; 2] {
if k(&a) <= k(&b) { [a, b] } else { [b, a] }
}