Skip to main content

bb_runtime/framework/
peer_gate.rs

1//! `PeerGate` - per-name concurrency limiter used by `Limit.Acquire`
2//! / `Limit.Release` syscalls.
3use std::collections::HashMap;
4
5/// Per-name concurrency limiter.
6#[derive(Default)]
7pub struct PeerGate {
8    inflight: HashMap<String, u32>,
9}
10
11impl PeerGate {
12    /// Construct fresh.
13    pub fn new() -> Self {
14        Self::default()
15    }
16
17    /// Try to acquire one permit. Returns `false` if the current
18    /// `inflight` count for `name` is at or above `n`, else
19    /// increments the counter and returns `true`.
20    pub fn acquire(&mut self, name: &str, n: u32) -> bool {
21        let current = self.inflight.entry(name.to_string()).or_insert(0);
22        if *current >= n {
23            return false;
24        }
25        *current += 1;
26        true
27    }
28
29    /// Release one permit.
30    pub fn release(&mut self, name: &str) {
31        if let Some(c) = self.inflight.get_mut(name) {
32            if *c > 0 {
33                *c -= 1;
34            }
35        }
36    }
37
38    /// Read current inflight count for the named gate.
39    pub fn inflight(&self, name: &str) -> u32 {
40        self.inflight.get(name).copied().unwrap_or(0)
41    }
42}
43