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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#![no_std]

extern crate alloc;

use core::ops::Deref;

use alloc::sync::Arc;
use spin::mutex::SpinMutex;

/// A thread-safe PID allocator that can allocate and recycle PIDs efficiently.
/// It encapsulates the allocator's state within an `Arc<SpinMutex<...>>` to allow safe shared access across threads.
#[derive(Debug, Default)]
pub struct PidAllocator<const ORDER: usize> {
    inner: Arc<SpinMutex<PidAllocatorInner<ORDER>>>,
}

/// The internal state of the PID allocator, containing the layers of available PIDs.
#[derive(Debug)]
pub struct PidAllocatorInner<const ORDER: usize> {
    top_layer: usize,
    bottom_layers: [usize; ORDER],
}

impl<const ORDER: usize> PidAllocator<ORDER> {
    /// Creates a new instance of the PID allocator.
    ///
    /// This constructor initializes the PID allocator, setting up its internal
    /// structure to keep track of allocated and available PIDs. The allocator
    /// supports up to `ORDER * usize::BITS` unique PIDs, where `ORDER` is a
    /// compile-time constant defining the number of layers in the allocator.
    ///
    /// # Examples
    ///
    /// ```
    /// let allocator = PidAllocator::<8>::new();
    /// ```
    ///
    /// This creates a PID allocator with 8 layers, capable of managing
    /// a total of `8 * usize::BITS` PIDs, which depends on the architecture
    /// (e.g., 256 PIDs for a 32-bit architecture or 512 PIDs for a 64-bit architecture).
    pub fn new() -> Self {
        Self {
            inner: Arc::new(SpinMutex::new(PidAllocatorInner::new())),
        }
    }

    /// Attempts to allocate a new PID. Returns `Some(Pid)` if successful, or `None` if all PIDs are currently allocated.
    /// The allocated PID is wrapped in a `Pid` object, which will automatically recycle the PID when dropped.
    ///
    /// This method locks the internal state, searches for a free PID, marks it as used,
    /// and returns a `Pid` instance representing the allocated PID. If no PIDs are available,
    /// it returns `None`.
    ///
    /// # Returns
    ///
    /// * `Some(Pid<ORDER>)` containing the allocated PID if allocation is successful.
    /// * `None` if all PIDs are already allocated.
    ///
    /// # Examples
    ///
    /// Successful allocation:
    ///
    /// ```
    /// let allocator = PidAllocator::<8>::new();
    /// if let Some(pid) = allocator.allocate() {
    ///     println!("Allocated PID: {}", *pid);
    /// }
    /// ```
    ///
    /// Handling failure to allocate a PID:
    ///
    /// ```
    /// let allocator = PidAllocator::<8>::new();
    /// let mut pids = Vec::new();
    /// while let Some(pid) = allocator.allocate() {
    ///     pids.push(pid);
    /// }
    /// // At this point, no more PIDs can be allocated.
    /// assert!(allocator.allocate().is_none());
    /// ```
    ///
    /// In this example, PIDs are continuously allocated until no more are available,
    /// at which point `allocate()` returns `None`.
    pub fn allocate(&self) -> Option<Pid<ORDER>> {
        let mut inner = self.inner.lock();
        inner.allocate().map(|number| Pid {
            number,
            allocator: self.inner.clone(),
        })
    }

    /// Checks whether a given PID is currently allocated.
    ///
    /// # Parameters
    /// 
    /// * `number`: The PID number to check for allocation.
    ///
    /// # Returns
    /// 
    /// * `true` if the PID is currently allocated.
    /// * `false` otherwise.
    ///
    /// # Example
    ///
    /// ```
    /// let allocator = PidAllocator::<32>::new();
    /// let pid = allocator.allocate().expect("Failed to allocate PID");
    /// 
    /// assert!(allocator.contains(*pid), "The PID should be marked as allocated.");
    /// ```
    ///
    /// # Note
    ///
    /// This method performs a read-only operation on the allocator's state and is thread-safe,
    /// thanks to the internal use of `Arc<SpinMutex<...>>`. However, because the state of the allocator
    /// can change in concurrent environments, the returned allocation state might not remain valid
    /// immediately after this method is called.
    pub fn contains(&self, number: usize) -> bool {
        self.inner.lock().contains(number)
    }
}

impl<const ORDER: usize> PidAllocatorInner<ORDER> {
    fn new() -> Self {
        Self {
            top_layer: 0,
            bottom_layers: [0; ORDER],
        }
    }

