xref: /DragonOS/kernel/crates/unified-init/src/lib.rs (revision f2022a8a1cc4a8e2a85e9061e036e9c491a2fa00)
1 #![no_std]
2 
3 use system_error::SystemError;
4 pub use unified_init_macros as macros;
5 
6 /// 统一初始化器
7 #[derive(Debug)]
8 pub struct UnifiedInitializer {
9     function: &'static UnifiedInitFunction,
10     name: &'static str,
11 }
12 
13 impl UnifiedInitializer {
14     pub const fn new(
15         name: &'static str,
16         function: &'static UnifiedInitFunction,
17     ) -> UnifiedInitializer {
18         UnifiedInitializer { function, name }
19     }
20 
21     /// 调用初始化函数
22     pub fn call(&self) -> Result<(), SystemError> {
23         (self.function)()
24     }
25 
26     /// 获取初始化函数的名称
27     pub const fn name(&self) -> &'static str {
28         self.name
29     }
30 }
31 
32 pub type UnifiedInitFunction = fn() -> core::result::Result<(), SystemError>;
33 
34 /// 定义统一初始化器的分布式切片数组(私有)
35 #[macro_export]
36 macro_rules! define_unified_initializer_slice {
37     ($name:ident) => {
38         #[::linkme::distributed_slice]
39         static $name: [::unified_init::UnifiedInitializer] = [..];
40     };
41     () => {
42         compile_error!(
43             "define_unified_initializer_slice! requires at least one argument: slice_name"
44         );
45     };
46 }
47 
48 /// 定义统一初始化器的分布式切片数组(公开)
49 #[macro_export]
50 macro_rules! define_public_unified_initializer_slice {
51     ($name:ident) => {
52         #[::linkme::distributed_slice]
53         pub static $name: [::unified_init::UnifiedInitializer] = [..];
54     };
55     () => {
56         compile_error!(
57             "define_unified_initializer_slice! requires at least one argument: slice_name"
58         );
59     };
60 }
61 
62 /// 调用指定数组中的所有初始化器
63 #[macro_export]
64 macro_rules! unified_init {
65     ($initializer_slice:ident) => {
66         for initializer in $initializer_slice.iter() {
67             initializer.call().unwrap_or_else(|e| {
68                 kerror!("Failed to call initializer {}: {:?}", initializer.name(), e);
69             });
70         }
71     };
72 }
73