Hi there, I've been working on a little tool and wrote this function to check whether an input string is a valid UUID (example: 2a1c18cb-1bc6-4520-bdc3-09139558b783
). I'm looking for feedback on how to make this function more concise or perform better. I've been interested in and trying to get better at using iterators and method chains for string processing, so I'm not interested in solutions that use for loops or anything like that, even if they would be better (but feel free to share them nonetheless if you think they're particularly good or interesting).
pub async fn match_uuid(string: &str) -> Option<Uuid> {
// Check if there are exactly 5 segments. This is necessary because the `zip()` method only
// runs for the first 5 segments and will ignore anything that comes after.
if !(string.split('-').count() == 5) {
return None;
}
// Check if segments of the UUID are the proper lengths and if they are made up of hex digits.
let segment_lengths = [8, 4, 4, 4, 12];
string
.split('-')
.zip(segment_lengths)
.all(|(seg, len)| is_hexstring_of_len(seg, len))
.then(|| Uuid {
likely_genuine: is_genuine_hash(
&string
.chars()
.filter(|c| c.is_ascii_hexdigit())
.collect::<String>(),
)
.unwrap(),
})
}
I'm also curious if there's a neat way, or a way at all, to do the is_hexstring_of_len
function as a single chain of methods, instead of needing to do the length check 'separately':
pub fn is_hexstring_of_len(string: &str, len: usize) -> bool {
string.len() == len && string.chars().all(|c| c.is_ascii_hexdigit())
}