linear_map/
set.rs

1//! A set implemented by searching linearly in a vector.
2//!
3//! See the [`LinearSet`](struct.LinearSet.html) type for details.
4
5use std::borrow::Borrow;
6use std::fmt;
7use std::iter::{Chain, FromIterator};
8use std::ops::{BitOr, BitAnd, BitXor, Sub};
9
10use super::{LinearMap, Keys};
11
12/// An implementation of a set using the underlying representation of a
13/// LinearMap where the value is ().
14///
15/// # Examples
16///
17/// ```
18/// use linear_map::set::LinearSet;;
19/// // Type inference lets us omit an explicit type signature (which
20/// // would be `LinearSet<&str>` in this example).
21/// let mut books = LinearSet::new();
22///
23/// // Add some books.
24/// books.insert("A Dance With Dragons");
25/// books.insert("To Kill a Mockingbird");
26/// books.insert("The Odyssey");
27/// books.insert("The Great Gatsby");
28///
29/// // Check for a specific one.
30/// if !books.contains("The Winds of Winter") {
31///     println!("We have {} books, but The Winds of Winter ain't one.",
32///              books.len());
33/// }
34///
35/// // Remove a book.
36/// books.remove("The Odyssey");
37///
38/// // Iterate over everything.
39/// for book in &books {
40///     println!("{}", book);
41/// }
42/// ```
43///
44/// The easiest way to use `LinearSet` with a custom type is to derive
45/// `Eq`. We must also derive `PartialEq`, this will in the
46/// future be implied by `Eq`.
47///
48/// ```
49/// use linear_map::set::LinearSet;;
50/// #[derive(Eq, PartialEq, Debug)]
51/// struct Viking<'a> {
52///     name: &'a str,
53///     power: usize,
54/// }
55///
56/// let mut vikings = LinearSet::new();
57///
58/// vikings.insert(Viking { name: "Einar", power: 9 });
59/// vikings.insert(Viking { name: "Einar", power: 9 });
60/// vikings.insert(Viking { name: "Olaf", power: 4 });
61/// vikings.insert(Viking { name: "Harald", power: 8 });
62///
63/// // Use derived implementation to print the vikings.
64/// for x in &vikings {
65///     println!("{:?}", x);
66/// }
67/// ```
68#[derive(Clone)]
69pub struct LinearSet<T> {
70    map: LinearMap<T, ()>
71}
72
73impl<T: Eq> LinearSet<T> {
74    /// Creates an empty LinearSet.
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use linear_map::set::LinearSet;;
80    /// let mut set: LinearSet<i32> = LinearSet::new();
81    /// ```
82    #[inline]
83
84    pub fn new() -> LinearSet<T> {
85        LinearSet { map: LinearMap::new() }
86    }
87
88    /// Creates an empty LinearSet with space for at least `n` elements in
89    /// the map.
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use linear_map::set::LinearSet;;
95    /// let mut set: LinearSet<i32> = LinearSet::with_capacity(10);
96    /// ```
97    #[inline]
98    pub fn with_capacity(capacity: usize) -> LinearSet<T> {
99        LinearSet { map: LinearMap::with_capacity(capacity) }
100    }
101}
102
103impl<T> LinearSet<T>
104    where T: Eq
105{
106    /// Returns the number of elements the set can hold without reallocating.
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use linear_map::set::LinearSet;;
112    /// let set: LinearSet<i32> = LinearSet::with_capacity(100);
113    /// assert!(set.capacity() >= 100);
114    /// ```
115    #[inline]
116
117    pub fn capacity(&self) -> usize {
118        self.map.capacity()
119    }
120
121    /// Reserves capacity for at least `additional` more elements to be inserted
122    /// in the `LinearSet`. The collection may reserve more space to avoid
123    /// frequent reallocations.
124    ///
125    /// # Panics
126    ///
127    /// Panics if the new allocation size overflows `usize`.
128    ///
129    /// # Examples
130    ///
131    /// ```
132    /// use linear_map::set::LinearSet;;
133    /// let mut set: LinearSet<i32> = LinearSet::new();
134    /// set.reserve(10);
135    /// ```
136
137    pub fn reserve(&mut self, additional: usize) {
138        self.map.reserve(additional)
139    }
140
141    /// Shrinks the capacity of the set as much as possible. It will drop
142    /// down as much as possible while maintaining the internal rules
143    /// and possibly leaving some space in accordance with the resize policy.
144    ///
145    /// # Examples
146    ///
147    /// ```
148    /// use linear_map::set::LinearSet;;
149    ///
150    /// let mut set = LinearSet::with_capacity(100);
151    /// set.insert(1);
152    /// set.insert(2);
153    /// assert!(set.capacity() >= 100);
154    /// set.shrink_to_fit();
155    /// assert!(set.capacity() >= 2);
156    /// ```
157
158    pub fn shrink_to_fit(&mut self) {
159        self.map.shrink_to_fit()
160    }
161
162    /// An iterator visiting all elements in arbitrary order.
163    /// Iterator element type is &'a T.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// use linear_map::set::LinearSet;;
169    /// let mut set = LinearSet::new();
170    /// set.insert("a");
171    /// set.insert("b");
172    ///
173    /// // Will print in an arbitrary order.
174    /// for x in set.iter() {
175    ///     println!("{}", x);
176    /// }
177    /// ```
178
179    pub fn iter(&self) -> Iter<T> {
180        Iter { iter: self.map.keys() }
181    }
182
183    /// Visit the values representing the difference.
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// use linear_map::set::LinearSet;;
189    /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
190    /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect();
191    ///
192    /// // Can be seen as `a - b`.
193    /// for x in a.difference(&b) {
194    ///     println!("{}", x); // Print 1
195    /// }
196    ///
197    /// let diff: LinearSet<_> = a.difference(&b).cloned().collect();
198    /// assert_eq!(diff, [1].iter().cloned().collect());
199    ///
200    /// // Note that difference is not symmetric,
201    /// // and `b - a` means something else:
202    /// let diff: LinearSet<_> = b.difference(&a).cloned().collect();
203    /// assert_eq!(diff, [4].iter().cloned().collect());
204    /// ```
205
206    pub fn difference<'a>(&'a self, other: &'a LinearSet<T>) -> Difference<'a, T> {
207        Difference {
208            iter: self.iter(),
209            other: other,
210        }
211    }
212
213    /// Visit the values representing the symmetric difference.
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use linear_map::set::LinearSet;;
219    /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
220    /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect();
221    ///
222    /// // Print 1, 4 in arbitrary order.
223    /// for x in a.symmetric_difference(&b) {
224    ///     println!("{}", x);
225    /// }
226    ///
227    /// let diff1: LinearSet<_> = a.symmetric_difference(&b).cloned().collect();
228    /// let diff2: LinearSet<_> = b.symmetric_difference(&a).cloned().collect();
229    ///
230    /// assert_eq!(diff1, diff2);
231    /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
232    /// ```
233
234    pub fn symmetric_difference<'a>(&'a self, other: &'a LinearSet<T>)
235        -> SymmetricDifference<'a, T> {
236        SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
237    }
238
239    /// Visit the values representing the intersection.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use linear_map::set::LinearSet;;
245    /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
246    /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect();
247    ///
248    /// // Print 2, 3 in arbitrary order.
249    /// for x in a.intersection(&b) {
250    ///     println!("{}", x);
251    /// }
252    ///
253    /// let intersection: LinearSet<_> = a.intersection(&b).cloned().collect();
254    /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
255    /// ```
256
257    pub fn intersection<'a>(&'a self, other: &'a LinearSet<T>) -> Intersection<'a, T> {
258        Intersection {
259            iter: self.iter(),
260            other: other,
261        }
262    }
263
264    /// Visit the values representing the union.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use linear_map::set::LinearSet;;
270    /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
271    /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect();
272    ///
273    /// // Print 1, 2, 3, 4 in arbitrary order.
274    /// for x in a.union(&b) {
275    ///     println!("{}", x);
276    /// }
277    ///
278    /// let union: LinearSet<_> = a.union(&b).cloned().collect();
279    /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
280    /// ```
281
282    pub fn union<'a>(&'a self, other: &'a LinearSet<T>) -> Union<'a, T> {
283        Union { iter: self.iter().chain(other.difference(self)) }
284    }
285
286    /// Returns the number of elements in the set.
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// use linear_map::set::LinearSet;;
292    ///
293    /// let mut v = LinearSet::new();
294    /// assert_eq!(v.len(), 0);
295    /// v.insert(1);
296    /// assert_eq!(v.len(), 1);
297    /// ```
298
299    pub fn len(&self) -> usize { self.map.len() }
300
301    /// Returns true if the set contains no elements.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use linear_map::set::LinearSet;;
307    ///
308    /// let mut v = LinearSet::new();
309    /// assert!(v.is_empty());
310    /// v.insert(1);
311    /// assert!(!v.is_empty());
312    /// ```
313
314    pub fn is_empty(&self) -> bool { self.map.is_empty() }
315
316    /// Clears the set, returning all elements in an iterator.
317    #[inline]
318    pub fn drain(&mut self) -> Drain<T> {
319        Drain { iter: self.map.drain() }
320    }
321
322    /// Clears the set, removing all values.
323    ///
324    /// # Examples
325    ///
326    /// ```
327    /// use linear_map::set::LinearSet;;
328    ///
329    /// let mut v = LinearSet::new();
330    /// v.insert(1);
331    /// v.clear();
332    /// assert!(v.is_empty());
333    /// ```
334    pub fn clear(&mut self) { self.map.clear() }
335
336    /// Retains only the elements specified by the predicate.
337    ///
338    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
339    ///
340    pub fn retain<F>(&mut self, mut f: F)
341    where F: FnMut(&T) -> bool {
342        self.map.retain(|k, _| f(k));
343    }
344
345    /// Returns `true` if the set contains a value.
346    ///
347    /// The value may be any borrowed form of the set's value type, but
348    /// `Eq` on the borrowed form *must* match those for
349    /// the value type.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// use linear_map::set::LinearSet;;
355    ///
356    /// let set: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
357    /// assert_eq!(set.contains(&1), true);
358    /// assert_eq!(set.contains(&4), false);
359    /// ```
360    pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
361        where T: Borrow<Q>, Q: Eq
362    {
363        self.map.contains_key(value)
364    }
365
366    /// Returns `true` if the set has no elements in common with `other`.
367    /// This is equivalent to checking for an empty intersection.
368    ///
369    /// # Examples
370    ///
371    /// ```
372    /// use linear_map::set::LinearSet;;
373    ///
374    /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
375    /// let mut b = LinearSet::new();
376    ///
377    /// assert_eq!(a.is_disjoint(&b), true);
378    /// b.insert(4);
379    /// assert_eq!(a.is_disjoint(&b), true);
380    /// b.insert(1);
381    /// assert_eq!(a.is_disjoint(&b), false);
382    /// ```
383
384    pub fn is_disjoint(&self, other: &LinearSet<T>) -> bool {
385        self.iter().all(|v| !other.contains(v))
386    }
387
388    /// Returns `true` if the set is a subset of another.
389    ///
390    /// # Examples
391    ///
392    /// ```
393    /// use linear_map::set::LinearSet;;
394    ///
395    /// let sup: LinearSet<_> = [1, 2, 3].iter().cloned().collect();
396    /// let mut set = LinearSet::new();
397    ///
398    /// assert_eq!(set.is_subset(&sup), true);
399    /// set.insert(2);
400    /// assert_eq!(set.is_subset(&sup), true);
401    /// set.insert(4);
402    /// assert_eq!(set.is_subset(&sup), false);
403    /// ```
404
405    pub fn is_subset(&self, other: &LinearSet<T>) -> bool {
406        self.iter().all(|v| other.contains(v))
407    }
408
409    /// Returns `true` if the set is a superset of another.
410    ///
411    /// # Examples
412    ///
413    /// ```
414    /// use linear_map::set::LinearSet;;
415    ///
416    /// let sub: LinearSet<_> = [1, 2].iter().cloned().collect();
417    /// let mut set = LinearSet::new();
418    ///
419    /// assert_eq!(set.is_superset(&sub), false);
420    ///
421    /// set.insert(0);
422    /// set.insert(1);
423    /// assert_eq!(set.is_superset(&sub), false);
424    ///
425    /// set.insert(2);
426    /// assert_eq!(set.is_superset(&sub), true);
427    /// ```
428    #[inline]
429
430    pub fn is_superset(&self, other: &LinearSet<T>) -> bool {
431        other.is_subset(self)
432    }
433
434    /// Adds a value to the set.
435    ///
436    /// If the set did not have a value present, `true` is returned.
437    ///
438    /// If the set did have this key present, `false` is returned.
439    ///
440    /// # Examples
441    ///
442    /// ```
443    /// use linear_map::set::LinearSet;;
444    ///
445    /// let mut set = LinearSet::new();
446    ///
447    /// assert_eq!(set.insert(2), true);
448    /// assert_eq!(set.insert(2), false);
449    /// assert_eq!(set.len(), 1);
450    /// ```
451
452    pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
453
454    /// Removes a value from the set. Returns `true` if the value was
455    /// present in the set.
456    ///
457    /// The value may be any borrowed form of the set's value type, but
458    /// `Eq` on the borrowed form *must* match those for
459    /// the value type.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use linear_map::set::LinearSet;;
465    ///
466    /// let mut set = LinearSet::new();
467    ///
468    /// set.insert(2);
469    /// assert_eq!(set.remove(&2), true);
470    /// assert_eq!(set.remove(&2), false);
471    /// ```
472
473    pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
474        where T: Borrow<Q>, Q: Eq
475    {
476        self.map.remove(value).is_some()
477    }
478
479}
480
481impl<T> PartialEq for LinearSet<T>
482    where T: Eq
483{
484    fn eq(&self, other: &LinearSet<T>) -> bool {
485        if self.len() != other.len() { return false; }
486
487        self.iter().all(|key| other.contains(key))
488    }
489}
490
491impl<T> Eq for LinearSet<T>
492    where T: Eq
493{}
494
495impl<T> fmt::Debug for LinearSet<T>
496    where T: Eq + fmt::Debug
497{
498    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
499        f.debug_set().entries(self.iter()).finish()
500    }
501}
502
503impl<T> FromIterator<T> for LinearSet<T>
504    where T: Eq
505{
506    fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> LinearSet<T> {
507        let iterator = iter.into_iter();
508        let lower = iterator.size_hint().0;
509        let mut set = LinearSet::with_capacity(lower);
510        set.extend(iterator);
511        set
512    }
513}
514
515impl<T> Extend<T> for LinearSet<T>
516    where T: Eq
517{
518    fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
519        for k in iter {
520            self.insert(k);
521        }
522    }
523}
524
525impl<'a, T> Extend<&'a T> for LinearSet<T>
526    where T: 'a + Eq + Copy
527{
528    fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
529        self.extend(iter.into_iter().cloned());
530    }
531}
532
533impl<T> Default for LinearSet<T>
534    where T: Eq
535{
536    fn default() -> LinearSet<T> {
537        LinearSet::new()
538    }
539}
540
541impl<K: Eq> Into<Vec<K>> for LinearSet<K> {
542    fn into(self) -> Vec<K> {
543        unsafe {
544            use std::mem;
545            mem::transmute(self)
546        }
547    }
548}
549
550impl<'a, 'b, T> BitOr<&'b LinearSet<T>> for &'a LinearSet<T>
551    where T: Eq + Clone
552{
553    type Output = LinearSet<T>;
554
555    /// Returns the union of `self` and `rhs` as a new `LinearSet<T>`.
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use linear_map::set::LinearSet;;
561    ///
562    /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect();
563    /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect();
564    ///
565    /// let set = &a | &b;
566    ///
567    /// let mut i = 0;
568    /// let expected = [1, 2, 3, 4, 5];
569    /// for x in &set {
570    ///     assert!(expected.contains(x));
571    ///     i += 1;
572    /// }
573    /// assert_eq!(i, expected.len());
574    /// ```
575    fn bitor(self, rhs: &LinearSet<T>) -> LinearSet<T> {
576        self.union(rhs).cloned().collect()
577    }
578}
579
580impl<'a, 'b, T> BitAnd<&'b LinearSet<T>> for &'a LinearSet<T>
581    where T: Eq + Clone
582{
583    type Output = LinearSet<T>;
584
585    /// Returns the intersection of `self` and `rhs` as a new `LinearSet<T>`.
586    ///
587    /// # Examples
588    ///
589    /// ```
590    /// use linear_map::set::LinearSet;;
591    ///
592    /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect();
593    /// let b: LinearSet<_> = vec![2, 3, 4].into_iter().collect();
594    ///
595    /// let set = &a & &b;
596    ///
597    /// let mut i = 0;
598    /// let expected = [2, 3];
599    /// for x in &set {
600    ///     assert!(expected.contains(x));
601    ///     i += 1;
602    /// }
603    /// assert_eq!(i, expected.len());
604    /// ```
605    fn bitand(self, rhs: &LinearSet<T>) -> LinearSet<T> {
606        self.intersection(rhs).cloned().collect()
607    }
608}
609
610impl<'a, 'b, T> BitXor<&'b LinearSet<T>> for &'a LinearSet<T>
611    where T: Eq + Clone
612{
613    type Output = LinearSet<T>;
614
615    /// Returns the symmetric difference of `self` and `rhs` as a new `LinearSet<T>`.
616    ///
617    /// # Examples
618    ///
619    /// ```
620    /// use linear_map::set::LinearSet;;
621    ///
622    /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect();
623    /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect();
624    ///
625    /// let set = &a ^ &b;
626    ///
627    /// let mut i = 0;
628    /// let expected = [1, 2, 4, 5];
629    /// for x in &set {
630    ///     assert!(expected.contains(x));
631    ///     i += 1;
632    /// }
633    /// assert_eq!(i, expected.len());
634    /// ```
635    fn bitxor(self, rhs: &LinearSet<T>) -> LinearSet<T> {
636        self.symmetric_difference(rhs).cloned().collect()
637    }
638}
639
640impl<'a, 'b, T> Sub<&'b LinearSet<T>> for &'a LinearSet<T>
641    where T: Eq + Clone
642{
643    type Output = LinearSet<T>;
644
645    /// Returns the difference of `self` and `rhs` as a new `LinearSet<T>`.
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// use linear_map::set::LinearSet;;
651    ///
652    /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect();
653    /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect();
654    ///
655    /// let set = &a - &b;
656    ///
657    /// let mut i = 0;
658    /// let expected = [1, 2];
659    /// for x in &set {
660    ///     assert!(expected.contains(x));
661    ///     i += 1;
662    /// }
663    /// assert_eq!(i, expected.len());
664    /// ```
665    fn sub(self, rhs: &LinearSet<T>) -> LinearSet<T> {
666        self.difference(rhs).cloned().collect()
667    }
668}
669
670/// LinearSet iterator
671pub struct Iter<'a, K: 'a> {
672    iter: Keys<'a, K, ()>
673}
674
675/// LinearSet move iterator
676pub struct IntoIter<K> {
677    iter: super::IntoIter<K, ()>
678}
679
680/// LinearSet drain iterator
681pub struct Drain<'a, K: 'a> {
682    iter: super::Drain<'a, K, ()>,
683}
684
685/// Intersection iterator
686pub struct Intersection<'a, T: 'a> {
687    // iterator of the first set
688    iter: Iter<'a, T>,
689    // the second set
690    other: &'a LinearSet<T>,
691}
692
693/// Difference iterator
694pub struct Difference<'a, T: 'a> {
695    // iterator of the first set
696    iter: Iter<'a, T>,
697    // the second set
698    other: &'a LinearSet<T>,
699}
700
701/// Symmetric difference iterator.
702pub struct SymmetricDifference<'a, T: 'a> {
703    iter: Chain<Difference<'a, T>, Difference<'a, T>>
704}
705
706/// Set union iterator.
707pub struct Union<'a, T: 'a> {
708    iter: Chain<Iter<'a, T>, Difference<'a, T>>
709}
710
711impl<'a, T> IntoIterator for &'a LinearSet<T>
712    where T: Eq
713{
714    type Item = &'a T;
715    type IntoIter = Iter<'a, T>;
716
717    fn into_iter(self) -> Iter<'a, T> {
718        self.iter()
719    }
720}
721
722impl<T> IntoIterator for LinearSet<T>
723    where T: Eq
724{
725    type Item = T;
726    type IntoIter = IntoIter<T>;
727
728    /// Creates a consuming iterator, that is, one that moves each value out
729    /// of the set in arbitrary order. The set cannot be used after calling
730    /// this.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// use linear_map::set::LinearSet;;
736    /// let mut set = LinearSet::new();
737    /// set.insert("a".to_string());
738    /// set.insert("b".to_string());
739    ///
740    /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
741    /// let v: Vec<String> = set.into_iter().collect();
742    ///
743    /// // Will print in an arbitrary order.
744    /// for x in &v {
745    ///     println!("{}", x);
746    /// }
747    /// ```
748    fn into_iter(self) -> IntoIter<T> {
749        IntoIter { iter: self.map.into_iter() }
750    }
751}
752
753impl<'a, K> Clone for Iter<'a, K> {
754    fn clone(&self) -> Iter<'a, K> { Iter { iter: self.iter.clone() } }
755}
756impl<'a, K> Iterator for Iter<'a, K> {
757    type Item = &'a K;
758
759    fn next(&mut self) -> Option<&'a K> { self.iter.next() }
760    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
761}
762impl<'a, K> ExactSizeIterator for Iter<'a, K> {
763    fn len(&self) -> usize { self.iter.len() }
764}
765
766impl<K> Iterator for IntoIter<K> {
767    type Item = K;
768
769    fn next(&mut self) -> Option<K> { self.iter.next().map(|(k, _)| k) }
770    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
771}
772impl<K> ExactSizeIterator for IntoIter<K> {
773    fn len(&self) -> usize { self.iter.len() }
774}
775
776impl<'a, K> Iterator for Drain<'a, K> {
777    type Item = K;
778
779    fn next(&mut self) -> Option<K> { self.iter.next().map(|(k, _)| k) }
780    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
781}
782impl<'a, K> ExactSizeIterator for Drain<'a, K> {
783    fn len(&self) -> usize { self.iter.len() }
784}
785
786impl<'a, T> Clone for Intersection<'a, T> {
787    fn clone(&self) -> Intersection<'a, T> {
788        Intersection { iter: self.iter.clone(), ..*self }
789    }
790}
791
792impl<'a, T> Iterator for Intersection<'a, T>
793    where T: Eq
794{
795    type Item = &'a T;
796
797    fn next(&mut self) -> Option<&'a T> {
798        loop {
799            match self.iter.next() {
800                None => return None,
801                Some(elt) => if self.other.contains(elt) {
802                    return Some(elt)
803                },
804            }
805        }
806    }
807
808    fn size_hint(&self) -> (usize, Option<usize>) {
809        let (_, upper) = self.iter.size_hint();
810        (0, upper)
811    }
812}
813
814impl<'a, T> Clone for Difference<'a, T> {
815    fn clone(&self) -> Difference<'a, T> {
816        Difference { iter: self.iter.clone(), ..*self }
817    }
818}
819
820impl<'a, T> Iterator for Difference<'a, T>
821    where T: Eq
822{
823    type Item = &'a T;
824
825    fn next(&mut self) -> Option<&'a T> {
826        loop {
827            match self.iter.next() {
828                None => return None,
829                Some(elt) => if !self.other.contains(elt) {
830                    return Some(elt)
831                },
832            }
833        }
834    }
835
836    fn size_hint(&self) -> (usize, Option<usize>) {
837        let (_, upper) = self.iter.size_hint();
838        (0, upper)
839    }
840}
841
842impl<'a, T> Clone for SymmetricDifference<'a, T> {
843    fn clone(&self) -> SymmetricDifference<'a, T> {
844        SymmetricDifference { iter: self.iter.clone() }
845    }
846}
847
848impl<'a, T> Iterator for SymmetricDifference<'a, T>
849    where T: Eq
850{
851    type Item = &'a T;
852
853    fn next(&mut self) -> Option<&'a T> { self.iter.next() }
854    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
855}
856
857impl<'a, T> Clone for Union<'a, T> {
858    fn clone(&self) -> Union<'a, T> { Union { iter: self.iter.clone() } }
859}
860
861impl<'a, T> Iterator for Union<'a, T>
862    where T: Eq
863{
864    type Item = &'a T;
865
866    fn next(&mut self) -> Option<&'a T> { self.iter.next() }
867    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
868}
869
870#[allow(dead_code)]
871fn assert_covariance() {
872    fn set<'new>(v: LinearSet<&'static str>) -> LinearSet<&'new str> { v }
873    fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> { v }
874    fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> { v }
875    fn difference<'a, 'new>(v: Difference<'a, &'static str>)
876        -> Difference<'a, &'new str> { v }
877    fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str>)
878        -> SymmetricDifference<'a, &'new str> { v }
879    fn intersection<'a, 'new>(v: Intersection<'a, &'static str>)
880        -> Intersection<'a, &'new str> { v }
881    fn union<'a, 'new>(v: Union<'a, &'static str>)
882        -> Union<'a, &'new str> { v }
883}