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