lib.rs 1.9 KB

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