]> git.lizzy.rs Git - rust.git/blob - src/libcollections/btree/set.rs
Various fixes throughout std::collections' docs
[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 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`]
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.clone())
142          .finish()
143     }
144 }
145
146 /// A lazy iterator producing elements in the symmetric difference of `BTreeSet`s.
147 ///
148 /// This `struct` is created by the [`symmetric_difference`] method on
149 /// [`BTreeSet`]. See its documentation for more.
150 ///
151 /// [`BTreeSet`]: struct.BTreeSet.html
152 /// [`symmetric_difference`]: struct.BTreeSet.html#method.symmetric_difference
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct SymmetricDifference<'a, T: 'a> {
155     a: Peekable<Iter<'a, T>>,
156     b: Peekable<Iter<'a, T>>,
157 }
158
159 #[stable(feature = "collection_debug", since = "1.17.0")]
160 impl<'a, T: 'a + fmt::Debug> fmt::Debug for SymmetricDifference<'a, T> {
161     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162         f.debug_tuple("SymmetricDifference")
163          .field(&self.clone())
164          .finish()
165     }
166 }
167
168 /// A lazy iterator producing elements in the intersection of `BTreeSet`s.
169 ///
170 /// This `struct` is created by the [`intersection`] method on [`BTreeSet`].
171 /// See its documentation for more.
172 ///
173 /// [`BTreeSet`]: struct.BTreeSet.html
174 /// [`intersection`]: struct.BTreeSet.html#method.intersection
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub struct Intersection<'a, T: 'a> {
177     a: Peekable<Iter<'a, T>>,
178     b: Peekable<Iter<'a, T>>,
179 }
180
181 #[stable(feature = "collection_debug", since = "1.17.0")]
182 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Intersection<'a, T> {
183     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184         f.debug_tuple("Intersection")
185          .field(&self.clone())
186          .finish()
187     }
188 }
189
190 /// A lazy iterator producing elements in the union of `BTreeSet`s.
191 ///
192 /// This `struct` is created by the [`union`] method on [`BTreeSet`].
193 /// See its documentation for more.
194 ///
195 /// [`BTreeSet`]: struct.BTreeSet.html
196 /// [`union`]: struct.BTreeSet.html#method.union
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub struct Union<'a, T: 'a> {
199     a: Peekable<Iter<'a, T>>,
200     b: Peekable<Iter<'a, T>>,
201 }
202
203 #[stable(feature = "collection_debug", since = "1.17.0")]
204 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Union<'a, T> {
205     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206         f.debug_tuple("Union")
207          .field(&self.clone())
208          .finish()
209     }
210 }
211
212 impl<T: Ord> BTreeSet<T> {
213     /// Makes a new `BTreeSet` with a reasonable choice of B.
214     ///
215     /// # Examples
216     ///
217     /// ```
218     /// # #![allow(unused_mut)]
219     /// use std::collections::BTreeSet;
220     ///
221     /// let mut set: BTreeSet<i32> = BTreeSet::new();
222     /// ```
223     #[stable(feature = "rust1", since = "1.0.0")]
224     pub fn new() -> BTreeSet<T> {
225         BTreeSet { map: BTreeMap::new() }
226     }
227 }
228
229 impl<T> BTreeSet<T> {
230     /// Gets an iterator that visits the values in the `BTreeSet` in ascending order.
231     ///
232     /// # Examples
233     ///
234     /// ```
235     /// use std::collections::BTreeSet;
236     ///
237     /// let set: BTreeSet<usize> = [1, 2, 3].iter().cloned().collect();
238     /// let mut set_iter = set.iter();
239     /// assert_eq!(set_iter.next(), Some(&1));
240     /// assert_eq!(set_iter.next(), Some(&2));
241     /// assert_eq!(set_iter.next(), Some(&3));
242     /// assert_eq!(set_iter.next(), None);
243     /// ```
244     ///
245     /// Values returned by the iterator are returned in ascending order:
246     ///
247     /// ```
248     /// use std::collections::BTreeSet;
249     ///
250     /// let set: BTreeSet<usize> = [3, 1, 2].iter().cloned().collect();
251     /// let mut set_iter = set.iter();
252     /// assert_eq!(set_iter.next(), Some(&1));
253     /// assert_eq!(set_iter.next(), Some(&2));
254     /// assert_eq!(set_iter.next(), Some(&3));
255     /// assert_eq!(set_iter.next(), None);
256     /// ```
257     #[stable(feature = "rust1", since = "1.0.0")]
258     pub fn iter(&self) -> Iter<T> {
259         Iter { iter: self.map.keys() }
260     }
261 }
262
263 impl<T: Ord> BTreeSet<T> {
264     /// Constructs a double-ended iterator over a sub-range of elements in the set.
265     /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
266     /// yield elements from min (inclusive) to max (exclusive).
267     /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
268     /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
269     /// range from 4 to 10.
270     ///
271     /// # Examples
272     ///
273     /// ```
274     /// use std::collections::BTreeSet;
275     /// use std::collections::Bound::Included;
276     ///
277     /// let mut set = BTreeSet::new();
278     /// set.insert(3);
279     /// set.insert(5);
280     /// set.insert(8);
281     /// for &elem in set.range((Included(&4), Included(&8))) {
282     ///     println!("{}", elem);
283     /// }
284     /// assert_eq!(Some(&5), set.range(4..).next());
285     /// ```
286     #[stable(feature = "btree_range", since = "1.17.0")]
287     pub fn range<K: ?Sized, R>(&self, range: R) -> Range<T>
288         where K: Ord, T: Borrow<K>, R: RangeArgument<K>
289     {
290         Range { iter: self.map.range(range) }
291     }
292 }
293
294 impl<T: Ord> BTreeSet<T> {
295     /// Visits the values representing the difference,
296     /// i.e. the values that are in `self` but not in `other`,
297     /// in ascending order.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::collections::BTreeSet;
303     ///
304     /// let mut a = BTreeSet::new();
305     /// a.insert(1);
306     /// a.insert(2);
307     ///
308     /// let mut b = BTreeSet::new();
309     /// b.insert(2);
310     /// b.insert(3);
311     ///
312     /// let diff: Vec<_> = a.difference(&b).cloned().collect();
313     /// assert_eq!(diff, [1]);
314     /// ```
315     #[stable(feature = "rust1", since = "1.0.0")]
316     pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
317         Difference {
318             a: self.iter().peekable(),
319             b: other.iter().peekable(),
320         }
321     }
322
323     /// Visits the values representing the symmetric difference,
324     /// i.e. the values that are in `self` or in `other` but not in both,
325     /// 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     /// a.insert(2);
335     ///
336     /// let mut b = BTreeSet::new();
337     /// b.insert(2);
338     /// b.insert(3);
339     ///
340     /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
341     /// assert_eq!(sym_diff, [1, 3]);
342     /// ```
343     #[stable(feature = "rust1", since = "1.0.0")]
344     pub fn symmetric_difference<'a>(&'a self,
345                                     other: &'a BTreeSet<T>)
346                                     -> SymmetricDifference<'a, T> {
347         SymmetricDifference {
348             a: self.iter().peekable(),
349             b: other.iter().peekable(),
350         }
351     }
352
353     /// Visits the values representing the intersection,
354     /// i.e. the values that are both in `self` and `other`,
355     /// in ascending order.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::collections::BTreeSet;
361     ///
362     /// let mut a = BTreeSet::new();
363     /// a.insert(1);
364     /// a.insert(2);
365     ///
366     /// let mut b = BTreeSet::new();
367     /// b.insert(2);
368     /// b.insert(3);
369     ///
370     /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
371     /// assert_eq!(intersection, [2]);
372     /// ```
373     #[stable(feature = "rust1", since = "1.0.0")]
374     pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T> {
375         Intersection {
376             a: self.iter().peekable(),
377             b: other.iter().peekable(),
378         }
379     }
380
381     /// Visits the values representing the union,
382     /// i.e. all the values in `self` or `other`, without duplicates,
383     /// in ascending order.
384     ///
385     /// # Examples
386     ///
387     /// ```
388     /// use std::collections::BTreeSet;
389     ///
390     /// let mut a = BTreeSet::new();
391     /// a.insert(1);
392     ///
393     /// let mut b = BTreeSet::new();
394     /// b.insert(2);
395     ///
396     /// let union: Vec<_> = a.union(&b).cloned().collect();
397     /// assert_eq!(union, [1, 2]);
398     /// ```
399     #[stable(feature = "rust1", since = "1.0.0")]
400     pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
401         Union {
402             a: self.iter().peekable(),
403             b: other.iter().peekable(),
404         }
405     }
406
407     /// Returns the number of elements in the set.
408     ///
409     /// # Examples
410     ///
411     /// ```
412     /// use std::collections::BTreeSet;
413     ///
414     /// let mut v = BTreeSet::new();
415     /// assert_eq!(v.len(), 0);
416     /// v.insert(1);
417     /// assert_eq!(v.len(), 1);
418     /// ```
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn len(&self) -> usize {
421         self.map.len()
422     }
423
424     /// Returns `true` if the set contains no elements.
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// use std::collections::BTreeSet;
430     ///
431     /// let mut v = BTreeSet::new();
432     /// assert!(v.is_empty());
433     /// v.insert(1);
434     /// assert!(!v.is_empty());
435     /// ```
436     #[stable(feature = "rust1", since = "1.0.0")]
437     pub fn is_empty(&self) -> bool {
438         self.len() == 0
439     }
440
441     /// Clears the set, removing all values.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::collections::BTreeSet;
447     ///
448     /// let mut v = BTreeSet::new();
449     /// v.insert(1);
450     /// v.clear();
451     /// assert!(v.is_empty());
452     /// ```
453     #[stable(feature = "rust1", since = "1.0.0")]
454     pub fn clear(&mut self) {
455         self.map.clear()
456     }
457
458     /// Returns `true` if the set contains a value.
459     ///
460     /// The value may be any borrowed form of the set's value type,
461     /// but the ordering on the borrowed form *must* match the
462     /// ordering on the value type.
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// use std::collections::BTreeSet;
468     ///
469     /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
470     /// assert_eq!(set.contains(&1), true);
471     /// assert_eq!(set.contains(&4), false);
472     /// ```
473     #[stable(feature = "rust1", since = "1.0.0")]
474     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
475         where T: Borrow<Q>,
476               Q: Ord
477     {
478         self.map.contains_key(value)
479     }
480
481     /// Returns a reference to the value in the set, if any, that is equal to the given value.
482     ///
483     /// The value may be any borrowed form of the set's value type,
484     /// but the ordering on the borrowed form *must* match the
485     /// ordering on the value type.
486     #[stable(feature = "set_recovery", since = "1.9.0")]
487     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
488         where T: Borrow<Q>,
489               Q: Ord
490     {
491         Recover::get(&self.map, value)
492     }
493
494     /// Returns `true` if `self` has no elements in common with `other`.
495     /// This is equivalent to checking for an empty intersection.
496     ///
497     /// # Examples
498     ///
499     /// ```
500     /// use std::collections::BTreeSet;
501     ///
502     /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
503     /// let mut b = BTreeSet::new();
504     ///
505     /// assert_eq!(a.is_disjoint(&b), true);
506     /// b.insert(4);
507     /// assert_eq!(a.is_disjoint(&b), true);
508     /// b.insert(1);
509     /// assert_eq!(a.is_disjoint(&b), false);
510     /// ```
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
513         self.intersection(other).next().is_none()
514     }
515
516     /// Returns `true` if the set is a subset of another,
517     /// i.e. `other` contains at least all the values in `self`.
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// use std::collections::BTreeSet;
523     ///
524     /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
525     /// let mut set = BTreeSet::new();
526     ///
527     /// assert_eq!(set.is_subset(&sup), true);
528     /// set.insert(2);
529     /// assert_eq!(set.is_subset(&sup), true);
530     /// set.insert(4);
531     /// assert_eq!(set.is_subset(&sup), false);
532     /// ```
533     #[stable(feature = "rust1", since = "1.0.0")]
534     pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
535         // Stolen from TreeMap
536         let mut x = self.iter();
537         let mut y = other.iter();
538         let mut a = x.next();
539         let mut b = y.next();
540         while a.is_some() {
541             if b.is_none() {
542                 return false;
543             }
544
545             let a1 = a.unwrap();
546             let b1 = b.unwrap();
547
548             match b1.cmp(a1) {
549                 Less => (),
550                 Greater => return false,
551                 Equal => a = x.next(),
552             }
553
554             b = y.next();
555         }
556         true
557     }
558
559     /// Returns `true` if the set is a superset of another,
560     /// i.e. `self` contains at least all the values in `other`.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// use std::collections::BTreeSet;
566     ///
567     /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
568     /// let mut set = BTreeSet::new();
569     ///
570     /// assert_eq!(set.is_superset(&sub), false);
571     ///
572     /// set.insert(0);
573     /// set.insert(1);
574     /// assert_eq!(set.is_superset(&sub), false);
575     ///
576     /// set.insert(2);
577     /// assert_eq!(set.is_superset(&sub), true);
578     /// ```
579     #[stable(feature = "rust1", since = "1.0.0")]
580     pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
581         other.is_subset(self)
582     }
583
584     /// Adds a value to the set.
585     ///
586     /// If the set did not have this value present, `true` is returned.
587     ///
588     /// If the set did have this value present, `false` is returned, and the
589     /// entry is not updated. See the [module-level documentation] for more.
590     ///
591     /// [module-level documentation]: index.html#insert-and-complex-keys
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// use std::collections::BTreeSet;
597     ///
598     /// let mut set = BTreeSet::new();
599     ///
600     /// assert_eq!(set.insert(2), true);
601     /// assert_eq!(set.insert(2), false);
602     /// assert_eq!(set.len(), 1);
603     /// ```
604     #[stable(feature = "rust1", since = "1.0.0")]
605     pub fn insert(&mut self, value: T) -> bool {
606         self.map.insert(value, ()).is_none()
607     }
608
609     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
610     /// one. Returns the replaced value.
611     #[stable(feature = "set_recovery", since = "1.9.0")]
612     pub fn replace(&mut self, value: T) -> Option<T> {
613         Recover::replace(&mut self.map, value)
614     }
615
616     /// Removes a value from the set. Returns `true` if the value was
617     /// present in the set.
618     ///
619     /// The value may be any borrowed form of the set's value type,
620     /// but the ordering on the borrowed form *must* match the
621     /// ordering on the value type.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// use std::collections::BTreeSet;
627     ///
628     /// let mut set = BTreeSet::new();
629     ///
630     /// set.insert(2);
631     /// assert_eq!(set.remove(&2), true);
632     /// assert_eq!(set.remove(&2), false);
633     /// ```
634     #[stable(feature = "rust1", since = "1.0.0")]
635     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
636         where T: Borrow<Q>,
637               Q: Ord
638     {
639         self.map.remove(value).is_some()
640     }
641
642     /// Removes and returns the value in the set, if any, that is equal to the given one.
643     ///
644     /// The value may be any borrowed form of the set's value type,
645     /// but the ordering on the borrowed form *must* match the
646     /// ordering on the value type.
647     #[stable(feature = "set_recovery", since = "1.9.0")]
648     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
649         where T: Borrow<Q>,
650               Q: Ord
651     {
652         Recover::take(&mut self.map, value)
653     }
654
655     /// Moves all elements from `other` into `Self`, leaving `other` empty.
656     ///
657     /// # Examples
658     ///
659     /// ```
660     /// use std::collections::BTreeSet;
661     ///
662     /// let mut a = BTreeSet::new();
663     /// a.insert(1);
664     /// a.insert(2);
665     /// a.insert(3);
666     ///
667     /// let mut b = BTreeSet::new();
668     /// b.insert(3);
669     /// b.insert(4);
670     /// b.insert(5);
671     ///
672     /// a.append(&mut b);
673     ///
674     /// assert_eq!(a.len(), 5);
675     /// assert_eq!(b.len(), 0);
676     ///
677     /// assert!(a.contains(&1));
678     /// assert!(a.contains(&2));
679     /// assert!(a.contains(&3));
680     /// assert!(a.contains(&4));
681     /// assert!(a.contains(&5));
682     /// ```
683     #[stable(feature = "btree_append", since = "1.11.0")]
684     pub fn append(&mut self, other: &mut Self) {
685         self.map.append(&mut other.map);
686     }
687
688     /// Splits the collection into two at the given key. Returns everything after the given key,
689     /// including the key.
690     ///
691     /// # Examples
692     ///
693     /// Basic usage:
694     ///
695     /// ```
696     /// use std::collections::BTreeMap;
697     ///
698     /// let mut a = BTreeMap::new();
699     /// a.insert(1, "a");
700     /// a.insert(2, "b");
701     /// a.insert(3, "c");
702     /// a.insert(17, "d");
703     /// a.insert(41, "e");
704     ///
705     /// let b = a.split_off(&3);
706     ///
707     /// assert_eq!(a.len(), 2);
708     /// assert_eq!(b.len(), 3);
709     ///
710     /// assert_eq!(a[&1], "a");
711     /// assert_eq!(a[&2], "b");
712     ///
713     /// assert_eq!(b[&3], "c");
714     /// assert_eq!(b[&17], "d");
715     /// assert_eq!(b[&41], "e");
716     /// ```
717     #[stable(feature = "btree_split_off", since = "1.11.0")]
718     pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where T: Borrow<Q> {
719         BTreeSet { map: self.map.split_off(key) }
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 impl<'a, T> Clone for Range<'a, T> {
945     fn clone(&self) -> Range<'a, T> {
946         Range { iter: self.iter.clone() }
947     }
948 }
949 impl<'a, T> Iterator for Range<'a, T> {
950     type Item = &'a T;
951
952     fn next(&mut self) -> Option<&'a T> {
953         self.iter.next().map(|(k, _)| k)
954     }
955 }
956 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
957     fn next_back(&mut self) -> Option<&'a T> {
958         self.iter.next_back().map(|(k, _)| k)
959     }
960 }
961
962 #[unstable(feature = "fused", issue = "35602")]
963 impl<'a, T> FusedIterator for Range<'a, T> {}
964
965 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
966 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering {
967     match (x, y) {
968         (None, _) => short,
969         (_, None) => long,
970         (Some(x1), Some(y1)) => x1.cmp(y1),
971     }
972 }
973
974 #[stable(feature = "rust1", since = "1.0.0")]
975 impl<'a, T> Clone for Difference<'a, T> {
976     fn clone(&self) -> Difference<'a, T> {
977         Difference {
978             a: self.a.clone(),
979             b: self.b.clone(),
980         }
981     }
982 }
983 #[stable(feature = "rust1", since = "1.0.0")]
984 impl<'a, T: Ord> Iterator for Difference<'a, T> {
985     type Item = &'a T;
986
987     fn next(&mut self) -> Option<&'a T> {
988         loop {
989             match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
990                 Less => return self.a.next(),
991                 Equal => {
992                     self.a.next();
993                     self.b.next();
994                 }
995                 Greater => {
996                     self.b.next();
997                 }
998             }
999         }
1000     }
1001
1002     fn size_hint(&self) -> (usize, Option<usize>) {
1003         let a_len = self.a.len();
1004         let b_len = self.b.len();
1005         (a_len.saturating_sub(b_len), Some(a_len))
1006     }
1007 }
1008
1009 #[unstable(feature = "fused", issue = "35602")]
1010 impl<'a, T: Ord> FusedIterator for Difference<'a, T> {}
1011
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<'a, T> Clone for SymmetricDifference<'a, T> {
1014     fn clone(&self) -> SymmetricDifference<'a, T> {
1015         SymmetricDifference {
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 SymmetricDifference<'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(), Greater, Less) {
1028                 Less => return self.a.next(),
1029                 Equal => {
1030                     self.a.next();
1031                     self.b.next();
1032                 }
1033                 Greater => return self.b.next(),
1034             }
1035         }
1036     }
1037
1038     fn size_hint(&self) -> (usize, Option<usize>) {
1039         (0, Some(self.a.len() + self.b.len()))
1040     }
1041 }
1042
1043 #[unstable(feature = "fused", issue = "35602")]
1044 impl<'a, T: Ord> FusedIterator for SymmetricDifference<'a, T> {}
1045
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 impl<'a, T> Clone for Intersection<'a, T> {
1048     fn clone(&self) -> Intersection<'a, T> {
1049         Intersection {
1050             a: self.a.clone(),
1051             b: self.b.clone(),
1052         }
1053     }
1054 }
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
1057     type Item = &'a T;
1058
1059     fn next(&mut self) -> Option<&'a T> {
1060         loop {
1061             let o_cmp = match (self.a.peek(), self.b.peek()) {
1062                 (None, _) => None,
1063                 (_, None) => None,
1064                 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
1065             };
1066             match o_cmp {
1067                 None => return None,
1068                 Some(Less) => {
1069                     self.a.next();
1070                 }
1071                 Some(Equal) => {
1072                     self.b.next();
1073                     return self.a.next();
1074                 }
1075                 Some(Greater) => {
1076                     self.b.next();
1077                 }
1078             }
1079         }
1080     }
1081
1082     fn size_hint(&self) -> (usize, Option<usize>) {
1083         (0, Some(min(self.a.len(), self.b.len())))
1084     }
1085 }
1086
1087 #[unstable(feature = "fused", issue = "35602")]
1088 impl<'a, T: Ord> FusedIterator for Intersection<'a, T> {}
1089
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<'a, T> Clone for Union<'a, T> {
1092     fn clone(&self) -> Union<'a, T> {
1093         Union {
1094             a: self.a.clone(),
1095             b: self.b.clone(),
1096         }
1097     }
1098 }
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<'a, T: Ord> Iterator for Union<'a, T> {
1101     type Item = &'a T;
1102
1103     fn next(&mut self) -> Option<&'a T> {
1104         loop {
1105             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
1106                 Less => return self.a.next(),
1107                 Equal => {
1108                     self.b.next();
1109                     return self.a.next();
1110                 }
1111                 Greater => return self.b.next(),
1112             }
1113         }
1114     }
1115
1116     fn size_hint(&self) -> (usize, Option<usize>) {
1117         let a_len = self.a.len();
1118         let b_len = self.b.len();
1119         (max(a_len, b_len), Some(a_len + b_len))
1120     }
1121 }
1122
1123 #[unstable(feature = "fused", issue = "35602")]
1124 impl<'a, T: Ord> FusedIterator for Union<'a, T> {}