]> git.lizzy.rs Git - rust.git/blob - src/libcollections/btree/set.rs
Unignore u128 test for stage 0,1
[rust.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, FusedIterator};
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 range::RangeArgument;
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 ///
79 /// This structure is created by the [`iter`] method on [`BTreeSet`].
80 ///
81 /// [`BTreeSet`]: struct.BTreeSet.html
82 /// [`iter`]: struct.BTreeSet.html#method.iter
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct Iter<'a, T: 'a> {
85     iter: Keys<'a, T, ()>,
86 }
87
88 /// An owning iterator over a `BTreeSet`'s items.
89 ///
90 /// This structure is created by the `into_iter` method on [`BTreeSet`]
91 /// [`BTreeSet`] (provided by the `IntoIterator` trait).
92 ///
93 /// [`BTreeSet`]: struct.BTreeSet.html
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct IntoIter<T> {
96     iter: ::btree_map::IntoIter<T, ()>,
97 }
98
99 /// An iterator over a sub-range of `BTreeSet`'s items.
100 ///
101 /// This structure is created by the [`range`] method on [`BTreeSet`].
102 ///
103 /// [`BTreeSet`]: struct.BTreeSet.html
104 /// [`range`]: struct.BTreeSet.html#method.range
105 pub struct Range<'a, T: 'a> {
106     iter: ::btree_map::Range<'a, T, ()>,
107 }
108
109 /// A lazy iterator producing elements in the set difference (in-order).
110 ///
111 /// This structure is created by the [`difference`] method on [`BTreeSet`].
112 ///
113 /// [`BTreeSet`]: struct.BTreeSet.html
114 /// [`difference`]: struct.BTreeSet.html#method.difference
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub struct Difference<'a, T: 'a> {
117     a: Peekable<Iter<'a, T>>,
118     b: Peekable<Iter<'a, T>>,
119 }
120
121 /// A lazy iterator producing elements in the set symmetric difference (in-order).
122 ///
123 /// This structure is created by the [`symmetric_difference`] method on
124 /// [`BTreeSet`].
125 ///
126 /// [`BTreeSet`]: struct.BTreeSet.html
127 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct SymmetricDifference<'a, T: 'a> {
130     a: Peekable<Iter<'a, T>>,
131     b: Peekable<Iter<'a, T>>,
132 }
133
134 /// A lazy iterator producing elements in the set intersection (in-order).
135 ///
136 /// This structure is created by the [`intersection`] method on [`BTreeSet`].
137 ///
138 /// [`BTreeSet`]: struct.BTreeSet.html
139 /// [`intersection`]: struct.BTreeSet.html#method.intersection
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub struct Intersection<'a, T: 'a> {
142     a: Peekable<Iter<'a, T>>,
143     b: Peekable<Iter<'a, T>>,
144 }
145
146 /// A lazy iterator producing elements in the set union (in-order).
147 ///
148 /// This structure is created by the [`union`] method on [`BTreeSet`].
149 ///
150 /// [`BTreeSet`]: struct.BTreeSet.html
151 /// [`union`]: struct.BTreeSet.html#method.union
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub struct Union<'a, T: 'a> {
154     a: Peekable<Iter<'a, T>>,
155     b: Peekable<Iter<'a, T>>,
156 }
157
158 impl<T: Ord> BTreeSet<T> {
159     /// Makes a new `BTreeSet` with a reasonable choice of B.
160     ///
161     /// # Examples
162     ///
163     /// ```
164     /// # #![allow(unused_mut)]
165     /// use std::collections::BTreeSet;
166     ///
167     /// let mut set: BTreeSet<i32> = BTreeSet::new();
168     /// ```
169     #[stable(feature = "rust1", since = "1.0.0")]
170     pub fn new() -> BTreeSet<T> {
171         BTreeSet { map: BTreeMap::new() }
172     }
173 }
174
175 impl<T> BTreeSet<T> {
176     /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
177     ///
178     /// # Examples
179     ///
180     /// ```
181     /// use std::collections::BTreeSet;
182     ///
183     /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
184     /// let mut set_iter = set.iter();
185     /// assert_eq!(set_iter.next(), Some(&1));
186     /// assert_eq!(set_iter.next(), Some(&2));
187     /// assert_eq!(set_iter.next(), Some(&3));
188     /// assert_eq!(set_iter.next(), None);
189     /// ```
190     ///
191     /// Values returned by the iterator are returned in ascending order:
192     ///
193     /// ```
194     /// use std::collections::BTreeSet;
195     ///
196     /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
197     /// let mut set_iter = set.iter();
198     /// assert_eq!(set_iter.next(), Some(&1));
199     /// assert_eq!(set_iter.next(), Some(&2));
200     /// assert_eq!(set_iter.next(), Some(&3));
201     /// assert_eq!(set_iter.next(), None);
202     /// ```
203     #[stable(feature = "rust1", since = "1.0.0")]
204     pub fn iter(&self) -> Iter<T> {
205         Iter { iter: self.map.keys() }
206     }
207 }
208
209 impl<T: Ord> BTreeSet<T> {
210     /// Constructs a double-ended iterator over a sub-range of elements in the set.
211     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
212     /// yield elements from min (inclusive) to max (exclusive).
213     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
214     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
215     /// range from 4 to 10.
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// #![feature(btree_range, collections_bound)]
221     ///
222     /// use std::collections::BTreeSet;
223     /// use std::collections::Bound::Included;
224     ///
225     /// let mut set = BTreeSet::new();
226     /// set.insert(3);
227     /// set.insert(5);
228     /// set.insert(8);
229     /// for &elem in set.range((Included(&4), Included(&8))) {
230     ///     println!("{}", elem);
231     /// }
232     /// assert_eq!(Some(&5), set.range(4..).next());
233     /// ```
234     #[unstable(feature = "btree_range",
235                reason = "matches collection reform specification, waiting for dust to settle",
236                issue = "27787")]
237     pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
238         where K: Ord, T: Borrow<K>, R: RangeArgument<K>
239     {
240         Range { iter: self.map.range(range) }
241     }
242 }
243
244 impl<T: Ord> BTreeSet<T> {
245     /// Visits the values representing the difference, in ascending order.
246     ///
247     /// # Examples
248     ///
249     /// ```
250     /// use std::collections::BTreeSet;
251     ///
252     /// let mut a = BTreeSet::new();
253     /// a.insert(1);
254     /// a.insert(2);
255     ///
256     /// let mut b = BTreeSet::new();
257     /// b.insert(2);
258     /// b.insert(3);
259     ///
260     /// let diff: Vec<_> = a.difference(&b).cloned().collect();
261     /// assert_eq!(diff, [1]);
262     /// ```
263     #[stable(feature = "rust1", since = "1.0.0")]
264     pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
265         Difference {
266             a: self.iter().peekable(),
267             b: other.iter().peekable(),
268         }
269     }
270
271     /// Visits the values representing the symmetric difference, in ascending order.
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// use std::collections::BTreeSet;
277     ///
278     /// let mut a = BTreeSet::new();
279     /// a.insert(1);
280     /// a.insert(2);
281     ///
282     /// let mut b = BTreeSet::new();
283     /// b.insert(2);
284     /// b.insert(3);
285     ///
286     /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
287     /// assert_eq!(sym_diff, [1, 3]);
288     /// ```
289     #[stable(feature = "rust1", since = "1.0.0")]
290     pub fn symmetric_difference<'a>(&'a self,
291                                     other: &'a BTreeSet<T>)
292                                     -> SymmetricDifference<'a, T> {
293         SymmetricDifference {
294             a: self.iter().peekable(),
295             b: other.iter().peekable(),
296         }
297     }
298
299     /// Visits the values representing the intersection, in ascending order.
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use std::collections::BTreeSet;
305     ///
306     /// let mut a = BTreeSet::new();
307     /// a.insert(1);
308     /// a.insert(2);
309     ///
310     /// let mut b = BTreeSet::new();
311     /// b.insert(2);
312     /// b.insert(3);
313     ///
314     /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
315     /// assert_eq!(intersection, [2]);
316     /// ```
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
319         Intersection {
320             a: self.iter().peekable(),
321             b: other.iter().peekable(),
322         }
323     }
324
325     /// Visits the values representing the union, in ascending order.
326     ///
327     /// # Examples
328     ///
329     /// ```
330     /// use std::collections::BTreeSet;
331     ///
332     /// let mut a = BTreeSet::new();
333     /// a.insert(1);
334     ///
335     /// let mut b = BTreeSet::new();
336     /// b.insert(2);
337     ///
338     /// let union: Vec<_> = a.union(&b).cloned().collect();
339     /// assert_eq!(union, [1, 2]);
340     /// ```
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
343         Union {
344             a: self.iter().peekable(),
345             b: other.iter().peekable(),
346         }
347     }
348
349     /// Returns the number of elements in the set.
350     ///
351     /// # Examples
352     ///
353     /// ```
354     /// use std::collections::BTreeSet;
355     ///
356     /// let mut v = BTreeSet::new();
357     /// assert_eq!(v.len(), 0);
358     /// v.insert(1);
359     /// assert_eq!(v.len(), 1);
360     /// ```
361     #[stable(feature = "rust1", since = "1.0.0")]
362     pub fn len(&self) -> usize {
363         self.map.len()
364     }
365
366     /// Returns true if the set contains no elements.
367     ///
368     /// # Examples
369     ///
370     /// ```
371     /// use std::collections::BTreeSet;
372     ///
373     /// let mut v = BTreeSet::new();
374     /// assert!(v.is_empty());
375     /// v.insert(1);
376     /// assert!(!v.is_empty());
377     /// ```
378     #[stable(feature = "rust1", since = "1.0.0")]
379     pub fn is_empty(&self) -> bool {
380         self.len() == 0
381     }
382
383     /// Clears the set, removing all values.
384     ///
385     /// # Examples
386     ///
387     /// ```
388     /// use std::collections::BTreeSet;
389     ///
390     /// let mut v = BTreeSet::new();
391     /// v.insert(1);
392     /// v.clear();
393     /// assert!(v.is_empty());
394     /// ```
395     #[stable(feature = "rust1", since = "1.0.0")]
396     pub fn clear(&mut self) {
397         self.map.clear()
398     }
399
400     /// Returns `true` if the set contains a value.
401     ///
402     /// The value may be any borrowed form of the set's value type,
403     /// but the ordering on the borrowed form *must* match the
404     /// ordering on the value type.
405     ///
406     /// # Examples
407     ///
408     /// ```
409     /// use std::collections::BTreeSet;
410     ///
411     /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
412     /// assert_eq!(set.contains(&1), true);
413     /// assert_eq!(set.contains(&4), false);
414     /// ```
415     #[stable(feature = "rust1", since = "1.0.0")]
416     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
417         where T: Borrow<Q>,
418               Q: Ord
419     {
420         self.map.contains_key(value)
421     }
422
423     /// Returns a reference to the value in the set, if any, that is equal to the given value.
424     ///
425     /// The value may be any borrowed form of the set's value type,
426     /// but the ordering on the borrowed form *must* match the
427     /// ordering on the value type.
428     #[stable(feature = "set_recovery", since = "1.9.0")]
429     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
430         where T: Borrow<Q>,
431               Q: Ord
432     {
433         Recover::get(&self.map, value)
434     }
435
436     /// Returns `true` if the set has no elements in common with `other`.
437     /// This is equivalent to checking for an empty intersection.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// use std::collections::BTreeSet;
443     ///
444     /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
445     /// let mut b = BTreeSet::new();
446     ///
447     /// assert_eq!(a.is_disjoint(&b), true);
448     /// b.insert(4);
449     /// assert_eq!(a.is_disjoint(&b), true);
450     /// b.insert(1);
451     /// assert_eq!(a.is_disjoint(&b), false);
452     /// ```
453     #[stable(feature = "rust1", since = "1.0.0")]
454     pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
455         self.intersection(other).next().is_none()
456     }
457
458     /// Returns `true` if the set is a subset of another.
459     ///
460     /// # Examples
461     ///
462     /// ```
463     /// use std::collections::BTreeSet;
464     ///
465     /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
466     /// let mut set = BTreeSet::new();
467     ///
468     /// assert_eq!(set.is_subset(&sup), true);
469     /// set.insert(2);
470     /// assert_eq!(set.is_subset(&sup), true);
471     /// set.insert(4);
472     /// assert_eq!(set.is_subset(&sup), false);
473     /// ```
474     #[stable(feature = "rust1", since = "1.0.0")]
475     pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
476         // Stolen from TreeMap
477         let mut x = self.iter();
478         let mut y = other.iter();
479         let mut a = x.next();
480         let mut b = y.next();
481         while a.is_some() {
482             if b.is_none() {
483                 return false;
484             }
485
486             let a1 = a.unwrap();
487             let b1 = b.unwrap();
488
489             match b1.cmp(a1) {
490                 Less => (),
491                 Greater => return false,
492                 Equal => a = x.next(),
493             }
494
495             b = y.next();
496         }
497         true
498     }
499
500     /// Returns `true` if the set is a superset of another.
501     ///
502     /// # Examples
503     ///
504     /// ```
505     /// use std::collections::BTreeSet;
506     ///
507     /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
508     /// let mut set = BTreeSet::new();
509     ///
510     /// assert_eq!(set.is_superset(&sub), false);
511     ///
512     /// set.insert(0);
513     /// set.insert(1);
514     /// assert_eq!(set.is_superset(&sub), false);
515     ///
516     /// set.insert(2);
517     /// assert_eq!(set.is_superset(&sub), true);
518     /// ```
519     #[stable(feature = "rust1", since = "1.0.0")]
520     pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
521         other.is_subset(self)
522     }
523
524     /// Adds a value to the set.
525     ///
526     /// If the set did not have this value present, `true` is returned.
527     ///
528     /// If the set did have this value present, `false` is returned, and the
529     /// entry is not updated. See the [module-level documentation] for more.
530     ///
531     /// [module-level documentation]: index.html#insert-and-complex-keys
532     ///
533     /// # Examples
534     ///
535     /// ```
536     /// use std::collections::BTreeSet;
537     ///
538     /// let mut set = BTreeSet::new();
539     ///
540     /// assert_eq!(set.insert(2), true);
541     /// assert_eq!(set.insert(2), false);
542     /// assert_eq!(set.len(), 1);
543     /// ```
544     #[stable(feature = "rust1", since = "1.0.0")]
545     pub fn insert(&mut self, value: T) -> bool {
546         self.map.insert(value, ()).is_none()
547     }
548
549     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
550     /// one. Returns the replaced value.
551     #[stable(feature = "set_recovery", since = "1.9.0")]
552     pub fn replace(&mut self, value: T) -> Option<T> {
553         Recover::replace(&mut self.map, value)
554     }
555
556     /// Removes a value from the set. Returns `true` if the value was
557     /// present in the set.
558     ///
559     /// The value may be any borrowed form of the set's value type,
560     /// but the ordering on the borrowed form *must* match the
561     /// ordering on the value type.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// use std::collections::BTreeSet;
567     ///
568     /// let mut set = BTreeSet::new();
569     ///
570     /// set.insert(2);
571     /// assert_eq!(set.remove(&2), true);
572     /// assert_eq!(set.remove(&2), false);
573     /// ```
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
576         where T: Borrow<Q>,
577               Q: Ord
578     {
579         self.map.remove(value).is_some()
580     }
581
582     /// Removes and returns the value in the set, if any, that is equal to the given one.
583     ///
584     /// The value may be any borrowed form of the set's value type,
585     /// but the ordering on the borrowed form *must* match the
586     /// ordering on the value type.
587     #[stable(feature = "set_recovery", since = "1.9.0")]
588     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
589         where T: Borrow<Q>,
590               Q: Ord
591     {
592         Recover::take(&mut self.map, value)
593     }
594
595     /// Moves all elements from `other` into `Self`, leaving `other` empty.
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// use std::collections::BTreeSet;
601     ///
602     /// let mut a = BTreeSet::new();
603     /// a.insert(1);
604     /// a.insert(2);
605     /// a.insert(3);
606     ///
607     /// let mut b = BTreeSet::new();
608     /// b.insert(3);
609     /// b.insert(4);
610     /// b.insert(5);
611     ///
612     /// a.append(&mut b);
613     ///
614     /// assert_eq!(a.len(), 5);
615     /// assert_eq!(b.len(), 0);
616     ///
617     /// assert!(a.contains(&1));
618     /// assert!(a.contains(&2));
619     /// assert!(a.contains(&3));
620     /// assert!(a.contains(&4));
621     /// assert!(a.contains(&5));
622     /// ```
623     #[stable(feature = "btree_append", since = "1.11.0")]
624     pub fn append(&mut self, other: &mut Self) {
625         self.map.append(&mut other.map);
626     }
627
628     /// Splits the collection into two at the given key. Returns everything after the given key,
629     /// including the key.
630     ///
631     /// # Examples
632     ///
633     /// Basic usage:
634     ///
635     /// ```
636     /// use std::collections::BTreeMap;
637     ///
638     /// let mut a = BTreeMap::new();
639     /// a.insert(1, "a");
640     /// a.insert(2, "b");
641     /// a.insert(3, "c");
642     /// a.insert(17, "d");
643     /// a.insert(41, "e");
644     ///
645     /// let b = a.split_off(&3);
646     ///
647     /// assert_eq!(a.len(), 2);
648     /// assert_eq!(b.len(), 3);
649     ///
650     /// assert_eq!(a[&1], "a");
651     /// assert_eq!(a[&2], "b");
652     ///
653     /// assert_eq!(b[&3], "c");
654     /// assert_eq!(b[&17], "d");
655     /// assert_eq!(b[&41], "e");
656     /// ```
657     #[stable(feature = "btree_split_off", since = "1.11.0")]
658     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
659         BTreeSet { map: self.map.split_off(key) }
660     }
661 }
662
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
665     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
666         let mut set = BTreeSet::new();
667         set.extend(iter);
668         set
669     }
670 }
671
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T> IntoIterator for BTreeSet<T> {
674     type Item = T;
675     type IntoIter = IntoIter<T>;
676
677     /// Gets an iterator for moving out the BtreeSet's contents.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// use std::collections::BTreeSet;
683     ///
684     /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
685     ///
686     /// let v: Vec<_> = set.into_iter().collect();
687     /// assert_eq!(v, [1, 2, 3, 4]);
688     /// ```
689     fn into_iter(self) -> IntoIter<T> {
690         IntoIter { iter: self.map.into_iter() }
691     }
692 }
693
694 #[stable(feature = "rust1", since = "1.0.0")]
695 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
696     type Item = &'a T;
697     type IntoIter = Iter<'a, T>;
698
699     fn into_iter(self) -> Iter<'a, T> {
700         self.iter()
701     }
702 }
703
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl<T: Ord> Extend<T> for BTreeSet<T> {
706     #[inline]
707     fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
708         for elem in iter {
709             self.insert(elem);
710         }
711     }
712 }
713
714 #[stable(feature = "extend_ref", since = "1.2.0")]
715 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
716     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
717         self.extend(iter.into_iter().cloned());
718     }
719 }
720
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl<T: Ord> Default for BTreeSet<T> {
723     /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
724     fn default() -> BTreeSet<T> {
725         BTreeSet::new()
726     }
727 }
728
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
731     type Output = BTreeSet<T>;
732
733     /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// use std::collections::BTreeSet;
739     ///
740     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
741     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
742     ///
743     /// let result = &a - &b;
744     /// let result_vec: Vec<_> = result.into_iter().collect();
745     /// assert_eq!(result_vec, [1, 2]);
746     /// ```
747     fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
748         self.difference(rhs).cloned().collect()
749     }
750 }
751
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
754     type Output = BTreeSet<T>;
755
756     /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
757     ///
758     /// # Examples
759     ///
760     /// ```
761     /// use std::collections::BTreeSet;
762     ///
763     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
764     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
765     ///
766     /// let result = &a ^ &b;
767     /// let result_vec: Vec<_> = result.into_iter().collect();
768     /// assert_eq!(result_vec, [1, 4]);
769     /// ```
770     fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
771         self.symmetric_difference(rhs).cloned().collect()
772     }
773 }
774
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
777     type Output = BTreeSet<T>;
778
779     /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
780     ///
781     /// # Examples
782     ///
783     /// ```
784     /// use std::collections::BTreeSet;
785     ///
786     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
787     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
788     ///
789     /// let result = &a & &b;
790     /// let result_vec: Vec<_> = result.into_iter().collect();
791     /// assert_eq!(result_vec, [2, 3]);
792     /// ```
793     fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
794         self.intersection(rhs).cloned().collect()
795     }
796 }
797
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
800     type Output = BTreeSet<T>;
801
802     /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
803     ///
804     /// # Examples
805     ///
806     /// ```
807     /// use std::collections::BTreeSet;
808     ///
809     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
810     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
811     ///
812     /// let result = &a | &b;
813     /// let result_vec: Vec<_> = result.into_iter().collect();
814     /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
815     /// ```
816     fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
817         self.union(rhs).cloned().collect()
818     }
819 }
820
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<T: Debug> Debug for BTreeSet<T> {
823     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
824         f.debug_set().entries(self.iter()).finish()
825     }
826 }
827
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<'a, T> Clone for Iter<'a, T> {
830     fn clone(&self) -> Iter<'a, T> {
831         Iter { iter: self.iter.clone() }
832     }
833 }
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<'a, T> Iterator for Iter<'a, T> {
836     type Item = &'a T;
837
838     fn next(&mut self) -> Option<&'a T> {
839         self.iter.next()
840     }
841     fn size_hint(&self) -> (usize, Option<usize>) {
842         self.iter.size_hint()
843     }
844 }
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
847     fn next_back(&mut self) -> Option<&'a T> {
848         self.iter.next_back()
849     }
850 }
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
853     fn len(&self) -> usize { self.iter.len() }
854 }
855
856 #[unstable(feature = "fused", issue = "35602")]
857 impl<'a, T> FusedIterator for Iter<'a, T> {}
858
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<T> Iterator for IntoIter<T> {
861     type Item = T;
862
863     fn next(&mut self) -> Option<T> {
864         self.iter.next().map(|(k, _)| k)
865     }
866     fn size_hint(&self) -> (usize, Option<usize>) {
867         self.iter.size_hint()
868     }
869 }
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl<T> DoubleEndedIterator for IntoIter<T> {
872     fn next_back(&mut self) -> Option<T> {
873         self.iter.next_back().map(|(k, _)| k)
874     }
875 }
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<T> ExactSizeIterator for IntoIter<T> {
878     fn len(&self) -> usize { self.iter.len() }
879 }
880
881 #[unstable(feature = "fused", issue = "35602")]
882 impl<T> FusedIterator for IntoIter<T> {}
883
884 impl<'a, T> Clone for Range<'a, T> {
885     fn clone(&self) -> Range<'a, T> {
886         Range { iter: self.iter.clone() }
887     }
888 }
889 impl<'a, T> Iterator for Range<'a, T> {
890     type Item = &'a T;
891
892     fn next(&mut self) -> Option<&'a T> {
893         self.iter.next().map(|(k, _)| k)
894     }
895 }
896 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
897     fn next_back(&mut self) -> Option<&'a T> {
898         self.iter.next_back().map(|(k, _)| k)
899     }
900 }
901
902 #[unstable(feature = "fused", issue = "35602")]
903 impl<'a, T> FusedIterator for Range<'a, T> {}
904
905 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
906 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
907     match (x, y) {
908         (None, _) => short,
909         (_, None) => long,
910         (Some(x1), Some(y1)) => x1.cmp(y1),
911     }
912 }
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<'a, T> Clone for Difference<'a, T> {
916     fn clone(&self) -> Difference<'a, T> {
917         Difference {
918             a: self.a.clone(),
919             b: self.b.clone(),
920         }
921     }
922 }
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<'a, T: Ord> Iterator for Difference<'a, T> {
925     type Item = &'a T;
926
927     fn next(&mut self) -> Option<&'a T> {
928         loop {
929             match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
930                 Less => return self.a.next(),
931                 Equal => {
932                     self.a.next();
933                     self.b.next();
934                 }
935                 Greater => {
936                     self.b.next();
937                 }
938             }
939         }
940     }
941
942     fn size_hint(&self) -> (usize, Option<usize>) {
943         let a_len = self.a.len();
944         let b_len = self.b.len();
945         (a_len.saturating_sub(b_len), Some(a_len))
946     }
947 }
948
949 #[unstable(feature = "fused", issue = "35602")]
950 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
951
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T> Clone for SymmetricDifference<'a, T> {
954     fn clone(&self) -> SymmetricDifference<'a, T> {
955         SymmetricDifference {
956             a: self.a.clone(),
957             b: self.b.clone(),
958         }
959     }
960 }
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
963     type Item = &'a T;
964
965     fn next(&mut self) -> Option<&'a T> {
966         loop {
967             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
968                 Less => return self.a.next(),
969                 Equal => {
970                     self.a.next();
971                     self.b.next();
972                 }
973                 Greater => return self.b.next(),
974             }
975         }
976     }
977
978     fn size_hint(&self) -> (usize, Option<usize>) {
979         (0, Some(self.a.len() + self.b.len()))
980     }
981 }
982
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
985
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<'a, T> Clone for Intersection<'a, T> {
988     fn clone(&self) -> Intersection<'a, T> {
989         Intersection {
990             a: self.a.clone(),
991             b: self.b.clone(),
992         }
993     }
994 }
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
997     type Item = &'a T;
998
999     fn next(&mut self) -> Option<&'a T> {
1000         loop {
1001             let o_cmp = match (self.a.peek(), self.b.peek()) {
1002                 (None, _) => None,
1003                 (_, None) => None,
1004                 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
1005             };
1006             match o_cmp {
1007                 None => return None,
1008                 Some(Less) => {
1009                     self.a.next();
1010                 }
1011                 Some(Equal) => {
1012                     self.b.next();
1013                     return self.a.next();
1014                 }
1015                 Some(Greater) => {
1016                     self.b.next();
1017                 }
1018             }
1019         }
1020     }
1021
1022     fn size_hint(&self) -> (usize, Option<usize>) {
1023         (0, Some(min(self.a.len(), self.b.len())))
1024     }
1025 }
1026
1027 #[unstable(feature = "fused", issue = "35602")]
1028 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1029
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'a, T> Clone for Union<'a, T> {
1032     fn clone(&self) -> Union<'a, T> {
1033         Union {
1034             a: self.a.clone(),
1035             b: self.b.clone(),
1036         }
1037     }
1038 }
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<'a, T: Ord> Iterator for Union<'a, T> {
1041     type Item = &'a T;
1042
1043     fn next(&mut self) -> Option<&'a T> {
1044         loop {
1045             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1046                 Less => return self.a.next(),
1047                 Equal => {
1048                     self.b.next();
1049                     return self.a.next();
1050                 }
1051                 Greater => return self.b.next(),
1052             }
1053         }
1054     }
1055
1056     fn size_hint(&self) -> (usize, Option<usize>) {
1057         let a_len = self.a.len();
1058         let b_len = self.b.len();
1059         (max(a_len, b_len), Some(a_len + b_len))
1060     }
1061 }
1062
1063 #[unstable(feature = "fused", issue = "35602")]
1064 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}