stringqb/src/fns.rs

45 lines
982 B
Rust

//! Utility / Helper functions that don't really belong anywhere else
use std::any::Any;
/// Split a string, apply a closure to each substring,
/// then join the string back together
///
/// For example:
/// ```
/// use stringqb::fns::split_map_join;
///
/// let result = split_map_join("a\n,b, c\t,d", ",", |s| s.trim().to_string());
/// assert_eq!("a,b,c,d", result);
/// ```
pub fn split_map_join<'a>(
string: &'a str,
split_join_by: &str,
map_fn: impl (FnMut(&'a str) -> String),
) -> String {
string
.split(split_join_by)
.into_iter()
.map(map_fn)
.collect::<Vec<String>>()
.join(split_join_by)
}
pub fn get_typed_ref<T: 'static>(val: &Any) -> Option<&T> {
if ! val.is::<T>() {
return None;
}
val.downcast_ref::<T>()
}
pub fn get_typed_mut<T: 'static>(val: &mut Any) -> Option<&mut T> {
if ! val.is::<T>() {
return None;
}
val.downcast_mut::<T>()
}
#[cfg(test)]
mod tests {}