Re: [PATCH v1 1/2] rust: Add support for calling a function exactly once

Alice Ryhl
2025-11-05T10:32:43Z

On Wed, Nov 05, 2025 at 02:47:30PM +0900, FUJITA Tomonori wrote:
> Add the Rust equivalent of the kernel's `DO_ONCE_LITE` macro. While it
> would be possible to implement the feature entirely as a Rust macro,
> the functionality that can be implemented as regular functions has
> been extracted and implemented as the `OnceLite` struct for better
> code maintainability.
>
> Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>

The OnceLite implementation LGTM, but I have suggestions for the macro.

> +/// Run the given function exactly once.
> +///
> +/// This is equivalent to the kernel's `DO_ONCE_LITE` macro.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// kernel::do_once_lite!(|| {
> +/// kernel::pr_info!("This will be printed only once\n");
> +/// });
> +/// ```
> +#[macro_export]
> +macro_rules! do_once_lite {
> + ($e:expr) => {{
> + #[link_section = ".data..once"]
> + static ONCE: $crate::once_lite::OnceLite = $crate::once_lite::OnceLite::new();
> + ONCE.call_once($e)
> + }};
> +}

Wouldn't it be nicer if the macro syntax looks like this?

kernel::do_once_lite! {
kernel::pr_info!("This will be printed only once\n");
}

You might implement it like this:

macro_rules! do_once_lite {
{ $($e:tt)* } => {{
#[link_section = ".data..once"]
static ONCE: $crate::once_lite::OnceLite = $crate::once_lite::OnceLite::new();
ONCE.call_once(|| {
$($e)*
})
}};
}

Alice