]> git.proxmox.com Git - rustc.git/blob - src/libcollections/btree/set.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libcollections / btree / set.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
12 // to TreeMap
13
14 use core::cmp::Ordering::{self, Less, Greater, Equal};
15 use core::cmp::{min, max};
16 use core::fmt::Debug;
17 use core::fmt;
18 use core::iter::{Peekable, FromIterator};
19 use core::ops::{BitOr, BitAnd, BitXor, Sub};
20
21 use borrow::Borrow;
22 use btree_map::{BTreeMap, Keys};
23 use super::Recover;
24 use Bound;
25
26 // FIXME(conventions): implement bounded iterators
27
28 /// A set based on a B-Tree.
29 ///
30 /// See [`BTreeMap`]'s documentation for a detailed discussion of this collection's performance
31 /// benefits and drawbacks.
32 ///
33 /// It is a logic error for an item to be modified in such a way that the item's ordering relative
34 /// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is
35 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
36 ///
37 /// [`BTreeMap`]: struct.BTreeMap.html
38 /// [`Ord`]: ../../std/cmp/trait.Ord.html
39 /// [`Cell`]: ../../std/cell/struct.Cell.html
40 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use std::collections::BTreeSet;
46 ///
47 /// // Type inference lets us omit an explicit type signature (which
48 /// // would be `BTreeSet<&str>` in this example).
49 /// let mut books = BTreeSet::new();
50 ///
51 /// // Add some books.
52 /// books.insert("A Dance With Dragons");
53 /// books.insert("To Kill a Mockingbird");
54 /// books.insert("The Odyssey");
55 /// books.insert("The Great Gatsby");
56 ///
57 /// // Check for a specific one.
58 /// if !books.contains("The Winds of Winter") {
59 /// println!("We have {} books, but The Winds of Winter ain't one.",
60 /// books.len());
61 /// }
62 ///
63 /// // Remove a book.
64 /// books.remove("The Odyssey");
65 ///
66 /// // Iterate over everything.
67 /// for book in &books {
68 /// println!("{}", book);
69 /// }
70 /// ```
71 #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub struct BTreeSet<T> {
74 map: BTreeMap<T, ()>,
75 }
76
77 /// An iterator over a BTreeSet's items.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct Iter<'a, T: 'a> {
80 iter: Keys<'a, T, ()>,
81 }
82
83 /// An owning iterator over a BTreeSet's items.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct IntoIter<T> {
86 iter: ::btree_map::IntoIter<T, ()>,
87 }
88
89 /// An iterator over a sub-range of BTreeSet's items.
90 pub struct Range<'a, T: 'a> {
91 iter: ::btree_map::Range<'a, T, ()>,
92 }
93
94 /// A lazy iterator producing elements in the set difference (in-order).
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Difference<'a, T: 'a> {
97 a: Peekable<Iter<'a, T>>,
98 b: Peekable<Iter<'a, T>>,
99 }
100
101 /// A lazy iterator producing elements in the set symmetric difference (in-order).
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub struct SymmetricDifference<'a, T: 'a> {
104 a: Peekable<Iter<'a, T>>,
105 b: Peekable<Iter<'a, T>>,
106 }
107
108 /// A lazy iterator producing elements in the set intersection (in-order).
109 #[stable(feature = "rust1", since = "1.0.0")]
110 pub struct Intersection<'a, T: 'a> {
111 a: Peekable<Iter<'a, T>>,
112 b: Peekable<Iter<'a, T>>,
113 }
114
115 /// A lazy iterator producing elements in the set union (in-order).
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub struct Union<'a, T: 'a> {
118 a: Peekable<Iter<'a, T>>,
119 b: Peekable<Iter<'a, T>>,
120 }
121
122 impl<T: Ord> BTreeSet<T> {
123 /// Makes a new BTreeSet with a reasonable choice of B.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// # #![allow(unused_mut)]
129 /// use std::collections::BTreeSet;
130 ///
131 /// let mut set: BTreeSet<i32> = BTreeSet::new();
132 /// ```
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub fn new() -> BTreeSet<T> {
135 BTreeSet { map: BTreeMap::new() }
136 }
137 }
138
139 impl<T> BTreeSet<T> {
140 /// Gets an iterator over the BTreeSet's contents.
141 ///
142 /// # Examples
143 ///
144 /// ```
145 /// use std::collections::BTreeSet;
146 ///
147 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
148 ///
149 /// for x in set.iter() {
150 /// println!("{}", x);
151 /// }
152 ///
153 /// let v: Vec<_> = set.iter().cloned().collect();
154 /// assert_eq!(v, [1, 2, 3, 4]);
155 /// ```
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub fn iter(&self) -> Iter<T> {
158 Iter { iter: self.map.keys() }
159 }
160 }
161
162 impl<T: Ord> BTreeSet<T> {
163 /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
164 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
165 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
166 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// #![feature(btree_range, collections_bound)]
172 ///
173 /// use std::collections::BTreeSet;
174 /// use std::collections::Bound::{Included, Unbounded};
175 ///
176 /// let mut set = BTreeSet::new();
177 /// set.insert(3);
178 /// set.insert(5);
179 /// set.insert(8);
180 /// for &elem in set.range(Included(&4), Included(&8)) {
181 /// println!("{}", elem);
182 /// }
183 /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
184 /// ```
185 #[unstable(feature = "btree_range",
186 reason = "matches collection reform specification, waiting for dust to settle",
187 issue = "27787")]
188 pub fn range<'a, Min: ?Sized + Ord, Max: ?Sized + Ord>(&'a self,
189 min: Bound<&Min>,
190 max: Bound<&Max>)
191 -> Range<'a, T>
192 where T: Borrow<Min> + Borrow<Max>
193 {
194 Range { iter: self.map.range(min, max) }
195 }
196 }
197
198 impl<T: Ord> BTreeSet<T> {
199 /// Visits the values representing the difference, in ascending order.
200 ///
201 /// # Examples
202 ///
203 /// ```
204 /// use std::collections::BTreeSet;
205 ///
206 /// let mut a = BTreeSet::new();
207 /// a.insert(1);
208 /// a.insert(2);
209 ///
210 /// let mut b = BTreeSet::new();
211 /// b.insert(2);
212 /// b.insert(3);
213 ///
214 /// let diff: Vec<_> = a.difference(&b).cloned().collect();
215 /// assert_eq!(diff, [1]);
216 /// ```
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
219 Difference {
220 a: self.iter().peekable(),
221 b: other.iter().peekable(),
222 }
223 }
224
225 /// Visits the values representing the symmetric difference, in ascending order.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// use std::collections::BTreeSet;
231 ///
232 /// let mut a = BTreeSet::new();
233 /// a.insert(1);
234 /// a.insert(2);
235 ///
236 /// let mut b = BTreeSet::new();
237 /// b.insert(2);
238 /// b.insert(3);
239 ///
240 /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
241 /// assert_eq!(sym_diff, [1, 3]);
242 /// ```
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn symmetric_difference<'a>(&'a self,
245 other: &'a BTreeSet<T>)
246 -> SymmetricDifference<'a, T> {
247 SymmetricDifference {
248 a: self.iter().peekable(),
249 b: other.iter().peekable(),
250 }
251 }
252
253 /// Visits the values representing the intersection, in ascending order.
254 ///
255 /// # Examples
256 ///
257 /// ```
258 /// use std::collections::BTreeSet;
259 ///
260 /// let mut a = BTreeSet::new();
261 /// a.insert(1);
262 /// a.insert(2);
263 ///
264 /// let mut b = BTreeSet::new();
265 /// b.insert(2);
266 /// b.insert(3);
267 ///
268 /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
269 /// assert_eq!(intersection, [2]);
270 /// ```
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
273 Intersection {
274 a: self.iter().peekable(),
275 b: other.iter().peekable(),
276 }
277 }
278
279 /// Visits the values representing the union, in ascending order.
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// use std::collections::BTreeSet;
285 ///
286 /// let mut a = BTreeSet::new();
287 /// a.insert(1);
288 ///
289 /// let mut b = BTreeSet::new();
290 /// b.insert(2);
291 ///
292 /// let union: Vec<_> = a.union(&b).cloned().collect();
293 /// assert_eq!(union, [1, 2]);
294 /// ```
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
297 Union {
298 a: self.iter().peekable(),
299 b: other.iter().peekable(),
300 }
301 }
302
303 /// Returns the number of elements in the set.
304 ///
305 /// # Examples
306 ///
307 /// ```
308 /// use std::collections::BTreeSet;
309 ///
310 /// let mut v = BTreeSet::new();
311 /// assert_eq!(v.len(), 0);
312 /// v.insert(1);
313 /// assert_eq!(v.len(), 1);
314 /// ```
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn len(&self) -> usize {
317 self.map.len()
318 }
319
320 /// Returns true if the set contains no elements.
321 ///
322 /// # Examples
323 ///
324 /// ```
325 /// use std::collections::BTreeSet;
326 ///
327 /// let mut v = BTreeSet::new();
328 /// assert!(v.is_empty());
329 /// v.insert(1);
330 /// assert!(!v.is_empty());
331 /// ```
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn is_empty(&self) -> bool {
334 self.len() == 0
335 }
336
337 /// Clears the set, removing all values.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use std::collections::BTreeSet;
343 ///
344 /// let mut v = BTreeSet::new();
345 /// v.insert(1);
346 /// v.clear();
347 /// assert!(v.is_empty());
348 /// ```
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub fn clear(&mut self) {
351 self.map.clear()
352 }
353
354 /// Returns `true` if the set contains a value.
355 ///
356 /// The value may be any borrowed form of the set's value type,
357 /// but the ordering on the borrowed form *must* match the
358 /// ordering on the value type.
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// use std::collections::BTreeSet;
364 ///
365 /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
366 /// assert_eq!(set.contains(&1), true);
367 /// assert_eq!(set.contains(&4), false);
368 /// ```
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
371 where T: Borrow<Q>,
372 Q: Ord
373 {
374 self.map.contains_key(value)
375 }
376
377 /// Returns a reference to the value in the set, if any, that is equal to the given value.
378 ///
379 /// The value may be any borrowed form of the set's value type,
380 /// but the ordering on the borrowed form *must* match the
381 /// ordering on the value type.
382 #[stable(feature = "set_recovery", since = "1.9.0")]
383 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
384 where T: Borrow<Q>,
385 Q: Ord
386 {
387 Recover::get(&self.map, value)
388 }
389
390 /// Returns `true` if the set has no elements in common with `other`.
391 /// This is equivalent to checking for an empty intersection.
392 ///
393 /// # Examples
394 ///
395 /// ```
396 /// use std::collections::BTreeSet;
397 ///
398 /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
399 /// let mut b = BTreeSet::new();
400 ///
401 /// assert_eq!(a.is_disjoint(&b), true);
402 /// b.insert(4);
403 /// assert_eq!(a.is_disjoint(&b), true);
404 /// b.insert(1);
405 /// assert_eq!(a.is_disjoint(&b), false);
406 /// ```
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
409 self.intersection(other).next().is_none()
410 }
411
412 /// Returns `true` if the set is a subset of another.
413 ///
414 /// # Examples
415 ///
416 /// ```
417 /// use std::collections::BTreeSet;
418 ///
419 /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
420 /// let mut set = BTreeSet::new();
421 ///
422 /// assert_eq!(set.is_subset(&sup), true);
423 /// set.insert(2);
424 /// assert_eq!(set.is_subset(&sup), true);
425 /// set.insert(4);
426 /// assert_eq!(set.is_subset(&sup), false);
427 /// ```
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
430 // Stolen from TreeMap
431 let mut x = self.iter();
432 let mut y = other.iter();
433 let mut a = x.next();
434 let mut b = y.next();
435 while a.is_some() {
436 if b.is_none() {
437 return false;
438 }
439
440 let a1 = a.unwrap();
441 let b1 = b.unwrap();
442
443 match b1.cmp(a1) {
444 Less => (),
445 Greater => return false,
446 Equal => a = x.next(),
447 }
448
449 b = y.next();
450 }
451 true
452 }
453
454 /// Returns `true` if the set is a superset of another.
455 ///
456 /// # Examples
457 ///
458 /// ```
459 /// use std::collections::BTreeSet;
460 ///
461 /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
462 /// let mut set = BTreeSet::new();
463 ///
464 /// assert_eq!(set.is_superset(&sub), false);
465 ///
466 /// set.insert(0);
467 /// set.insert(1);
468 /// assert_eq!(set.is_superset(&sub), false);
469 ///
470 /// set.insert(2);
471 /// assert_eq!(set.is_superset(&sub), true);
472 /// ```
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
475 other.is_subset(self)
476 }
477
478 /// Adds a value to the set.
479 ///
480 /// If the set did not have a value present, `true` is returned.
481 ///
482 /// If the set did have this key present, `false` is returned, and the
483 /// entry is not updated. See the [module-level documentation] for more.
484 ///
485 /// [module-level documentation]: index.html#insert-and-complex-keys
486 ///
487 /// # Examples
488 ///
489 /// ```
490 /// use std::collections::BTreeSet;
491 ///
492 /// let mut set = BTreeSet::new();
493 ///
494 /// assert_eq!(set.insert(2), true);
495 /// assert_eq!(set.insert(2), false);
496 /// assert_eq!(set.len(), 1);
497 /// ```
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn insert(&mut self, value: T) -> bool {
500 self.map.insert(value, ()).is_none()
501 }
502
503 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
504 /// one. Returns the replaced value.
505 #[stable(feature = "set_recovery", since = "1.9.0")]
506 pub fn replace(&mut self, value: T) -> Option<T> {
507 Recover::replace(&mut self.map, value)
508 }
509
510 /// Removes a value from the set. Returns `true` if the value was
511 /// present in the set.
512 ///
513 /// The value may be any borrowed form of the set's value type,
514 /// but the ordering on the borrowed form *must* match the
515 /// ordering on the value type.
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// use std::collections::BTreeSet;
521 ///
522 /// let mut set = BTreeSet::new();
523 ///
524 /// set.insert(2);
525 /// assert_eq!(set.remove(&2), true);
526 /// assert_eq!(set.remove(&2), false);
527 /// ```
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
530 where T: Borrow<Q>,
531 Q: Ord
532 {
533 self.map.remove(value).is_some()
534 }
535
536 /// Removes and returns the value in the set, if any, that is equal to the given one.
537 ///
538 /// The value may be any borrowed form of the set's value type,
539 /// but the ordering on the borrowed form *must* match the
540 /// ordering on the value type.
541 #[stable(feature = "set_recovery", since = "1.9.0")]
542 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
543 where T: Borrow<Q>,
544 Q: Ord
545 {
546 Recover::take(&mut self.map, value)
547 }
548 }
549
550 #[stable(feature = "rust1", since = "1.0.0")]
551 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
552 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
553 let mut set = BTreeSet::new();
554 set.extend(iter);
555 set
556 }
557 }
558
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl<T> IntoIterator for BTreeSet<T> {
561 type Item = T;
562 type IntoIter = IntoIter<T>;
563
564 /// Gets an iterator for moving out the BtreeSet's contents.
565 ///
566 /// # Examples
567 ///
568 /// ```
569 /// use std::collections::BTreeSet;
570 ///
571 /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
572 ///
573 /// let v: Vec<_> = set.into_iter().collect();
574 /// assert_eq!(v, [1, 2, 3, 4]);
575 /// ```
576 fn into_iter(self) -> IntoIter<T> {
577 IntoIter { iter: self.map.into_iter() }
578 }
579 }
580
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
583 type Item = &'a T;
584 type IntoIter = Iter<'a, T>;
585
586 fn into_iter(self) -> Iter<'a, T> {
587 self.iter()
588 }
589 }
590
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<T: Ord> Extend<T> for BTreeSet<T> {
593 #[inline]
594 fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
595 for elem in iter {
596 self.insert(elem);
597 }
598 }
599 }
600
601 #[stable(feature = "extend_ref", since = "1.2.0")]
602 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
603 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
604 self.extend(iter.into_iter().cloned());
605 }
606 }
607
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<T: Ord> Default for BTreeSet<T> {
610 fn default() -> BTreeSet<T> {
611 BTreeSet::new()
612 }
613 }
614
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
617 type Output = BTreeSet<T>;
618
619 /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
620 ///
621 /// # Examples
622 ///
623 /// ```
624 /// use std::collections::BTreeSet;
625 ///
626 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
627 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
628 ///
629 /// let result = &a - &b;
630 /// let result_vec: Vec<_> = result.into_iter().collect();
631 /// assert_eq!(result_vec, [1, 2]);
632 /// ```
633 fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
634 self.difference(rhs).cloned().collect()
635 }
636 }
637
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
640 type Output = BTreeSet<T>;
641
642 /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// use std::collections::BTreeSet;
648 ///
649 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
650 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
651 ///
652 /// let result = &a ^ &b;
653 /// let result_vec: Vec<_> = result.into_iter().collect();
654 /// assert_eq!(result_vec, [1, 4]);
655 /// ```
656 fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
657 self.symmetric_difference(rhs).cloned().collect()
658 }
659 }
660
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
663 type Output = BTreeSet<T>;
664
665 /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
666 ///
667 /// # Examples
668 ///
669 /// ```
670 /// use std::collections::BTreeSet;
671 ///
672 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
673 /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
674 ///
675 /// let result = &a & &b;
676 /// let result_vec: Vec<_> = result.into_iter().collect();
677 /// assert_eq!(result_vec, [2, 3]);
678 /// ```
679 fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
680 self.intersection(rhs).cloned().collect()
681 }
682 }
683
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
686 type Output = BTreeSet<T>;
687
688 /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
689 ///
690 /// # Examples
691 ///
692 /// ```
693 /// use std::collections::BTreeSet;
694 ///
695 /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
696 /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
697 ///
698 /// let result = &a | &b;
699 /// let result_vec: Vec<_> = result.into_iter().collect();
700 /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
701 /// ```
702 fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
703 self.union(rhs).cloned().collect()
704 }
705 }
706
707 #[stable(feature = "rust1", since = "1.0.0")]
708 impl<T: Debug> Debug for BTreeSet<T> {
709 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
710 f.debug_set().entries(self.iter()).finish()
711 }
712 }
713
714 impl<'a, T> Clone for Iter<'a, T> {
715 fn clone(&self) -> Iter<'a, T> {
716 Iter { iter: self.iter.clone() }
717 }
718 }
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<'a, T> Iterator for Iter<'a, T> {
721 type Item = &'a T;
722
723 fn next(&mut self) -> Option<&'a T> {
724 self.iter.next()
725 }
726 fn size_hint(&self) -> (usize, Option<usize>) {
727 self.iter.size_hint()
728 }
729 }
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
732 fn next_back(&mut self) -> Option<&'a T> {
733 self.iter.next_back()
734 }
735 }
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
738 fn len(&self) -> usize { self.iter.len() }
739 }
740
741
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<T> Iterator for IntoIter<T> {
744 type Item = T;
745
746 fn next(&mut self) -> Option<T> {
747 self.iter.next().map(|(k, _)| k)
748 }
749 fn size_hint(&self) -> (usize, Option<usize>) {
750 self.iter.size_hint()
751 }
752 }
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T> DoubleEndedIterator for IntoIter<T> {
755 fn next_back(&mut self) -> Option<T> {
756 self.iter.next_back().map(|(k, _)| k)
757 }
758 }
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl<T> ExactSizeIterator for IntoIter<T> {
761 fn len(&self) -> usize { self.iter.len() }
762 }
763
764
765 impl<'a, T> Clone for Range<'a, T> {
766 fn clone(&self) -> Range<'a, T> {
767 Range { iter: self.iter.clone() }
768 }
769 }
770 impl<'a, T> Iterator for Range<'a, T> {
771 type Item = &'a T;
772
773 fn next(&mut self) -> Option<&'a T> {
774 self.iter.next().map(|(k, _)| k)
775 }
776 }
777 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
778 fn next_back(&mut self) -> Option<&'a T> {
779 self.iter.next_back().map(|(k, _)| k)
780 }
781 }
782
783 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
784 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
785 match (x, y) {
786 (None, _) => short,
787 (_, None) => long,
788 (Some(x1), Some(y1)) => x1.cmp(y1),
789 }
790 }
791
792 impl<'a, T> Clone for Difference<'a, T> {
793 fn clone(&self) -> Difference<'a, T> {
794 Difference {
795 a: self.a.clone(),
796 b: self.b.clone(),
797 }
798 }
799 }
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl<'a, T: Ord> Iterator for Difference<'a, T> {
802 type Item = &'a T;
803
804 fn next(&mut self) -> Option<&'a T> {
805 loop {
806 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
807 Less => return self.a.next(),
808 Equal => {
809 self.a.next();
810 self.b.next();
811 }
812 Greater => {
813 self.b.next();
814 }
815 }
816 }
817 }
818
819 fn size_hint(&self) -> (usize, Option<usize>) {
820 let a_len = self.a.len();
821 let b_len = self.b.len();
822 (a_len.saturating_sub(b_len), Some(a_len))
823 }
824 }
825
826 impl<'a, T> Clone for SymmetricDifference<'a, T> {
827 fn clone(&self) -> SymmetricDifference<'a, T> {
828 SymmetricDifference {
829 a: self.a.clone(),
830 b: self.b.clone(),
831 }
832 }
833 }
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
836 type Item = &'a T;
837
838 fn next(&mut self) -> Option<&'a T> {
839 loop {
840 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
841 Less => return self.a.next(),
842 Equal => {
843 self.a.next();
844 self.b.next();
845 }
846 Greater => return self.b.next(),
847 }
848 }
849 }
850
851 fn size_hint(&self) -> (usize, Option<usize>) {
852 (0, Some(self.a.len() + self.b.len()))
853 }
854 }
855
856 impl<'a, T> Clone for Intersection<'a, T> {
857 fn clone(&self) -> Intersection<'a, T> {
858 Intersection {
859 a: self.a.clone(),
860 b: self.b.clone(),
861 }
862 }
863 }
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
866 type Item = &'a T;
867
868 fn next(&mut self) -> Option<&'a T> {
869 loop {
870 let o_cmp = match (self.a.peek(), self.b.peek()) {
871 (None, _) => None,
872 (_, None) => None,
873 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
874 };
875 match o_cmp {
876 None => return None,
877 Some(Less) => {
878 self.a.next();
879 }
880 Some(Equal) => {
881 self.b.next();
882 return self.a.next();
883 }
884 Some(Greater) => {
885 self.b.next();
886 }
887 }
888 }
889 }
890
891 fn size_hint(&self) -> (usize, Option<usize>) {
892 (0, Some(min(self.a.len(), self.b.len())))
893 }
894 }
895
896 impl<'a, T> Clone for Union<'a, T> {
897 fn clone(&self) -> Union<'a, T> {
898 Union {
899 a: self.a.clone(),
900 b: self.b.clone(),
901 }
902 }
903 }
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<'a, T: Ord> Iterator for Union<'a, T> {
906 type Item = &'a T;
907
908 fn next(&mut self) -> Option<&'a T> {
909 loop {
910 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
911 Less => return self.a.next(),
912 Equal => {
913 self.b.next();
914 return self.a.next();
915 }
916 Greater => return self.b.next(),
917 }
918 }
919 }
920
921 fn size_hint(&self) -> (usize, Option<usize>) {
922 let a_len = self.a.len();
923 let b_len = self.b.len();
924 (max(a_len, b_len), Some(a_len + b_len))
925 }
926 }