utils module

master
Ondřej Hruška 4 years ago
parent b4dbb94e27
commit f8020a01f9
Signed by: MightyPork
GPG Key ID: 2C5FD5035250423D
  1. 31
      src/cool.rs
  2. 4
      src/main.rs
  3. 33
      src/yopa.rs

@ -0,0 +1,31 @@
use std::hash::Hash;
use std::collections::HashMap;
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
}
pub trait KVVecToKeysOrValues<K, V> {
fn keys(self) -> Vec<K>;
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()
}
}

@ -5,8 +5,8 @@ use log::LevelFilter;
mod yopa; mod yopa;
use yopa::model; use yopa::model;
use yopa::model::DataType; use yopa::model::DataType;
use crate::yopa::model::TypedValue;
use anyhow::Error; mod cool;
fn main() { fn main() {
simple_logging::log_to_stderr(LevelFilter::Debug); simple_logging::log_to_stderr(LevelFilter::Debug);

@ -1,8 +1,8 @@
use std::collections::{HashMap}; use std::collections::{HashMap};
use std::iter::Extend;
use crate::yopa::model::{ObjectTemplate, ID}; use crate::yopa::model::{ObjectTemplate, ID};
use thiserror::Error; use thiserror::Error;
use std::hash::Hash;
use crate::cool::{map_drain_filter, KVVecToKeysOrValues};
/// Data model structs and enums /// Data model structs and enums
pub mod model { pub mod model {
@ -268,32 +268,3 @@ impl InMemoryStorage {
} }
} }
} }
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
}
trait KVVecToKeysOrValues<K, V> {
fn keys(self) -> Vec<K>;
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()
}
}

Loading…
Cancel
Save