Skip to content

Instantly share code, notes, and snippets.

@xpe xpe/pair_set.rs
Created Jan 24, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.