    /// Allocates a PID from the internal state. This method should only be called with exclusive access to the state.
    pub fn allocate(&mut self) -> Option<usize> {
        for (index, &layer) in self.bottom_layers.iter().enumerate() {
            if layer != usize::MAX {
                let free_bit = (!layer).trailing_zeros() as usize;
                self.bottom_layers[index] |= 1 << free_bit;
                if self.bottom_layers[index] == usize::MAX {
                    self.top_layer |= 1 << index;
                }
                return Some(index * (usize::BITS as usize) + free_bit);
            }
        }
        None
    }

    /// Recycles the given PID, making it available for allocation again.
    pub fn recycle(&mut self, number: usize) {
        const BITS_PER_LAYER_SHIFT: usize = usize::BITS.trailing_zeros() as usize;

        let layer_index = number >> BITS_PER_LAYER_SHIFT;
        let bit_index = number & (usize::BITS - 1) as usize;

        self.bottom_layers[layer_index] &= !(1 << bit_index);
        self.top_layer &= !(1 << layer_index);
    }

    /// Checks whether a given PID is currently allocated.
    pub fn contains(&self, number: usize) -> bool {
        const BITS_PER_LAYER_SHIFT: usize = usize::BITS.trailing_zeros() as usize;
        let layer_index = number >> BITS_PER_LAYER_SHIFT;
        let bit_index = number & ((1 << BITS_PER_LAYER_SHIFT) - 1);

        if layer_index < self.bottom_layers.len() {
            (self.bottom_layers[layer_index] & (1 << bit_index)) != 0
        } else {
            false
        }
    }
}

impl<const ORDER: usize> Default for PidAllocatorInner<ORDER> {
    fn default() -> Self {
        Self::new()
    }
}

/// A handle to an allocated PID. When dropped, the PID is automatically recycled back into the allocator.
#[derive(Debug)]
pub struct Pid<const ORDER: usize> {
    number: usize,
    allocator: Arc<SpinMutex<PidAllocatorInner<ORDER>>>,
}

impl<const ORDER: usize> Deref for Pid<ORDER> {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        &self.number
    }
}

impl<const ORDER: usize> Drop for Pid<ORDER> {
    fn drop(&mut self) {
        self.allocator.lock().recycle(self.number);
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;

    use super::*;

    const ORDER: usize = 32;

    #[test]
    fn pid_allocate_success() {
        let allocator = PidAllocator::<ORDER>::new();
        assert!(allocator.allocate().is_some());
    }

    #[test]
    fn pid_allocate_unique() {
        let allocator = PidAllocator::<ORDER>::new();
        let pid1 = allocator.allocate().expect("Failed to allocate PID 1");
        let pid2 = allocator.allocate().expect("Failed to allocate PID 2");
        assert_ne!(*pid1, *pid2, "Allocated PIDs should be unique");
    }

    #[test]
    fn pid_recycle_and_reallocate() {
        let allocator = PidAllocator::<ORDER>::new();

        {
            let _pid = allocator.allocate().expect("Failed to allocate PID");
        }

        let mut pids = Vec::new();
        for _ in 0..ORDER * usize::BITS as usize {
            if let Some(pid) = allocator.allocate() {
                pids.push(*pid);
            } else {
                panic!("Failed to allocate a new PID after recycling");
            }
        }

        assert_eq!(
            pids.len(),
            ORDER * usize::BITS as usize,
            "Not all PIDs were successfully re-allocated"
        );
    }

    #[test]
    fn test_contains_allocated_pid() {
        let allocator = PidAllocator::<ORDER>::new();
        let pid = allocator.allocate().expect("Failed to allocate PID");
        assert!(allocator.contains(*pid), "Allocated PID should be recognized as allocated");
    }

    #[test]
    fn test_recycle_pid() {
        let allocator = PidAllocator::<ORDER>::new();
        let pid = allocator.allocate().expect("Failed to allocate PID");
        let pid_value = *pid;
        core::mem::drop(pid); // Drop to trigger recycle
        assert!(!allocator.contains(pid_value), "Recycled PID should not be recognized as allocated");
    }

    #[test]
    fn test_contains_unallocated_pid() {
        let allocator = PidAllocator::<ORDER>::new();
        // 假设每个ORDER位都可以分配usize::BITS个PID,取一个足够大的数字以超过可能分配的PID范围
        let unallocated_pid = ORDER * usize::BITS as usize * 2; 
        assert!(!allocator.contains(unallocated_pid), "Unallocated PID should not be recognized as allocated");
    }
}