Skip to content
This repository was archived by the owner on May 14, 2026. It is now read-only.

once: add Once::init_from_ref() method - #179

Merged
zesterer merged 2 commits into
zesterer:masterfrom
00xc:once/init_from_ref
Dec 8, 2025
Merged

zesterer merged 2 commits into
zesterer:masterfrom
00xc:once/init_from_ref

Conversation

@00xc

@00xc 00xc commented Dec 3, 2025

Copy link
Copy Markdown
Contributor

Add a Once::init_from_ref() method, which initializes the Once only once by copying from a &T. This is a simpler initialization method that can be used to avoid expensive copies to the stack in debug builds, since the compiler might not be able to optimize away the move of the value into the internal cell.

The method has a very simple signature:

pub fn init_from_ref(&self, value: &T) -> &T
    where
        T: Copy,

To implement this reusing the existing functionality I had to refactor some code out of try_call_once_slow into separate methods.

During the initialization of Once, several operations need to be
performed on the internal atomic status to properly get the right
to initialize the internal cell. Abstract these operations away into
separate methods, in preparation for a new initialization method that
will reuse this functionality.
@00xc
00xc force-pushed the once/init_from_ref branch from 295ff90 to e956fa5 Compare December 3, 2025 14:14

@zesterer zesterer left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. I think this is a good change, and the implementation passes the sniff test. I've just one comment.

Comment thread src/once.rs Resolved
Add a method to initialize a Once from a reference to a &T (which
implements Copy). This method can be used to avoid expensive copies into
the stack in debug builds, which might not be able to optimize away the
moving of the value into the internal cell.

Add as well a basic test to ensure the functionality is correct.
@00xc
00xc force-pushed the once/init_from_ref branch from e956fa5 to 267273e Compare December 8, 2025 22:19
@zesterer

zesterer commented Dec 8, 2025

Copy link
Copy Markdown
Owner

Thanks!

@zesterer
zesterer merged commit efe8e74 into zesterer:master Dec 8, 2025
5 of 6 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants