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