This commit is contained in:
Aram 🍐 2021-10-14 21:31:09 -04:00
parent bf489900e6
commit ccb51fe5f8
3 changed files with 190 additions and 15 deletions

View file

@ -7,23 +7,37 @@ const MAX_PORT: u16 = 60999;
const PORT_RANGE: Range<u16> = MIN_PORT..MAX_PORT;
pub struct PortPool {
/// Remaining ports
inner: lockfree::queue::Queue<u16>,
/// Ports in use
taken: lockfree::set::Set<u16>,
}
impl PortPool {
pub fn new() -> Self {
let inner = lockfree::queue::Queue::default();
PORT_RANGE.for_each(|p| inner.push(p) as ());
Self { inner }
Self {
inner,
taken: lockfree::set::Set::new(),
}
}
pub fn next(&self) -> anyhow::Result<u16> {
self.inner
let port = self
.inner
.pop()
.with_context(|| "Virtual port pool is exhausted")
.with_context(|| "Virtual port pool is exhausted")?;
self.taken.insert(port);
Ok(port)
}
pub fn release(&self, port: u16) {
self.inner.push(port);
self.taken.remove(&port);
}
pub fn is_in_use(&self, port: u16) -> bool {
self.taken.contains(&port)
}
}