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

FUJITA Tomonori
2025-11-06T00:34:18Z

On Wed, 5 Nov 2025 10:32:41 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> 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)*
> })
> }};
> }

Indeed, looks more readable and flexible. I'll use the syntax in the
next version.

Thanks!