use std::{collections::BTreeMap, fmt::Debug};
pub fn map_btree<F, K, V1, V2>(
input: impl IntoIterator<Item = (K, V1)>,
mut f: F,
) -> BTreeMap<K, V2>
where
K: Ord,
F: FnMut(V1) -> V2,
{
input.into_iter().map(|(k, v)| (k, f(v))).collect()
}
pub fn map_btree_ref<'a, F, K, V1, V2>(
input: impl IntoIterator<Item = (&'a K, &'a V1)>,
mut f: F,
) -> BTreeMap<K, V2>
where
K: Ord + Clone + 'static,
V1: 'static,
F: FnMut(&V1) -> V2,
{
input.into_iter().map(|(k, v)| (k.clone(), f(v))).collect()
}
#[derive(Debug, thiserror::Error)]
#[error("Error mapping BTreeMap value for key {key:?}: {error:?}")]
pub struct BtreeMapError<K: Debug, E: Debug> {
key: K,
error: E,
}
pub fn map_btree_fallible<F, K, V1, V2, E>(
input: impl IntoIterator<Item = (K, V1)>,
mut f: F,
) -> Result<BTreeMap<K, V2>, BtreeMapError<K, E>>
where
K: Ord + Debug,
E: Debug,
F: FnMut(V1) -> Result<V2, E>,
{
let mut output = BTreeMap::new();
for (k, v) in input.into_iter() {
match f(v) {
Ok(v) => {
output.insert(k, v);
}
Err(e) => {
return Err(BtreeMapError { key: k, error: e });
}
}
}
Ok(output)
}