Created
January 24, 2017 00:03
-
-
Save xpe/9f8d949320402edf89cac22d6096d500 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct PairSet<T> { | |
a: T, | |
b: T, | |
} | |
impl<T> PairSet<T> where T: Eq { | |
/// If the values are different, creates a `PairSet` with them. | |
pub fn new(x: T, y: T) -> Option<PairSet<T>> { | |
if x == y { | |
None | |
} else { | |
Some(PairSet { a: x, b: y }) | |
} | |
} | |
} | |
impl<T> PairSet<T> where T: Eq { | |
/// Returns true if the `PairSet` contains a value. | |
pub fn contains(&self, x: T) -> bool { | |
self.a == x || self.b == x | |
} | |
} | |
impl<T> PartialEq for PairSet<T> where T: Eq { | |
/// Returns true if the `PairSet` is equal to another. | |
fn eq(&self, other: &PairSet<T>) -> bool { | |
(self.a == other.a && self.b == other.b) || | |
(self.a == other.b && self.b == other.a) | |
} | |
} | |
impl<T> Eq for PairSet<T> where T: Eq {} | |
// ----- consuming iterator ----- | |
pub struct IntoIter<T> { | |
pair_set: PairSet<T>, | |
index: usize, | |
} | |
impl<T> IntoIterator for PairSet<T> where T: Clone { | |
type Item = T; | |
type IntoIter = IntoIter<T>; | |
fn into_iter(self) -> Self::IntoIter { | |
IntoIter { pair_set: self, index: 0 } | |
} | |
} | |
impl<T> Iterator for IntoIter<T> where T: Clone { | |
type Item = T; | |
fn next(&mut self) -> Option<T> { | |
let result = match self.index { | |
0 => Some(self.pair_set.a.clone()), | |
1 => Some(self.pair_set.b.clone()), | |
_ => return None, | |
}; | |
self.index += 1; | |
result | |
} | |
} | |
// ----- non-consuming iterator ----- | |
pub struct Iter<'a, T: 'a> { | |
pair_set: &'a PairSet<T>, | |
index: usize, | |
} | |
impl<'a, T> IntoIterator for &'a PairSet<T> where T: Clone { | |
type Item = T; | |
type IntoIter = Iter<'a, T>; | |
fn into_iter(self) -> Self::IntoIter { | |
Iter { pair_set: self, index: 0 } | |
} | |
} | |
impl<'a, T> Iterator for Iter<'a, T> where T: Clone { | |
type Item = T; | |
fn next(&mut self) -> Option<T> { | |
let result = match self.index { | |
0 => Some(self.pair_set.a.clone()), | |
1 => Some(self.pair_set.b.clone()), | |
_ => return None, | |
}; | |
self.index += 1; | |
result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment