55 lines
1.3 KiB
Rust
55 lines
1.3 KiB
Rust
use std::{collections::HashMap, borrow::Borrow};
|
|
|
|
use crate::message::Link;
|
|
use std::hash::Hash;
|
|
|
|
pub struct Linkmap<T: Hash + Eq + Clone> {
|
|
to: HashMap<T, Link>,
|
|
from: HashMap<Link, Vec<T>>,
|
|
}
|
|
|
|
impl <T: Hash + Eq + Clone> Linkmap<T> {
|
|
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<K>(&self, channel: &K) -> Option<&Link>
|
|
where T: Borrow<K>, 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 <T: Hash + Eq + Clone> FromIterator<(T, Link)> for Linkmap<T> {
|
|
fn from_iter<I: IntoIterator<Item=(T, Link)>>(iter: I) -> Self {
|
|
let to: HashMap<T, Link> = 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 }
|
|
}
|
|
}
|