]> git.lizzy.rs Git - rust.git/blob - src/libcollections/btree/set.rs
collections: Clean up feature flags doc examples
[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::prelude::*;
15
16 use core::cmp::Ordering::{self, Less, Greater, Equal};
17 use core::fmt::Debug;
18 use core::fmt;
19 use core::iter::{Peekable, Map, FromIterator};
20 use core::ops::{BitOr, BitAnd, BitXor, Sub};
21
22 use borrow::Borrow;
23 use btree_map::{BTreeMap, Keys};
24 use Bound;
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 #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub struct BTreeSet<T>{
39     map: BTreeMap<T, ()>,
40 }
41
42 /// An iterator over a BTreeSet's items.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub struct Iter<'a, T: 'a> {
45     iter: Keys<'a, T, ()>
46 }
47
48 /// An owning iterator over a BTreeSet's items.
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct IntoIter<T> {
51     iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T>
52 }
53
54 /// An iterator over a sub-range of BTreeSet's items.
55 pub struct Range<'a, T: 'a> {
56     iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T>
57 }
58
59 /// A lazy iterator producing elements in the set difference (in-order).
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Difference<'a, T:'a> {
62     a: Peekable<Iter<'a, T>>,
63     b: Peekable<Iter<'a, T>>,
64 }
65
66 /// A lazy iterator producing elements in the set symmetric difference (in-order).
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct SymmetricDifference<'a, T:'a> {
69     a: Peekable<Iter<'a, T>>,
70     b: Peekable<Iter<'a, T>>,
71 }
72
73 /// A lazy iterator producing elements in the set intersection (in-order).
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub struct Intersection<'a, T:'a> {
76     a: Peekable<Iter<'a, T>>,
77     b: Peekable<Iter<'a, T>>,
78 }
79
80 /// A lazy iterator producing elements in the set union (in-order).
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub struct Union<'a, T:'a> {
83     a: Peekable<Iter<'a, T>>,
84     b: Peekable<Iter<'a, T>>,
85 }
86
87 impl<T: Ord> BTreeSet<T> {
88     /// Makes a new BTreeSet with a reasonable choice of B.
89     ///
90     /// # Examples
91     ///
92     /// ```
93     /// use std::collections::BTreeSet;
94     ///
95     /// let mut set: BTreeSet<i32> = BTreeSet::new();
96     /// ```
97     #[stable(feature = "rust1", since = "1.0.0")]
98     pub fn new() -> BTreeSet<T> {
99         BTreeSet { map: BTreeMap::new() }
100     }
101
102     /// Makes a new BTreeSet with the given B.
103     ///
104     /// B cannot be less than 2.
105     #[unstable(feature = "collections",
106                reason = "probably want this to be on the type, eventually")]
107     pub fn with_b(b: usize) -> BTreeSet<T> {
108         BTreeSet { map: BTreeMap::with_b(b) }
109     }
110 }
111
112 impl<T> BTreeSet<T> {
113     /// Gets an iterator over the BTreeSet's contents.
114     ///
115     /// # Examples
116     ///
117     /// ```
118     /// use std::collections::BTreeSet;
119     ///
120     /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
121     ///
122     /// for x in set.iter() {
123     ///     println!("{}", x);
124     /// }
125     ///
126     /// let v: Vec<_> = set.iter().cloned().collect();
127     /// assert_eq!(v, [1, 2, 3, 4]);
128     /// ```
129     #[stable(feature = "rust1", since = "1.0.0")]
130     pub fn iter(&self) -> Iter<T> {
131         Iter { iter: self.map.keys() }
132     }
133 }
134
135 impl<T: Ord> BTreeSet<T> {
136     /// Constructs a double-ended iterator over a sub-range of elements in the set, starting
137     /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
138     /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
139     /// Thus range(Unbounded, Unbounded) will yield the whole collection.
140     ///
141     /// # Examples
142     ///
143     /// ```
144     /// # #![feature(collections)]
145     /// use std::collections::BTreeSet;
146     /// use std::collections::Bound::{Included, Unbounded};
147     ///
148     /// let mut set = BTreeSet::new();
149     /// set.insert(3);
150     /// set.insert(5);
151     /// set.insert(8);
152     /// for &elem in set.range(Included(&4), Included(&8)) {
153     ///     println!("{}", elem);
154     /// }
155     /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
156     /// ```
157     #[unstable(feature = "collections",
158                reason = "matches collection reform specification, waiting for dust to settle")]
159     pub fn range<'a>(&'a self, min: Bound<&T>, max: Bound<&T>) -> Range<'a, T> {
160         fn first<A, B>((a, _): (A, B)) -> A { a }
161         let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer
162
163         Range { iter: self.map.range(min, max).map(first) }
164     }
165 }
166
167 impl<T: Ord> BTreeSet<T> {
168     /// Visits the values representing the difference, in ascending order.
169     ///
170     /// # Examples
171     ///
172     /// ```
173     /// use std::collections::BTreeSet;
174     ///
175     /// let mut a = BTreeSet::new();
176     /// a.insert(1);
177     /// a.insert(2);
178     ///
179     /// let mut b = BTreeSet::new();
180     /// b.insert(2);
181     /// b.insert(3);
182     ///
183     /// let diff: Vec<_> = a.difference(&b).cloned().collect();
184     /// assert_eq!(diff, [1]);
185     /// ```
186     #[stable(feature = "rust1", since = "1.0.0")]
187     pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
188         Difference{a: self.iter().peekable(), b: other.iter().peekable()}
189     }
190
191     /// Visits the values representing the symmetric difference, in ascending order.
192     ///
193     /// # Examples
194     ///
195     /// ```
196     /// use std::collections::BTreeSet;
197     ///
198     /// let mut a = BTreeSet::new();
199     /// a.insert(1);
200     /// a.insert(2);
201     ///
202     /// let mut b = BTreeSet::new();
203     /// b.insert(2);
204     /// b.insert(3);
205     ///
206     /// let sym_diff: Vec<_> = a.symmetric_difference(&b).cloned().collect();
207     /// assert_eq!(sym_diff, [1, 3]);
208     /// ```
209     #[stable(feature = "rust1", since = "1.0.0")]
210     pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
211         -> SymmetricDifference<'a, T> {
212         SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()}
213     }
214
215     /// Visits the values representing the intersection, in ascending order.
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// use std::collections::BTreeSet;
221     ///
222     /// let mut a = BTreeSet::new();
223     /// a.insert(1);
224     /// a.insert(2);
225     ///
226     /// let mut b = BTreeSet::new();
227     /// b.insert(2);
228     /// b.insert(3);
229     ///
230     /// let intersection: Vec<_> = a.intersection(&b).cloned().collect();
231     /// assert_eq!(intersection, [2]);
232     /// ```
233     #[stable(feature = "rust1", since = "1.0.0")]
234     pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
235         -> Intersection<'a, T> {
236         Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
237     }
238
239     /// Visits the values representing the union, in ascending order.
240     ///
241     /// # Examples
242     ///
243     /// ```
244     /// use std::collections::BTreeSet;
245     ///
246     /// let mut a = BTreeSet::new();
247     /// a.insert(1);
248     ///
249     /// let mut b = BTreeSet::new();
250     /// b.insert(2);
251     ///
252     /// let union: Vec<_> = a.union(&b).cloned().collect();
253     /// assert_eq!(union, [1, 2]);
254     /// ```
255     #[stable(feature = "rust1", since = "1.0.0")]
256     pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
257         Union{a: self.iter().peekable(), b: other.iter().peekable()}
258     }
259
260     /// Returns the number of elements in the set.
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::collections::BTreeSet;
266     ///
267     /// let mut v = BTreeSet::new();
268     /// assert_eq!(v.len(), 0);
269     /// v.insert(1);
270     /// assert_eq!(v.len(), 1);
271     /// ```
272     #[stable(feature = "rust1", since = "1.0.0")]
273     pub fn len(&self) -> usize { self.map.len() }
274
275     /// Returns true if the set contains no elements.
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::collections::BTreeSet;
281     ///
282     /// let mut v = BTreeSet::new();
283     /// assert!(v.is_empty());
284     /// v.insert(1);
285     /// assert!(!v.is_empty());
286     /// ```
287     #[stable(feature = "rust1", since = "1.0.0")]
288     pub fn is_empty(&self) -> bool { self.len() == 0 }
289
290     /// Clears the set, removing all values.
291     ///
292     /// # Examples
293     ///
294     /// ```
295     /// use std::collections::BTreeSet;
296     ///
297     /// let mut v = BTreeSet::new();
298     /// v.insert(1);
299     /// v.clear();
300     /// assert!(v.is_empty());
301     /// ```
302     #[stable(feature = "rust1", since = "1.0.0")]
303     pub fn clear(&mut self) {
304         self.map.clear()
305     }
306
307     /// Returns `true` if the set contains a value.
308     ///
309     /// The value may be any borrowed form of the set's value type,
310     /// but the ordering on the borrowed form *must* match the
311     /// ordering on the value type.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// use std::collections::BTreeSet;
317     ///
318     /// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
319     /// assert_eq!(set.contains(&1), true);
320     /// assert_eq!(set.contains(&4), false);
321     /// ```
322     #[stable(feature = "rust1", since = "1.0.0")]
323     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
324         self.map.contains_key(value)
325     }
326
327     /// Returns `true` if the set has no elements in common with `other`.
328     /// This is equivalent to checking for an empty intersection.
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// use std::collections::BTreeSet;
334     ///
335     /// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
336     /// let mut b = BTreeSet::new();
337     ///
338     /// assert_eq!(a.is_disjoint(&b), true);
339     /// b.insert(4);
340     /// assert_eq!(a.is_disjoint(&b), true);
341     /// b.insert(1);
342     /// assert_eq!(a.is_disjoint(&b), false);
343     /// ```
344     #[stable(feature = "rust1", since = "1.0.0")]
345     pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
346         self.intersection(other).next().is_none()
347     }
348
349     /// Returns `true` if the set is a subset of another.
350     ///
351     /// # Examples
352     ///
353     /// ```
354     /// use std::collections::BTreeSet;
355     ///
356     /// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
357     /// let mut set = BTreeSet::new();
358     ///
359     /// assert_eq!(set.is_subset(&sup), true);
360     /// set.insert(2);
361     /// assert_eq!(set.is_subset(&sup), true);
362     /// set.insert(4);
363     /// assert_eq!(set.is_subset(&sup), false);
364     /// ```
365     #[stable(feature = "rust1", since = "1.0.0")]
366     pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
367         // Stolen from TreeMap
368         let mut x = self.iter();
369         let mut y = other.iter();
370         let mut a = x.next();
371         let mut b = y.next();
372         while a.is_some() {
373             if b.is_none() {
374                 return false;
375             }
376
377             let a1 = a.unwrap();
378             let b1 = b.unwrap();
379
380             match b1.cmp(a1) {
381                 Less => (),
382                 Greater => return false,
383                 Equal => a = x.next(),
384             }
385
386             b = y.next();
387         }
388         true
389     }
390
391     /// Returns `true` if the set is a superset of another.
392     ///
393     /// # Examples
394     ///
395     /// ```
396     /// use std::collections::BTreeSet;
397     ///
398     /// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
399     /// let mut set = BTreeSet::new();
400     ///
401     /// assert_eq!(set.is_superset(&sub), false);
402     ///
403     /// set.insert(0);
404     /// set.insert(1);
405     /// assert_eq!(set.is_superset(&sub), false);
406     ///
407     /// set.insert(2);
408     /// assert_eq!(set.is_superset(&sub), true);
409     /// ```
410     #[stable(feature = "rust1", since = "1.0.0")]
411     pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
412         other.is_subset(self)
413     }
414
415     /// Adds a value to the set. Returns `true` if the value was not already
416     /// present in the set.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// use std::collections::BTreeSet;
422     ///
423     /// let mut set = BTreeSet::new();
424     ///
425     /// assert_eq!(set.insert(2), true);
426     /// assert_eq!(set.insert(2), false);
427     /// assert_eq!(set.len(), 1);
428     /// ```
429     #[stable(feature = "rust1", since = "1.0.0")]
430     pub fn insert(&mut self, value: T) -> bool {
431         self.map.insert(value, ()).is_none()
432     }
433
434     /// Removes a value from the set. Returns `true` if the value was
435     /// present in the set.
436     ///
437     /// The value may be any borrowed form of the set's value type,
438     /// but the ordering on the borrowed form *must* match the
439     /// ordering on the value type.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::collections::BTreeSet;
445     ///
446     /// let mut set = BTreeSet::new();
447     ///
448     /// set.insert(2);
449     /// assert_eq!(set.remove(&2), true);
450     /// assert_eq!(set.remove(&2), false);
451     /// ```
452     #[stable(feature = "rust1", since = "1.0.0")]
453     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
454         self.map.remove(value).is_some()
455     }
456 }
457
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl<T: Ord> FromIterator<T> for BTreeSet<T> {
460     fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BTreeSet<T> {
461         let mut set = BTreeSet::new();
462         set.extend(iter);
463         set
464     }
465 }
466
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl<T> IntoIterator for BTreeSet<T> {
469     type Item = T;
470     type IntoIter = IntoIter<T>;
471
472     /// Gets an iterator for moving out the BtreeSet's contents.
473     ///
474     /// # Examples
475     ///
476     /// ```
477     /// use std::collections::BTreeSet;
478     ///
479     /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
480     ///
481     /// let v: Vec<_> = set.into_iter().collect();
482     /// assert_eq!(v, [1, 2, 3, 4]);
483     /// ```
484     fn into_iter(self) -> IntoIter<T> {
485         fn first<A, B>((a, _): (A, B)) -> A { a }
486         let first: fn((T, ())) -> T = first; // coerce to fn pointer
487
488         IntoIter { iter: self.map.into_iter().map(first) }
489     }
490 }
491
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl<'a, T> IntoIterator for &'a BTreeSet<T> {
494     type Item = &'a T;
495     type IntoIter = Iter<'a, T>;
496
497     fn into_iter(self) -> Iter<'a, T> {
498         self.iter()
499     }
500 }
501
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T: Ord> Extend<T> for BTreeSet<T> {
504     #[inline]
505     fn extend<Iter: IntoIterator<Item=T>>(&mut self, iter: Iter) {
506         for elem in iter {
507             self.insert(elem);
508         }
509     }
510 }
511
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl<T: Ord> Default for BTreeSet<T> {
514     #[stable(feature = "rust1", since = "1.0.0")]
515     fn default() -> BTreeSet<T> {
516         BTreeSet::new()
517     }
518 }
519
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl<'a, 'b, T: Ord + Clone> Sub<&'b BTreeSet<T>> for &'a BTreeSet<T> {
522     type Output = BTreeSet<T>;
523
524     /// Returns the difference of `self` and `rhs` as a new `BTreeSet<T>`.
525     ///
526     /// # Examples
527     ///
528     /// ```
529     /// use std::collections::BTreeSet;
530     ///
531     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
532     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
533     ///
534     /// let result = &a - &b;
535     /// let result_vec: Vec<_> = result.into_iter().collect();
536     /// assert_eq!(result_vec, [1, 2]);
537     /// ```
538     fn sub(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
539         self.difference(rhs).cloned().collect()
540     }
541 }
542
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl<'a, 'b, T: Ord + Clone> BitXor<&'b BTreeSet<T>> for &'a BTreeSet<T> {
545     type Output = BTreeSet<T>;
546
547     /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet<T>`.
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// use std::collections::BTreeSet;
553     ///
554     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
555     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
556     ///
557     /// let result = &a ^ &b;
558     /// let result_vec: Vec<_> = result.into_iter().collect();
559     /// assert_eq!(result_vec, [1, 4]);
560     /// ```
561     fn bitxor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
562         self.symmetric_difference(rhs).cloned().collect()
563     }
564 }
565
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<'a, 'b, T: Ord + Clone> BitAnd<&'b BTreeSet<T>> for &'a BTreeSet<T> {
568     type Output = BTreeSet<T>;
569
570     /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`.
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// use std::collections::BTreeSet;
576     ///
577     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
578     /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect();
579     ///
580     /// let result = &a & &b;
581     /// let result_vec: Vec<_> = result.into_iter().collect();
582     /// assert_eq!(result_vec, [2, 3]);
583     /// ```
584     fn bitand(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
585         self.intersection(rhs).cloned().collect()
586     }
587 }
588
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
591     type Output = BTreeSet<T>;
592
593     /// Returns the union of `self` and `rhs` as a new `BTreeSet<T>`.
594     ///
595     /// # Examples
596     ///
597     /// ```
598     /// use std::collections::BTreeSet;
599     ///
600     /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect();
601     /// let b: BTreeSet<_> = vec![3, 4, 5].into_iter().collect();
602     ///
603     /// let result = &a | &b;
604     /// let result_vec: Vec<_> = result.into_iter().collect();
605     /// assert_eq!(result_vec, [1, 2, 3, 4, 5]);
606     /// ```
607     fn bitor(self, rhs: &BTreeSet<T>) -> BTreeSet<T> {
608         self.union(rhs).cloned().collect()
609     }
610 }
611
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl<T: Debug> Debug for BTreeSet<T> {
614     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
615         self.iter().fold(f.debug_set(), |b, e| b.entry(e)).finish()
616     }
617 }
618
619 impl<'a, T> Clone for Iter<'a, T> {
620     fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } }
621 }
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<'a, T> Iterator for Iter<'a, T> {
624     type Item = &'a T;
625
626     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
627     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
628 }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
631     fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
632 }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
635
636
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<T> Iterator for IntoIter<T> {
639     type Item = T;
640
641     fn next(&mut self) -> Option<T> { self.iter.next() }
642     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
643 }
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<T> DoubleEndedIterator for IntoIter<T> {
646     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
647 }
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<T> ExactSizeIterator for IntoIter<T> {}
650
651
652 impl<'a, T> Clone for Range<'a, T> {
653     fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } }
654 }
655 impl<'a, T> Iterator for Range<'a, T> {
656     type Item = &'a T;
657
658     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
659 }
660 impl<'a, T> DoubleEndedIterator for Range<'a, T> {
661     fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
662 }
663
664 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
665 fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
666                         short: Ordering, long: Ordering) -> Ordering {
667     match (x, y) {
668         (None    , _       ) => short,
669         (_       , None    ) => long,
670         (Some(x1), Some(y1)) => x1.cmp(y1),
671     }
672 }
673
674 impl<'a, T> Clone for Difference<'a, T> {
675     fn clone(&self) -> Difference<'a, T> {
676         Difference { a: self.a.clone(), b: self.b.clone() }
677     }
678 }
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<'a, T: Ord> Iterator for Difference<'a, T> {
681     type Item = &'a T;
682
683     fn next(&mut self) -> Option<&'a T> {
684         loop {
685             match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
686                 Less    => return self.a.next(),
687                 Equal   => { self.a.next(); self.b.next(); }
688                 Greater => { self.b.next(); }
689             }
690         }
691     }
692 }
693
694 impl<'a, T> Clone for SymmetricDifference<'a, T> {
695     fn clone(&self) -> SymmetricDifference<'a, T> {
696         SymmetricDifference { a: self.a.clone(), b: self.b.clone() }
697     }
698 }
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
701     type Item = &'a T;
702
703     fn next(&mut self) -> Option<&'a T> {
704         loop {
705             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
706                 Less    => return self.a.next(),
707                 Equal   => { self.a.next(); self.b.next(); }
708                 Greater => return self.b.next(),
709             }
710         }
711     }
712 }
713
714 impl<'a, T> Clone for Intersection<'a, T> {
715     fn clone(&self) -> Intersection<'a, T> {
716         Intersection { a: self.a.clone(), b: self.b.clone() }
717     }
718 }
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<'a, T: Ord> Iterator for Intersection<'a, T> {
721     type Item = &'a T;
722
723     fn next(&mut self) -> Option<&'a T> {
724         loop {
725             let o_cmp = match (self.a.peek(), self.b.peek()) {
726                 (None    , _       ) => None,
727                 (_       , None    ) => None,
728                 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
729             };
730             match o_cmp {
731                 None          => return None,
732                 Some(Less)    => { self.a.next(); }
733                 Some(Equal)   => { self.b.next(); return self.a.next() }
734                 Some(Greater) => { self.b.next(); }
735             }
736         }
737     }
738 }
739
740 impl<'a, T> Clone for Union<'a, T> {
741     fn clone(&self) -> Union<'a, T> {
742         Union { a: self.a.clone(), b: self.b.clone() }
743     }
744 }
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<'a, T: Ord> Iterator for Union<'a, T> {
747     type Item = &'a T;
748
749     fn next(&mut self) -> Option<&'a T> {
750         loop {
751             match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
752                 Less    => return self.a.next(),
753                 Equal   => { self.b.next(); return self.a.next() }
754                 Greater => return self.b.next(),
755             }
756         }
757     }
758 }