veilid/veilid-core/src/connection_table.rs

52 lines
1.4 KiB
Rust
Raw Normal View History

2022-01-04 04:58:26 +00:00
use crate::network_connection::*;
2021-11-22 16:28:30 +00:00
use crate::xx::*;
use crate::*;
#[derive(Debug)]
pub struct ConnectionTable {
2022-01-04 04:58:26 +00:00
conn_by_addr: BTreeMap<ConnectionDescriptor, NetworkConnection>,
2021-11-22 16:28:30 +00:00
}
impl ConnectionTable {
pub fn new() -> Self {
Self {
conn_by_addr: BTreeMap::new(),
2021-11-22 16:28:30 +00:00
}
}
2022-01-04 04:58:26 +00:00
pub fn add_connection(&mut self, conn: NetworkConnection) -> Result<(), String> {
let descriptor = conn.connection_descriptor();
2021-11-22 16:28:30 +00:00
assert_ne!(
descriptor.protocol_type(),
ProtocolType::UDP,
"Only connection oriented protocols go in the table!"
);
if self.conn_by_addr.contains_key(&descriptor) {
2021-12-14 14:48:33 +00:00
return Err(format!(
"Connection already added to table: {:?}",
descriptor
));
2021-11-22 16:28:30 +00:00
}
2022-01-04 14:53:30 +00:00
let res = self.conn_by_addr.insert(descriptor, conn);
2021-11-22 16:28:30 +00:00
assert!(res.is_none());
2022-01-04 14:53:30 +00:00
Ok(())
2021-11-22 16:28:30 +00:00
}
2022-01-04 14:53:30 +00:00
pub fn get_connection(&self, descriptor: &ConnectionDescriptor) -> Option<NetworkConnection> {
self.conn_by_addr.get(descriptor).cloned()
2021-11-22 16:28:30 +00:00
}
pub fn connection_count(&self) -> usize {
self.conn_by_addr.len()
2021-11-22 16:28:30 +00:00
}
pub fn remove_connection(
&mut self,
2021-11-22 16:28:30 +00:00
descriptor: &ConnectionDescriptor,
2022-01-04 14:53:30 +00:00
) -> Result<NetworkConnection, String> {
self.conn_by_addr
.remove(descriptor)
.ok_or_else(|| format!("Connection not in table: {:?}", descriptor))
2021-11-22 16:28:30 +00:00
}
}