-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement ACP 429: add Lazy{Cell,Lock}::get[_mut]
and force_mut
#130476
Merged
bors
merged 3 commits into
rust-lang:master
from
workingjubilee:more-lazy-methods-take-2
Sep 19, 2024
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
use super::UnsafeCell; | ||
use crate::hint::unreachable_unchecked; | ||
use crate::ops::Deref; | ||
use crate::{fmt, mem}; | ||
|
||
|
@@ -82,7 +83,7 @@ impl<T, F: FnOnce() -> T> LazyCell<T, F> { | |
match this.state.into_inner() { | ||
State::Init(data) => Ok(data), | ||
State::Uninit(f) => Err(f), | ||
State::Poisoned => panic!("LazyCell instance has previously been poisoned"), | ||
State::Poisoned => panic_poisoned(), | ||
} | ||
} | ||
|
||
|
@@ -114,7 +115,72 @@ impl<T, F: FnOnce() -> T> LazyCell<T, F> { | |
State::Init(data) => data, | ||
// SAFETY: The state is uninitialized. | ||
State::Uninit(_) => unsafe { LazyCell::really_init(this) }, | ||
State::Poisoned => panic!("LazyCell has previously been poisoned"), | ||
State::Poisoned => panic_poisoned(), | ||
} | ||
} | ||
|
||
/// Forces the evaluation of this lazy value and returns a mutable reference to | ||
/// the result. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// #![feature(lazy_get)] | ||
/// use std::cell::LazyCell; | ||
/// | ||
/// let mut lazy = LazyCell::new(|| 92); | ||
/// | ||
/// let p = LazyCell::force_mut(&mut lazy); | ||
/// assert_eq!(*p, 92); | ||
/// *p = 44; | ||
/// assert_eq!(*lazy, 44); | ||
/// ``` | ||
#[inline] | ||
#[unstable(feature = "lazy_get", issue = "129333")] | ||
pub fn force_mut(this: &mut LazyCell<T, F>) -> &mut T { | ||
#[cold] | ||
/// # Safety | ||
/// May only be called when the state is `Uninit`. | ||
unsafe fn really_init_mut<T, F: FnOnce() -> T>(state: &mut State<T, F>) -> &mut T { | ||
// INVARIANT: Always valid, but the value may not be dropped. | ||
struct PoisonOnPanic<T, F>(*mut State<T, F>); | ||
impl<T, F> Drop for PoisonOnPanic<T, F> { | ||
#[inline] | ||
fn drop(&mut self) { | ||
// SAFETY: Invariant states it is valid, and we don't drop the old value. | ||
unsafe { | ||
self.0.write(State::Poisoned); | ||
} | ||
} | ||
} | ||
|
||
let State::Uninit(f) = state else { | ||
// `unreachable!()` here won't optimize out because the function is cold. | ||
// SAFETY: Precondition. | ||
unsafe { unreachable_unchecked() }; | ||
}; | ||
// SAFETY: We never drop the state after we read `f`, and we write a valid value back | ||
// in any case, panic or success. `f` can't access the `LazyCell` because it is mutably | ||
// borrowed. | ||
let f = unsafe { core::ptr::read(f) }; | ||
// INVARIANT: Initiated from mutable reference, don't drop because we read it. | ||
let guard = PoisonOnPanic(state); | ||
let data = f(); | ||
// SAFETY: `PoisonOnPanic` invariant, and we don't drop the old value. | ||
unsafe { | ||
core::ptr::write(guard.0, State::Init(data)); | ||
} | ||
core::mem::forget(guard); | ||
let State::Init(data) = state else { unreachable!() }; | ||
data | ||
} | ||
|
||
let state = this.state.get_mut(); | ||
match state { | ||
State::Init(data) => data, | ||
// SAFETY: `state` is `Uninit`. | ||
State::Uninit(_) => unsafe { really_init_mut(state) }, | ||
State::Poisoned => panic_poisoned(), | ||
} | ||
} | ||
|
||
|
@@ -152,13 +218,55 @@ impl<T, F: FnOnce() -> T> LazyCell<T, F> { | |
} | ||
|
||
impl<T, F> LazyCell<T, F> { | ||
/// Returns a reference to the value if initialized, or `None` if not. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// #![feature(lazy_get)] | ||
/// | ||
/// use std::cell::LazyCell; | ||
/// | ||
/// let mut lazy = LazyCell::new(|| 92); | ||
/// | ||
/// assert_eq!(LazyCell::get_mut(&mut lazy), None); | ||
/// let _ = LazyCell::force(&lazy); | ||
/// *LazyCell::get_mut(&mut lazy).unwrap() = 44; | ||
/// assert_eq!(*lazy, 44); | ||
/// ``` | ||
#[inline] | ||
fn get(&self) -> Option<&T> { | ||
#[unstable(feature = "lazy_get", issue = "129333")] | ||
pub fn get_mut(this: &mut LazyCell<T, F>) -> Option<&mut T> { | ||
let state = this.state.get_mut(); | ||
match state { | ||
State::Init(data) => Some(data), | ||
_ => None, | ||
} | ||
} | ||
|
||
/// Returns a mutable reference to the value if initialized, or `None` if not. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. non-mutable reference |
||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// #![feature(lazy_get)] | ||
/// | ||
/// use std::cell::LazyCell; | ||
/// | ||
/// let lazy = LazyCell::new(|| 92); | ||
/// | ||
/// assert_eq!(LazyCell::get(&lazy), None); | ||
/// let _ = LazyCell::force(&lazy); | ||
/// assert_eq!(LazyCell::get(&lazy), Some(&92)); | ||
/// ``` | ||
#[inline] | ||
#[unstable(feature = "lazy_get", issue = "129333")] | ||
pub fn get(this: &LazyCell<T, F>) -> Option<&T> { | ||
// SAFETY: | ||
// This is sound for the same reason as in `force`: once the state is | ||
// initialized, it will not be mutably accessed again, so this reference | ||
// will stay valid for the duration of the borrow to `self`. | ||
let state = unsafe { &*self.state.get() }; | ||
let state = unsafe { &*this.state.get() }; | ||
match state { | ||
State::Init(data) => Some(data), | ||
_ => None, | ||
|
@@ -188,10 +296,16 @@ impl<T: Default> Default for LazyCell<T> { | |
impl<T: fmt::Debug, F> fmt::Debug for LazyCell<T, F> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
let mut d = f.debug_tuple("LazyCell"); | ||
match self.get() { | ||
match LazyCell::get(self) { | ||
Some(data) => d.field(data), | ||
None => d.field(&format_args!("<uninit>")), | ||
}; | ||
d.finish() | ||
} | ||
} | ||
|
||
#[cold] | ||
#[inline(never)] | ||
fn panic_poisoned() -> ! { | ||
panic!("LazyCell instance has previously been poisoned") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
mutable reference