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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use alloc::vec::Vec;

use lazy_static::lazy_static;

use crate::sync::Mutex;

pub type Pid = usize;

pub struct PidHandle {
    pid: Pid,
}

impl PidHandle {
    pub fn new(pid: Pid) -> Self {
        Self { pid }
    }

    pub fn pid(&self) -> Pid {
        self.pid
    }
}

impl Drop for PidHandle {
    fn drop(&mut self) {
        PID_ALLOCATOR.lock().deallocate(self.pid);
    }
}

pub struct PidAllocator {
    state: Pid,
    deallocated_pid: Vec<Pid>,
}

impl PidAllocator {
    pub fn new() -> Self {
        PidAllocator {
            state: 0,
            deallocated_pid: Vec::new(),
        }
    }

    pub fn allocate(&mut self) -> PidHandle {
        if let Some(pid) = self.deallocated_pid.pop() {
            PidHandle::new(pid)
        } else {
            let pid_handle = PidHandle::new(self.state);
            self.state += 1;
            pid_handle
        }
    }

    pub fn deallocate(&mut self, pid: Pid) {
        self.deallocated_pid.push(pid);
    }
}

lazy_static! {
    static ref PID_ALLOCATOR: Mutex<PidAllocator> = Mutex::new(PidAllocator::new());
}

pub fn allocate_pid() -> PidHandle {
    PID_ALLOCATOR.lock().allocate()
}