You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.4 KiB
55 lines
1.4 KiB
//! Utilities for internal use and other cool stuff
|
|
|
|
use std::collections::HashMap;
|
|
use std::hash::Hash;
|
|
|
|
/// drain_filter() implemented for HashMap. It returns the removed items as a Vec
|
|
pub fn map_drain_filter<K: Eq + Hash, V>(
|
|
map: &mut HashMap<K, V>,
|
|
filter: impl Fn(&K, &V) -> bool,
|
|
) -> Vec<(K, V)> {
|
|
let mut removed = vec![];
|
|
let mut retain = vec![];
|
|
for (k, v) in map.drain() {
|
|
if filter(&k, &v) {
|
|
removed.push((k, v));
|
|
} else {
|
|
retain.push((k, v));
|
|
}
|
|
}
|
|
map.extend(retain);
|
|
removed
|
|
}
|
|
|
|
/// Get the first or second item from a Vec of (Key, Value) pairs.
|
|
/// Use when only one part of the pair is needed
|
|
pub trait KVVecToKeysOrValues<K, V> {
|
|
/// Get the first item of each tuple
|
|
fn keys(self) -> Vec<K>;
|
|
/// Get the second item of each tuple
|
|
fn values(self) -> Vec<V>;
|
|
}
|
|
|
|
impl<K, V> KVVecToKeysOrValues<K, V> for Vec<(K, V)> {
|
|
fn keys(self) -> Vec<K> {
|
|
self.into_iter().map(|(k, _v)| k).collect()
|
|
}
|
|
|
|
fn values(self) -> Vec<V> {
|
|
self.into_iter().map(|(_k, v)| v).collect()
|
|
}
|
|
}
|
|
|
|
pub(crate) trait IsNoneOrElse<T>: Sized {
|
|
//noinspection RsSelfConvention
|
|
fn is_none_or_else(&self, test: impl FnOnce(&T) -> bool) -> bool;
|
|
}
|
|
|
|
impl<T> IsNoneOrElse<T> for Option<T> {
|
|
fn is_none_or_else(&self, test: impl FnOnce(&T) -> bool) -> bool {
|
|
match self {
|
|
None => true,
|
|
Some(value) => test(value),
|
|
}
|
|
}
|
|
}
|
|
|