xref: /DragonOS/kernel/src/libs/ida/src/lib.rs (revision 77799ccaaca276fe127448d169f0e035837cce44)
1 #![no_std]
2 #![feature(core_intrinsics)]
3 
4 use core::intrinsics::unlikely;
5 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6 
7 /// id分配器
8 ///
9 /// TODO: 当前只是为了简单实现功能,将来这里应使用类似linux的ida的方式去实现
10 #[derive(Debug)]
11 pub struct IdAllocator {
12     current_id: AtomicUsize,
13     max_id: usize,
14     dead: AtomicBool,
15 }
16 
17 impl IdAllocator {
18     /// 创建一个新的id分配器
19     pub const fn new(max_id: usize) -> Self {
20         Self {
21             current_id: AtomicUsize::new(0),
22             max_id,
23             dead: AtomicBool::new(false),
24         }
25     }
26 
27     /// 分配一个新的id
28     ///
29     /// ## 返回
30     ///
31     /// 如果分配成功,返回Some(id),否则返回None
32     pub fn alloc(&self) -> Option<usize> {
33         if unlikely(self.dead.load(Ordering::SeqCst)) {
34             return None;
35         }
36 
37         let ret = self.current_id.fetch_add(1, Ordering::SeqCst);
38         // 如果id溢出,panic
39         if ret == self.max_id {
40             self.dead.store(true, Ordering::SeqCst);
41             return None;
42         }
43 
44         return Some(ret);
45     }
46 
47     pub fn free(&self, _id: usize) {
48         // todo: free
49     }
50 }
51