Last active
March 16, 2020 19:47
-
-
Save NebulaFox/0f0480b51bd85df8be2ef591657164b6 to your computer and use it in GitHub Desktop.
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
use std::collections::HashSet; | |
#[derive(Debug)] | |
enum Check<'a> { | |
Known(&'a str), | |
Duplicate(&'a str), | |
Missing(&'a str), | |
Unknown(&'a str) | |
} | |
fn main() { | |
// clone of &str returns itself | |
let known_values: HashSet<_> = ["a","b","c"] | |
.iter().cloned().collect(); | |
// provided a Vec<String> | |
// from deserialized data for example | |
let provided_values:Vec<String> = vec![ | |
"a".to_string(), | |
"b".to_string(), | |
"z".to_string(), | |
"b".to_string()]; | |
// coerce into immutable &str | |
let im_provided_values: Vec<&str> = provided_values.iter().map(String::as_str).collect(); | |
// hash set of references | |
let mut found: HashSet<&str> = HashSet::new(); | |
// move provided_values | |
let mut check_values: Vec<_> = im_provided_values.into_iter() | |
.map(|v| { | |
if known_values.contains(&v) { | |
if found.contains(&v) { | |
Check::Duplicate(v) | |
} else { | |
found.insert(&v); | |
Check::Known(v) | |
} | |
} else { | |
Check::Unknown(v) | |
} | |
}).collect(); | |
let missing = known_values.difference(&found); | |
// move missing | |
check_values = missing | |
.fold(check_values, |mut cv, m| { | |
cv.push(Check::Missing(m)); | |
cv | |
}); | |
println!("{:#?}", check_values) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment