1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! An unordered set.
//!
//! An immutable hash set using [hash array mapped tries] [1].
//!
//! Most operations on this set are O(log<sub>x</sub> n) for a
//! suitably high *x* that it should be nearly O(1) for most sets.
//! Because of this, it's a great choice for a generic set as long as
//! you don't mind that values will need to implement
//! [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq].
//!
//! Values will have a predictable order based on the hasher
//! being used. Unless otherwise specified, this will be the standard
//! [`RandomState`][std::collections::hash_map::RandomState] hasher.
//!
//! [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie
//! [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
//! [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html
//! [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::collections::{self, BTreeSet};
use std::fmt::{Debug, Error, Formatter};
use std::hash::{BuildHasher, Hash};
use std::iter::{FromIterator, FusedIterator, Sum};
use std::ops::{Add, Deref, Mul};
use crate::nodes::hamt::{hash_key, Drain as NodeDrain, HashValue, Iter as NodeIter, Node};
use crate::ordset::OrdSet;
use crate::util::{Pool, PoolRef, Ref};
use crate::Vector;
/// Construct a set from a sequence of values.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// # fn main() {
/// assert_eq!(
/// hashset![1, 2, 3],
/// HashSet::from(vec![1, 2, 3])
/// );
/// # }
/// ```
#[macro_export]
macro_rules! hashset {
() => { $crate::hashset::HashSet::new() };
( $($x:expr),* ) => {{
let mut l = $crate::hashset::HashSet::new();
$(
l.insert($x);
)*
l
}};
( $($x:expr ,)* ) => {{
let mut l = $crate::hashset::HashSet::new();
$(
l.insert($x);
)*
l
}};
}
def_pool!(HashSetPool<A>, Node<Value<A>>);
/// An unordered set.
///
/// An immutable hash set using [hash array mapped tries] [1].
///
/// Most operations on this set are O(log<sub>x</sub> n) for a
/// suitably high *x* that it should be nearly O(1) for most sets.
/// Because of this, it's a great choice for a generic set as long as
/// you don't mind that values will need to implement
/// [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq].
///
/// Values will have a predictable order based on the hasher
/// being used. Unless otherwise specified, this will be the standard
/// [`RandomState`][std::collections::hash_map::RandomState] hasher.
///
/// [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie
/// [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
/// [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html
/// [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
pub struct HashSet<A, S = RandomState> {
hasher: Ref<S>,
pool: HashSetPool<A>,
root: PoolRef<Node<Value<A>>>,
size: usize,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Value<A>(A);
impl<A> Deref for Value<A> {
type Target = A;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// FIXME lacking specialisation, we can't simply implement `HashValue`
// for `A`, we have to use the `Value<A>` indirection.
impl<A> HashValue for Value<A>
where
A: Hash + Eq,
{
type Key = A;
fn extract_key(&self) -> &Self::Key {
&self.0
}
fn ptr_eq(&self, _other: &Self) -> bool {
false
}
}
impl<A> HashSet<A, RandomState> {
/// Construct an empty set.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Construct an empty set using a specific memory pool.
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool(pool: &HashSetPool<A>) -> Self {
Self {
pool: pool.clone(),
hasher: Default::default(),
size: 0,
root: PoolRef::default(&pool.0),
}
}
}
impl<A> HashSet<A, RandomState>
where
A: Hash + Eq + Clone,
{
/// Construct a set with a single value.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// # use std::sync::Arc;
/// let set = HashSet::unit(123);
/// assert!(set.contains(&123));
/// ```
#[inline]
#[must_use]
pub fn unit(a: A) -> Self {
HashSet::new().update(a)
}
}
impl<A, S> HashSet<A, S> {
/// Test whether a set is empty.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// assert!(
/// !hashset![1, 2, 3].is_empty()
/// );
/// assert!(
/// HashSet::<i32>::new().is_empty()
/// );
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Get the size of a set.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// assert_eq!(3, hashset![1, 2, 3].len());
/// ```
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.size
}
/// Test whether two sets refer to the same content in memory.
///
/// This is true if the two sides are references to the same set,
/// or if the two sets refer to the same root node.
///
/// This would return true if you're comparing a set to itself, or
/// if you're comparing a set to a fresh clone of itself.
///
/// Time: O(1)
pub fn ptr_eq(&self, other: &Self) -> bool {
std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
}
/// Get a reference to the memory pool used by this set.
///
/// Note that if you didn't specifically construct it with a pool, you'll
/// get back a reference to a pool of size 0.
#[cfg(feature = "pool")]
pub fn pool(&self) -> &HashSetPool<A> {
&self.pool
}
/// Construct an empty hash set using the provided hasher.
#[inline]
#[must_use]
pub fn with_hasher<RS>(hasher: RS) -> Self
where
Ref<S>: From<RS>,
{
let pool = HashSetPool::default();
let root = PoolRef::default(&pool.0);
HashSet {
size: 0,
pool,
root,
hasher: From::from(hasher),
}
}
/// Construct an empty hash set using the provided memory pool and hasher.
#[cfg(feature = "pool")]
#[inline]
#[must_use]
pub fn with_pool_hasher<RS>(pool: &HashSetPool<A>, hasher: RS) -> Self
where
Ref<S>: From<RS>,
{
let root = PoolRef::default(&pool.0);
HashSet {
size: 0,
pool: pool.clone(),
root,
hasher: From::from(hasher),
}
}
/// Get a reference to the set's [`BuildHasher`][BuildHasher].
///
/// [BuildHasher]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
#[must_use]
pub fn hasher(&self) -> &Ref<S> {
&self.hasher
}
/// Construct an empty hash set using the same hasher as the current hash set.
#[inline]
#[must_use]
pub fn new_from<A1>(&self) -> HashSet<A1, S>
where
A1: Hash + Eq + Clone,
{
let pool = HashSetPool::default();
let root = PoolRef::default(&pool.0);
HashSet {
size: 0,
pool,
root,
hasher: self.hasher.clone(),
}
}
/// Discard all elements from the set.
///
/// This leaves you with an empty set, and all elements that
/// were previously inside it are dropped.
///
/// Time: O(n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::HashSet;
/// let mut set = hashset![1, 2, 3];
/// set.clear();
/// assert!(set.is_empty());
/// ```
pub fn clear(&mut self) {
if !self.is_empty() {
self.root = PoolRef::default(&self.pool.0);
self.size = 0;
}
}
/// Get an iterator over the values in a hash set.
///
/// Please note that the order is consistent between sets using
/// the same hasher, but no other ordering guarantee is offered.
/// Items will not come out in insertion order or sort order.
/// They will, however, come out in the same order every time for
/// the same set.
#[must_use]
pub fn iter(&self) -> Iter<'_, A> {
Iter {
it: NodeIter::new(&self.root, self.size),
}
}
}
impl<A, S> HashSet<A, S>
where
A: Hash + Eq,
S: BuildHasher,
{
fn test_eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
let mut seen = collections::HashSet::new();
for value in self.iter() {
if !other.contains(value) {
return false;
}
seen.insert(value);
}
for value in other.iter() {
if !seen.contains(&value) {
return false;
}
}
true
}
/// Test if a value is part of a set.
///
/// Time: O(log n)
#[must_use]
pub fn contains<BA>(&self, a: &BA) -> bool
where
BA: Hash + Eq + ?Sized,
A: Borrow<BA>,
{
self.root.get(hash_key(&*self.hasher, a), 0, a).is_some()
}
/// Test whether a set is a subset of another set, meaning that
/// all values in our set must also be in the other set.
///
/// Time: O(n log n)
#[must_use]
pub fn is_subset<RS>(&self, other: RS) -> bool
where
RS: Borrow<Self>,
{
let o = other.borrow();
self.iter().all(|a| o.contains(a))
}
/// Test whether a set is a proper subset of another set, meaning
/// that all values in our set must also be in the other set. A
/// proper subset must also be smaller than the other set.
///
/// Time: O(n log n)
#[must_use]
pub fn is_proper_subset<RS>(&self, other: RS) -> bool
where
RS: Borrow<Self>,
{
self.len() != other.borrow().len() && self.is_subset(other)
}
}
impl<A, S> HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
/// Insert a value into a set.
///
/// Time: O(log n)
#[inline]
pub fn insert(&mut self, a: A) -> Option<A> {
let hash = hash_key(&*self.hasher, &a);
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.insert(&self.pool.0, hash, 0, Value(a)) {
None => {
self.size += 1;
None
}
Some(Value(old_value)) => Some(old_value),
}
}
/// Remove a value from a set if it exists.
///
/// Time: O(log n)
pub fn remove<BA>(&mut self, a: &BA) -> Option<A>
where
BA: Hash + Eq + ?Sized,
A: Borrow<BA>,
{
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
let result = root.remove(&self.pool.0, hash_key(&*self.hasher, a), 0, a);
if result.is_some() {
self.size -= 1;
}
result.map(|v| v.0)
}
/// Construct a new set from the current set with the given value
/// added.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// # use std::sync::Arc;
/// let set = hashset![123];
/// assert_eq!(
/// set.update(456),
/// hashset![123, 456]
/// );
/// ```
#[must_use]
pub fn update(&self, a: A) -> Self {
let mut out = self.clone();
out.insert(a);
out
}
/// Construct a new set with the given value removed if it's in
/// the set.
///
/// Time: O(log n)
#[must_use]
pub fn without<BA>(&self, a: &BA) -> Self
where
BA: Hash + Eq + ?Sized,
A: Borrow<BA>,
{
let mut out = self.clone();
out.remove(a);
out
}
/// Filter out values from a set which don't satisfy a predicate.
///
/// This is slightly more efficient than filtering using an
/// iterator, in that it doesn't need to rehash the retained
/// values, but it still needs to reconstruct the entire tree
/// structure of the set.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::HashSet;
/// let mut set = hashset![1, 2, 3];
/// set.retain(|v| *v > 1);
/// let expected = hashset![2, 3];
/// assert_eq!(expected, set);
/// ```
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&A) -> bool,
{
let old_root = self.root.clone();
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
for (value, hash) in NodeIter::new(&old_root, self.size) {
if !f(value) && root.remove(&self.pool.0, hash, 0, value).is_some() {
self.size -= 1;
}
}
}
/// Construct the union of two sets.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// let set1 = hashset!{1, 2};
/// let set2 = hashset!{2, 3};
/// let expected = hashset!{1, 2, 3};
/// assert_eq!(expected, set1.union(set2));
/// ```
#[must_use]
pub fn union(self, other: Self) -> Self {
let (mut to_mutate, to_consume) = if self.len() >= other.len() {
(self, other)
} else {
(other, self)
};
for value in to_consume {
to_mutate.insert(value);
}
to_mutate
}
/// Construct the union of multiple sets.
///
/// Time: O(n log n)
#[must_use]
pub fn unions<I>(i: I) -> Self
where
I: IntoIterator<Item = Self>,
S: Default,
{
i.into_iter().fold(Self::default(), Self::union)
}
/// Construct the symmetric difference between two sets.
///
/// This is an alias for the
/// [`symmetric_difference`][symmetric_difference] method.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// let set1 = hashset!{1, 2};
/// let set2 = hashset!{2, 3};
/// let expected = hashset!{1, 3};
/// assert_eq!(expected, set1.difference(set2));
/// ```
///
/// [symmetric_difference]: #method.symmetric_difference
#[deprecated(
since = "2.0.1",
note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
)]
#[must_use]
pub fn difference(self, other: Self) -> Self {
self.symmetric_difference(other)
}
/// Construct the symmetric difference between two sets.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// let set1 = hashset!{1, 2};
/// let set2 = hashset!{2, 3};
/// let expected = hashset!{1, 3};
/// assert_eq!(expected, set1.symmetric_difference(set2));
/// ```
#[must_use]
pub fn symmetric_difference(mut self, other: Self) -> Self {
for value in other {
if self.remove(&value).is_none() {
self.insert(value);
}
}
self
}
/// Construct the relative complement between two sets, that is the set
/// of values in `self` that do not occur in `other`.
///
/// Time: O(m log n) where m is the size of the other set
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::ordset::OrdSet;
/// let set1 = ordset!{1, 2};
/// let set2 = ordset!{2, 3};
/// let expected = ordset!{1};
/// assert_eq!(expected, set1.relative_complement(set2));
/// ```
#[must_use]
pub fn relative_complement(mut self, other: Self) -> Self {
for value in other {
let _ = self.remove(&value);
}
self
}
/// Construct the intersection of two sets.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate imbl;
/// # use imbl::hashset::HashSet;
/// let set1 = hashset!{1, 2};
/// let set2 = hashset!{2, 3};
/// let expected = hashset!{2};
/// assert_eq!(expected, set1.intersection(set2));
/// ```
#[must_use]
pub fn intersection(self, other: Self) -> Self {
let mut out = self.new_from();
for value in other {
if self.contains(&value) {
out.insert(value);
}
}
out
}
}
// Core traits
impl<A, S> Clone for HashSet<A, S>
where
A: Clone,
{
/// Clone a set.
///
/// Time: O(1)
#[inline]
fn clone(&self) -> Self {
HashSet {
hasher: self.hasher.clone(),
pool: self.pool.clone(),
root: self.root.clone(),
size: self.size,
}
}
}
impl<A, S> PartialEq for HashSet<A, S>
where
A: Hash + Eq,
S: BuildHasher + Default,
{
fn eq(&self, other: &Self) -> bool {
self.test_eq(other)
}
}
impl<A, S> Eq for HashSet<A, S>
where
A: Hash + Eq,
S: BuildHasher + Default,
{
}
impl<A, S> Default for HashSet<A, S>
where
S: BuildHasher + Default,
{
fn default() -> Self {
let pool = HashSetPool::default();
let root = PoolRef::default(&pool.0);
HashSet {
hasher: Ref::<S>::default(),
pool,
root,
size: 0,
}
}
}
impl<A, S> Add for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
type Output = HashSet<A, S>;
fn add(self, other: Self) -> Self::Output {
self.union(other)
}
}
impl<A, S> Mul for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
type Output = HashSet<A, S>;
fn mul(self, other: Self) -> Self::Output {
self.intersection(other)
}
}
impl<'a, A, S> Add for &'a HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
type Output = HashSet<A, S>;
fn add(self, other: Self) -> Self::Output {
self.clone().union(other.clone())
}
}
impl<'a, A, S> Mul for &'a HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
type Output = HashSet<A, S>;
fn mul(self, other: Self) -> Self::Output {
self.clone().intersection(other.clone())
}
}
impl<A, S> Sum for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn sum<I>(it: I) -> Self
where
I: Iterator<Item = Self>,
{
it.fold(Self::default(), |a, b| a + b)
}
}
impl<A, S, R> Extend<R> for HashSet<A, S>
where
A: Hash + Eq + Clone + From<R>,
S: BuildHasher,
{
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = R>,
{
for value in iter {
self.insert(From::from(value));
}
}
}
#[cfg(not(has_specialisation))]
impl<A, S> Debug for HashSet<A, S>
where
A: Hash + Eq + Debug,
S: BuildHasher,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.debug_set().entries(self.iter()).finish()
}
}
#[cfg(has_specialisation)]
impl<A, S> Debug for HashSet<A, S>
where
A: Hash + Eq + Debug,
S: BuildHasher,
{
default fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.debug_set().entries(self.iter()).finish()
}
}
#[cfg(has_specialisation)]
impl<A, S> Debug for HashSet<A, S>
where
A: Hash + Eq + Debug + Ord,
S: BuildHasher,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.debug_set().entries(self.iter()).finish()
}
}
// Iterators
/// An iterator over the elements of a set.
pub struct Iter<'a, A> {
it: NodeIter<'a, Value<A>>,
}
// We impl Clone instead of deriving it, because we want Clone even if K and V aren't.
impl<'a, A> Clone for Iter<'a, A> {
fn clone(&self) -> Self {
Iter {
it: self.it.clone(),
}
}
}
impl<'a, A> Iterator for Iter<'a, A>
where
A: 'a,
{
type Item = &'a A;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|(v, _)| &v.0)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
impl<'a, A> FusedIterator for Iter<'a, A> {}
/// A consuming iterator over the elements of a set.
pub struct ConsumingIter<A>
where
A: Hash + Eq + Clone,
{
it: NodeDrain<Value<A>>,
}
impl<A> Iterator for ConsumingIter<A>
where
A: Hash + Eq + Clone,
{
type Item = A;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|(v, _)| v.0)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<A> ExactSizeIterator for ConsumingIter<A> where A: Hash + Eq + Clone {}
impl<A> FusedIterator for ConsumingIter<A> where A: Hash + Eq + Clone {}
// Iterator conversions
impl<A, RA, S> FromIterator<RA> for HashSet<A, S>
where
A: Hash + Eq + Clone + From<RA>,
S: BuildHasher + Default,
{
fn from_iter<T>(i: T) -> Self
where
T: IntoIterator<Item = RA>,
{
let mut set = Self::default();
for value in i {
set.insert(From::from(value));
}
set
}
}
impl<'a, A, S> IntoIterator for &'a HashSet<A, S>
where
A: Hash + Eq,
S: BuildHasher,
{
type Item = &'a A;
type IntoIter = Iter<'a, A>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<A, S> IntoIterator for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher,
{
type Item = A;
type IntoIter = ConsumingIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
ConsumingIter {
it: NodeDrain::new(&self.pool.0, self.root, self.size),
}
}
}
// Conversions
impl<'s, 'a, A, OA, SA, SB> From<&'s HashSet<&'a A, SA>> for HashSet<OA, SB>
where
A: ToOwned<Owned = OA> + Hash + Eq + ?Sized,
OA: Borrow<A> + Hash + Eq + Clone,
SA: BuildHasher,
SB: BuildHasher + Default,
{
fn from(set: &HashSet<&A, SA>) -> Self {
set.iter().map(|a| (*a).to_owned()).collect()
}
}
impl<A, S, const N: usize> From<[A; N]> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(arr: [A; N]) -> Self {
IntoIterator::into_iter(arr).collect()
}
}
impl<'a, A, S> From<&'a [A]> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(slice: &'a [A]) -> Self {
slice.iter().cloned().collect()
}
}
impl<A, S> From<Vec<A>> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(vec: Vec<A>) -> Self {
vec.into_iter().collect()
}
}
impl<'a, A, S> From<&'a Vec<A>> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(vec: &Vec<A>) -> Self {
vec.iter().cloned().collect()
}
}
impl<A, S> From<Vector<A>> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(vector: Vector<A>) -> Self {
vector.into_iter().collect()
}
}
impl<'a, A, S> From<&'a Vector<A>> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(vector: &Vector<A>) -> Self {
vector.iter().cloned().collect()
}
}
impl<A, S> From<collections::HashSet<A>> for HashSet<A, S>
where
A: Eq + Hash + Clone,
S: BuildHasher + Default,
{
fn from(hash_set: collections::HashSet<A>) -> Self {
hash_set.into_iter().collect()
}
}
impl<'a, A, S> From<&'a collections::HashSet<A>> for HashSet<A, S>
where
A: Eq + Hash + Clone,
S: BuildHasher + Default,
{
fn from(hash_set: &collections::HashSet<A>) -> Self {
hash_set.iter().cloned().collect()
}
}
impl<'a, A, S> From<&'a BTreeSet<A>> for HashSet<A, S>
where
A: Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(btree_set: &BTreeSet<A>) -> Self {
btree_set.iter().cloned().collect()
}
}
impl<A, S> From<OrdSet<A>> for HashSet<A, S>
where
A: Ord + Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(ordset: OrdSet<A>) -> Self {
ordset.into_iter().collect()
}
}
impl<'a, A, S> From<&'a OrdSet<A>> for HashSet<A, S>
where
A: Ord + Hash + Eq + Clone,
S: BuildHasher + Default,
{
fn from(ordset: &OrdSet<A>) -> Self {
ordset.into_iter().cloned().collect()
}
}
// Proptest
#[cfg(any(test, feature = "proptest"))]
#[doc(hidden)]
pub mod proptest {
#[deprecated(
since = "14.3.0",
note = "proptest strategies have moved to imbl::proptest"
)]
pub use crate::proptest::hash_set;
}
#[cfg(test)]
mod test {
use super::proptest::*;
use super::*;
use crate::test::LolHasher;
use ::proptest::num::i16;
use ::proptest::proptest;
use static_assertions::{assert_impl_all, assert_not_impl_any};
use std::hash::BuildHasherDefault;
assert_impl_all!(HashSet<i32>: Send, Sync);
assert_not_impl_any!(HashSet<*const i32>: Send, Sync);
assert_covariant!(HashSet<T> in T);
#[test]
fn insert_failing() {
let mut set: HashSet<i16, BuildHasherDefault<LolHasher>> = Default::default();
set.insert(14658);
assert_eq!(1, set.len());
set.insert(-19198);
assert_eq!(2, set.len());
}
#[test]
fn match_strings_with_string_slices() {
let mut set: HashSet<String> = From::from(&hashset!["foo", "bar"]);
set = set.without("bar");
assert!(!set.contains("bar"));
set.remove("foo");
assert!(!set.contains("foo"));
}
#[test]
fn macro_allows_trailing_comma() {
let set1 = hashset! {"foo", "bar"};
let set2 = hashset! {
"foo",
"bar",
};
assert_eq!(set1, set2);
}
#[test]
fn issue_60_drain_iterator_memory_corruption() {
use crate::test::MetroHashBuilder;
for i in 0..1000 {
let mut lhs = vec![0, 1, 2];
lhs.sort_unstable();
let hasher = Ref::from(MetroHashBuilder::new(i));
let mut iset: HashSet<_, MetroHashBuilder> = HashSet::with_hasher(hasher.clone());
for &i in &lhs {
iset.insert(i);
}
let mut rhs: Vec<_> = iset.clone().into_iter().collect();
rhs.sort_unstable();
if lhs != rhs {
println!("iteration: {}", i);
println!("seed: {}", hasher.seed());
println!("lhs: {}: {:?}", lhs.len(), &lhs);
println!("rhs: {}: {:?}", rhs.len(), &rhs);
panic!();
}
}
}
proptest! {
#[test]
fn proptest_a_set(ref s in hash_set(".*", 10..100)) {
assert!(s.len() < 100);
assert!(s.len() >= 10);
}
}
}