maybe-once

What is this?
maybe-once offers a variation of OnceLock that keeps track of the number of references to the internal data
and drops it every time the references counter goes to 0.
Why is this useful?
In Rust static variables are not dropped when the program terminates. This is a problem when you need to initialize a shared resource that must be dropped when it is no longer used or when the process terminates. This happens, for example, when you a have a common resource to be usued by a set of integration tests, and you want it to be dropped when the tests terminates.
Usage examples
mod test {
use std::sync::OnceLock;
use maybe_once::blocking::{Data, MaybeOnce};
fn init() -> String {
"hello".to_string()
}
fn init2() -> String {
"hello".to_string()
}
#[test]
fn test1() {
let data = data(false);
println!("{}", *data);
}
#[test]
fn test2() {
let data = data(false);
println!("{}", *data);
}
#[test]
fn test3() {
let data = data(false);
println!("{}", *data);
}
}
Usage with tokio
The tokio feature of this crate allows you to use the optional MaybeOnceAsync object to initialize a shared resource using an async function.
#[cfg(feature = "tokio")]
mod test {
use std::sync::OnceLock;
use maybe_once::tokio::{Data, MaybeOnceAsync};
async fn init() -> String {
"hello".to_string()
}
#[tokio::test]
async fn test1() {
let data = data(false).await;
println!("{}", *data);
}
#[tokio::test]
async fn test2() {
let data = data(false).await;
println!("{}", *data);
}
#[tokio::test]
async fn test3() {
let data = data(false).await;
println!("{}", *data);
}
}