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