Created
January 21, 2022 21:45
-
-
Save nilz3ro/a7b9d74e2dd6aa12d9b4e5d4ac609525 to your computer and use it in GitHub Desktop.
Trait example
This file contains 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
#[derive(Debug, PartialEq)] | |
pub enum Comparison { | |
Equal, | |
Sublist, | |
Superlist, | |
Unequal, | |
} | |
trait IncludedIn { | |
fn included_in(&self, rhs: Self) -> bool; | |
} | |
impl<T: PartialEq> IncludedIn for &[T] { | |
fn included_in(&self, rhs: Self) -> bool { | |
if self.is_empty() && !rhs.is_empty() { | |
return true; | |
} | |
for window in rhs.windows(self.len()) { | |
if &window == self { | |
return true; | |
} | |
} | |
false | |
} | |
} | |
pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> Comparison { | |
if first_list == second_list { | |
Comparison::Equal | |
} else if first_list.included_in(second_list) { | |
Comparison::Sublist | |
} else if second_list.included_in(first_list) { | |
Comparison::Superlist | |
} else { | |
Comparison::Unequal | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment