aboutsummaryrefslogtreecommitdiff
path: root/src/limiter.rs
blob: 97bdb5c5b40900d7ea886523b8c05ceada5a76e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::sync::{atomic::AtomicUsize, Arc};

pub struct Limiter {
    limit: usize,
    counter: Arc<AtomicUsize>,
}

impl Limiter {
    pub fn new(limit: usize) -> Self {
        Limiter {
            counter: Default::default(),
            limit,
        }
    }
    pub fn obtain(&self) -> Option<LimitLock> {
        let c = self
            .counter
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if c < self.limit {
            Some(LimitLock {
                counter: self.counter.clone(),
            })
        } else {
            None
        }
    }
}

pub struct LimitLock {
    counter: Arc<AtomicUsize>,
}
impl Drop for LimitLock {
    fn drop(&mut self) {
        self.counter
            .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}