9 releases

0.0.11 Jan 7, 2025
0.0.10 Dec 13, 2024
0.0.5 Nov 30, 2024
0.0.1 Oct 17, 2024

#108 in #sync

Download history 138/week @ 2024-10-15 9/week @ 2024-10-22 341/week @ 2024-11-05 65/week @ 2024-11-12 25/week @ 2024-11-19 229/week @ 2024-11-26 313/week @ 2024-12-03 228/week @ 2024-12-10 15/week @ 2024-12-17 136/week @ 2025-01-07

169 downloads per month

MIT license

18KB
249 lines

OnceInit

#[cfg(test)]
mod tests {

    // log 门面库的类似实现。
    mod log {
        use crate::{
            OnceInit,
            StaticDefault,
        };
        pub trait Logger: Send + Sync {
            fn log(&self, msg: &str);
        }
        pub static LOGGER: OnceInit<dyn Logger> = OnceInit::new();
        
        // 只有 `T` 实现了 `StaticDefault`, `OnceInit<T>` 才会实现 `Deref<Target = T>`.
        struct DefaultLogger;
        impl Logger for DefaultLogger {
            fn log(&self, _msg: &str) {
                // do nothing.
            }
        }
        impl StaticDefault for dyn Logger {
            fn static_default() -> &'static Self {
                static NOP: DefaultLogger = DefaultLogger;
                &NOP
            }
        }
    }
    mod a_logger {
        use crate::OnceInitError;
        // 一个简单的 a_logger crate.
        use super::log::{
            Logger,
            LOGGER,
        };
        pub struct ALogger;

        impl Logger for ALogger {
            fn log(&self, msg: &str) {
                println!("{msg}");
            }
        }

        impl ALogger {
            pub fn init() -> Result<(), OnceInitError> {
                LOGGER.set_boxed_data(Box::new(ALogger))
            }
        }
    }
    mod hello_world {
        use crate::tests::log::LOGGER;

        pub fn hello_world() {
            LOGGER.log("Hello, world!");
        }
    }
    #[test]
    fn test_logger() {
        a_logger::ALogger::init().unwrap();
        hello_world::hello_world();
    }
}

LICENSE

LICENSE

No runtime deps

Features