]> git.lizzy.rs Git - rust.git/blob - src/liballoc/btree/set.rs
Rollup merge of #47216 - SergioBenitez:doc-fix, r=Mark-Simulacrum
[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     #[stable(feature = "set_recovery", since = "1.9.0")]
419     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
420         where T: Borrow<Q>,
421               Q: Ord
422     {
423         Recover::get(&self.map, value)
424     }
425
426     /// Returns `true` if `self` has no elements in common with `other`.
427     /// This is equivalent to checking for an empty intersection.
428     ///
429     /// # Examples
430     ///
431     /// ```
432     /// use std::collections::BTreeSet;
433     ///
434     /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
435     /// let mut b = BTreeSet::new();
436     ///
437     /// assert_eq!(a.is_disjoint(&b), true);
438     /// b.insert(4);
439     /// assert_eq!(a.is_disjoint(&b), true);
440     /// b.insert(1);
441     /// assert_eq!(a.is_disjoint(&b), false);
442     /// ```
443     #[stable(feature = "rust1", since = "1.0.0")]
444     pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
445         self.intersection(other).next().is_none()
446     }
447
448     /// Returns `true` if the set is a subset of another,
449     /// i.e. `other` contains at least all the values in `self`.
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// use std::collections::BTreeSet;
455     ///
456     /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
457     /// let mut set = BTreeSet::new();
458     ///
459     /// assert_eq!(set.is_subset(&sup), true);
460     /// set.insert(2);
461     /// assert_eq!(set.is_subset(&sup), true);
462     /// set.insert(4);
463     /// assert_eq!(set.is_subset(&sup), false);
464     /// ```
465     #[stable(feature = "rust1", since = "1.0.0")]
466     pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
467         // Stolen from TreeMap
468         let mut x = self.iter();
469         let mut y = other.iter();
470         let mut a = x.next();
471         let mut b = y.next();
472         while a.is_some() {
473             if b.is_none() {
474                 return false;
475             }
476
477             let a1 = a.unwrap();
478             let b1 = b.unwrap();
479
480             match b1.cmp(a1) {
481                 Less => (),
482                 Greater => return false,
483                 Equal => a = x.next(),
484             }
485
486             b = y.next();
487         }
488         true
489     }
490
491     /// Returns `true` if the set is a superset of another,
492     /// i.e. `self` contains at least all the values in `other`.
493     ///
494     /// # Examples
495     ///
496     /// ```
497     /// use std::collections::BTreeSet;
498     ///
499     /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
500     /// let mut set = BTreeSet::new();
501     ///
502     /// assert_eq!(set.is_superset(&sub), false);
503     ///
504     /// set.insert(0);
505     /// set.insert(1);
506     /// assert_eq!(set.is_superset(&sub), false);
507     ///
508     /// set.insert(2);
509     /// assert_eq!(set.is_superset(&sub), true);
510     /// ```
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
513         other.is_subset(self)
514     }
515
516     /// Adds a value to the set.
517     ///
518     /// If the set did not have this value present, `true` is returned.
519     ///
520     /// If the set did have this value present, `false` is returned, and the
521     /// entry is not updated. See the [module-level documentation] for more.
522     ///
523     /// [module-level documentation]: index.html#insert-and-complex-keys
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// use std::collections::BTreeSet;
529     ///
530     /// let mut set = BTreeSet::new();
531     ///
532     /// assert_eq!(set.insert(2), true);
533     /// assert_eq!(set.insert(2), false);
534     /// assert_eq!(set.len(), 1);
535     /// ```
536     #[stable(feature = "rust1", since = "1.0.0")]
537     pub fn insert(&mut self, value: T) -> bool {
538         self.map.insert(value, ()).is_none()
539     }
540
541     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
542     /// one. Returns the replaced value.
543     #[stable(feature = "set_recovery", since = "1.9.0")]
544     pub fn replace(&mut self, value: T) -> Option<T> {
545         Recover::replace(&mut self.map, value)
546     }
547
548     /// Removes a value from the set. Returns `true` if the value was
549     /// present in the set.
550     ///
551     /// The value may be any borrowed form of the set's value type,
552     /// but the ordering on the borrowed form *must* match the
553     /// ordering on the value type.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// use std::collections::BTreeSet;
559     ///
560     /// let mut set = BTreeSet::new();
561     ///
562     /// set.insert(2);
563     /// assert_eq!(set.remove(&2), true);
564     /// assert_eq!(set.remove(&2), false);
565     /// ```
566     #[stable(feature = "rust1", since = "1.0.0")]
567     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
568         where T: Borrow<Q>,
569               Q: Ord
570     {
571         self.map.remove(value).is_some()
572     }
573
574     /// Removes and returns the value in the set, if any, that is equal to the given one.
575     ///
576     /// The value may be any borrowed form of the set's value type,
577     /// but the ordering on the borrowed form *must* match the
578     /// ordering on the value type.
579     #[stable(feature = "set_recovery", since = "1.9.0")]
580     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
581         where T: Borrow<Q>,
582               Q: Ord
583     {
584         Recover::take(&mut self.map, value)
585     }
586
587     /// Moves all elements from `other` into `Self`, leaving `other` empty.
588     ///
589     /// # Examples
590     ///
591     /// ```
592     /// use std::collections::BTreeSet;
593     ///
594     /// let mut a = BTreeSet::new();
595     /// a.insert(1);
596     /// a.insert(2);
597     /// a.insert(3);
598     ///
599     /// let mut b = BTreeSet::new();
600     /// b.insert(3);
601     /// b.insert(4);
602     /// b.insert(5);
603     ///
604     /// a.append(&mut b);
605     ///
606     /// assert_eq!(a.len(), 5);
607     /// assert_eq!(b.len(), 0);
608     ///
609     /// assert!(a.contains(&1));
610     /// assert!(a.contains(&2));
611     /// assert!(a.contains(&3));
612     /// assert!(a.contains(&4));
613     /// assert!(a.contains(&5));
614     /// ```
615     #[stable(feature = "btree_append", since = "1.11.0")]
616     pub fn append(&mut self, other: &mut Self) {
617         self.map.append(&mut other.map);
618     }
619
620     /// Splits the collection into two at the given key. Returns everything after the given key,
621     /// including the key.
622     ///
623     /// # Examples
624     ///
625     /// Basic usage:
626     ///
627     /// ```
628     /// use std::collections::BTreeMap;
629     ///
630     /// let mut a = BTreeMap::new();
631     /// a.insert(1, "a");
632     /// a.insert(2, "b");
633     /// a.insert(3, "c");
634     /// a.insert(17, "d");
635     /// a.insert(41, "e");
636     ///
637     /// let b = a.split_off(&3);
638     ///
639     /// assert_eq!(a.len(), 2);
640     /// assert_eq!(b.len(), 3);
641     ///
642     /// assert_eq!(a[&1], "a");
643     /// assert_eq!(a[&2], "b");
644     ///
645     /// assert_eq!(b[&3], "c");
646     /// assert_eq!(b[&17], "d");
647     /// assert_eq!(b[&41], "e");
648     /// ```
649     #[stable(feature = "btree_split_off", since = "1.11.0")]
650     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
651         BTreeSet { map: self.map.split_off(key) }
652     }
653 }
654
655 impl<T> BTreeSet<T> {
656     /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// use std::collections::BTreeSet;
662     ///
663     /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
664     /// let mut set_iter = set.iter();
665     /// assert_eq!(set_iter.next(), Some(&1));
666     /// assert_eq!(set_iter.next(), Some(&2));
667     /// assert_eq!(set_iter.next(), Some(&3));
668     /// assert_eq!(set_iter.next(), None);
669     /// ```
670     ///
671     /// Values returned by the iterator are returned in ascending order:
672     ///
673     /// ```
674     /// use std::collections::BTreeSet;
675     ///
676     /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
677     /// let mut set_iter = set.iter();
678     /// assert_eq!(set_iter.next(), Some(&1));
679     /// assert_eq!(set_iter.next(), Some(&2));
680     /// assert_eq!(set_iter.next(), Some(&3));
681     /// assert_eq!(set_iter.next(), None);
682     /// ```
683     #[stable(feature = "rust1", since = "1.0.0")]
684     pub fn iter(&self) -> Iter<T> {
685         Iter { iter: self.map.keys() }
686     }
687
688     /// Returns the number of elements in the set.
689     ///
690     /// # Examples
691     ///
692     /// ```
693     /// use std::collections::BTreeSet;
694     ///
695     /// let mut v = BTreeSet::new();
696     /// assert_eq!(v.len(), 0);
697     /// v.insert(1);
698     /// assert_eq!(v.len(), 1);
699     /// ```
700     #[stable(feature = "rust1", since = "1.0.0")]
701     pub fn len(&self) -> usize {
702         self.map.len()
703     }
704
705     /// Returns `true` if the set contains no elements.
706     ///
707     /// # Examples
708     ///
709     /// ```
710     /// use std::collections::BTreeSet;
711     ///
712     /// let mut v = BTreeSet::new();
713     /// assert!(v.is_empty());
714     /// v.insert(1);
715     /// assert!(!v.is_empty());
716     /// ```
717     #[stable(feature = "rust1", since = "1.0.0")]
718     pub fn is_empty(&self) -> bool {
719         self.len() == 0
720     }
721 }
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
725     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
726         let mut set = BTreeSet::new();
727         set.extend(iter);
728         set
729     }
730 }
731
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl<T> IntoIterator for BTreeSet<T> {
734     type Item = T;
735     type IntoIter = IntoIter<T>;
736
737     /// Gets an iterator for moving out the `BTreeSet`'s contents.
738     ///
739     /// # Examples
740     ///
741     /// ```
742     /// use std::collections::BTreeSet;
743     ///
744     /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
745     ///
746     /// let v: Vec<_> = set.into_iter().collect();
747     /// assert_eq!(v, [1, 2, 3, 4]);
748     /// ```
749     fn into_iter(self) -> IntoIter<T> {
750         IntoIter { iter: self.map.into_iter() }
751     }
752 }
753
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
756     type Item = &'a T;
757     type IntoIter = Iter<'a, T>;
758
759     fn into_iter(self) -> Iter<'a, T> {
760         self.iter()
761     }
762 }
763
764 #[stable(feature = "rust1", since = "1.0.0")]
765 impl<T: Ord> Extend<T> for BTreeSet<T> {
766     #[inline]
767     fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
768         for elem in iter {
769             self.insert(elem);
770         }
771     }
772 }
773
774 #[stable(feature = "extend_ref", since = "1.2.0")]
775 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
776     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
777         self.extend(iter.into_iter().cloned());
778     }
779 }
780
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T: Ord> Default for BTreeSet<T> {
783     /// Makes an empty `BTreeSet<T>` with a reasonable choice of B.
784     fn default() -> BTreeSet<T> {
785         BTreeSet::new()
786     }
787 }
788
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
791     type Output = BTreeSet<T>;
792
793     /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
794     ///
795     /// # Examples
796     ///
797     /// ```
798     /// use std::collections::BTreeSet;
799     ///
800     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
801     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
802     ///
803     /// let result = &a - &b;
804     /// let result_vec: Vec<_> = result.into_iter().collect();
805     /// assert_eq!(result_vec, [1, 2]);
806     /// ```
807     fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
808         self.difference(rhs).cloned().collect()
809     }
810 }
811
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
814     type Output = BTreeSet<T>;
815
816     /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
817     ///
818     /// # Examples
819     ///
820     /// ```
821     /// use std::collections::BTreeSet;
822     ///
823     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
824     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
825     ///
826     /// let result = &a ^ &b;
827     /// let result_vec: Vec<_> = result.into_iter().collect();
828     /// assert_eq!(result_vec, [1, 4]);
829     /// ```
830     fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
831         self.symmetric_difference(rhs).cloned().collect()
832     }
833 }
834
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
837     type Output = BTreeSet<T>;
838
839     /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
840     ///
841     /// # Examples
842     ///
843     /// ```
844     /// use std::collections::BTreeSet;
845     ///
846     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
847     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
848     ///
849     /// let result = &a & &b;
850     /// let result_vec: Vec<_> = result.into_iter().collect();
851     /// assert_eq!(result_vec, [2, 3]);
852     /// ```
853     fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
854         self.intersection(rhs).cloned().collect()
855     }
856 }
857
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
860     type Output = BTreeSet<T>;
861
862     /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
863     ///
864     /// # Examples
865     ///
866     /// ```
867     /// use std::collections::BTreeSet;
868     ///
869     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
870     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
871     ///
872     /// let result = &a | &b;
873     /// let result_vec: Vec<_> = result.into_iter().collect();
874     /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
875     /// ```
876     fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
877         self.union(rhs).cloned().collect()
878     }
879 }
880
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<T: Debug> Debug for BTreeSet<T> {
883     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
884         f.debug_set().entries(self.iter()).finish()
885     }
886 }
887
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<'a, T> Clone for Iter<'a, T> {
890     fn clone(&self) -> Iter<'a, T> {
891         Iter { iter: self.iter.clone() }
892     }
893 }
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<'a, T> Iterator for Iter<'a, T> {
896     type Item = &'a T;
897
898     fn next(&mut self) -> Option<&'a T> {
899         self.iter.next()
900     }
901     fn size_hint(&self) -> (usize, Option<usize>) {
902         self.iter.size_hint()
903     }
904 }
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
907     fn next_back(&mut self) -> Option<&'a T> {
908         self.iter.next_back()
909     }
910 }
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
913     fn len(&self) -> usize { self.iter.len() }
914 }
915
916 #[unstable(feature = "fused", issue = "35602")]
917 impl<'a, T> FusedIterator for Iter<'a, T> {}
918
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl<T> Iterator for IntoIter<T> {
921     type Item = T;
922
923     fn next(&mut self) -> Option<T> {
924         self.iter.next().map(|(k, _)| k)
925     }
926     fn size_hint(&self) -> (usize, Option<usize>) {
927         self.iter.size_hint()
928     }
929 }
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<T> DoubleEndedIterator for IntoIter<T> {
932     fn next_back(&mut self) -> Option<T> {
933         self.iter.next_back().map(|(k, _)| k)
934     }
935 }
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T> ExactSizeIterator for IntoIter<T> {
938     fn len(&self) -> usize { self.iter.len() }
939 }
940
941 #[unstable(feature = "fused", issue = "35602")]
942 impl<T> FusedIterator for IntoIter<T> {}
943
944 #[stable(feature = "btree_range", since = "1.17.0")]
945 impl<'a, T> Clone for Range<'a, T> {
946     fn clone(&self) -> Range<'a, T> {
947         Range { iter: self.iter.clone() }
948     }
949 }
950
951 #[stable(feature = "btree_range", since = "1.17.0")]
952 impl<'a, T> Iterator for Range<'a, T> {
953     type Item = &'a T;
954
955     fn next(&mut self) -> Option<&'a T> {
956         self.iter.next().map(|(k, _)| k)
957     }
958 }
959
960 #[stable(feature = "btree_range", since = "1.17.0")]
961 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
962     fn next_back(&mut self) -> Option<&'a T> {
963         self.iter.next_back().map(|(k, _)| k)
964     }
965 }
966
967 #[unstable(feature = "fused", issue = "35602")]
968 impl<'a, T> FusedIterator for Range<'a, T> {}
969
970 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
971 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
972     match (x, y) {
973         (None, _) => short,
974         (_, None) => long,
975         (Some(x1), Some(y1)) => x1.cmp(y1),
976     }
977 }
978
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<'a, T> Clone for Difference<'a, T> {
981     fn clone(&self) -> Difference<'a, T> {
982         Difference {
983             a: self.a.clone(),
984             b: self.b.clone(),
985         }
986     }
987 }
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<'a, T: Ord> Iterator for Difference<'a, T> {
990     type Item = &'a T;
991
992     fn next(&mut self) -> Option<&'a T> {
993         loop {
994             match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
995                 Less => return self.a.next(),
996                 Equal => {
997                     self.a.next();
998                     self.b.next();
999                 }
1000                 Greater => {
1001                     self.b.next();
1002                 }
1003             }
1004         }
1005     }
1006
1007     fn size_hint(&self) -> (usize, Option<usize>) {
1008         let a_len = self.a.len();
1009         let b_len = self.b.len();
1010         (a_len.saturating_sub(b_len), Some(a_len))
1011     }
1012 }
1013
1014 #[unstable(feature = "fused", issue = "35602")]
1015 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1016
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1019     fn clone(&self) -> SymmetricDifference<'a, T> {
1020         SymmetricDifference {
1021             a: self.a.clone(),
1022             b: self.b.clone(),
1023         }
1024     }
1025 }
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
1028     type Item = &'a T;
1029
1030     fn next(&mut self) -> Option<&'a T> {
1031         loop {
1032             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1033                 Less => return self.a.next(),
1034                 Equal => {
1035                     self.a.next();
1036                     self.b.next();
1037                 }
1038                 Greater => return self.b.next(),
1039             }
1040         }
1041     }
1042
1043     fn size_hint(&self) -> (usize, Option<usize>) {
1044         (0, Some(self.a.len() + self.b.len()))
1045     }
1046 }
1047
1048 #[unstable(feature = "fused", issue = "35602")]
1049 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1050
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, T> Clone for Intersection<'a, T> {
1053     fn clone(&self) -> Intersection<'a, T> {
1054         Intersection {
1055             a: self.a.clone(),
1056             b: self.b.clone(),
1057         }
1058     }
1059 }
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1062     type Item = &'a T;
1063
1064     fn next(&mut self) -> Option<&'a T> {
1065         loop {
1066             match Ord::cmp(self.a.peek()?, self.b.peek()?) {
1067                 Less => {
1068                     self.a.next();
1069                 }
1070                 Equal => {
1071                     self.b.next();
1072                     return self.a.next();
1073                 }
1074                 Greater => {
1075                     self.b.next();
1076                 }
1077             }
1078         }
1079     }
1080
1081     fn size_hint(&self) -> (usize, Option<usize>) {
1082         (0, Some(min(self.a.len(), self.b.len())))
1083     }
1084 }
1085
1086 #[unstable(feature = "fused", issue = "35602")]
1087 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1088
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<'a, T> Clone for Union<'a, T> {
1091     fn clone(&self) -> Union<'a, T> {
1092         Union {
1093             a: self.a.clone(),
1094             b: self.b.clone(),
1095         }
1096     }
1097 }
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 impl<'a, T: Ord> Iterator for Union<'a, T> {
1100     type Item = &'a T;
1101
1102     fn next(&mut self) -> Option<&'a T> {
1103         match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1104             Less => self.a.next(),
1105             Equal => {
1106                 self.b.next();
1107                 self.a.next()
1108             }
1109             Greater => self.b.next(),
1110         }
1111     }
1112
1113     fn size_hint(&self) -> (usize, Option<usize>) {
1114         let a_len = self.a.len();
1115         let b_len = self.b.len();
1116         (max(a_len, b_len), Some(a_len + b_len))
1117     }
1118 }
1119
1120 #[unstable(feature = "fused", issue = "35602")]
1121 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}