use std::{collections::HashMap, borrow::Borrow}; use crate::message::Link; use std::hash::Hash; pub struct Linkmap { to: HashMap, from: HashMap>, } impl Linkmap { pub fn new() -> Self { Self { to: HashMap::new(), from: HashMap::new(), } } pub fn with_capacity(capacity: usize) -> Self { Self { to: HashMap::with_capacity(capacity), from: HashMap::with_capacity(capacity), } } pub fn get_link(&self, channel: &K) -> Option<&Link> where T: Borrow, K: Hash + Eq + ?Sized { self.to.get(channel) } pub fn get_channels(&self, link: &Link) -> &[T] { self.from.get(link).map(|a| a.as_slice()).unwrap_or(&[]) } pub fn insert(&mut self, link: Link, channel: T) { self.to.insert(channel.clone(), link.clone()); self.from.entry(link) .or_insert(Vec::with_capacity(1)) .push(channel.clone()); } } impl FromIterator<(T, Link)> for Linkmap { fn from_iter>(iter: I) -> Self { let to: HashMap = iter.into_iter().collect(); let mut from = HashMap::with_capacity(to.len()); for (k, v) in &to { from.entry(v.clone()) .or_insert(Vec::with_capacity(1)) .push(k.clone()); } Self { to, from } } }