Skip to content

Update once_cell 'get_or_init' to 'get_or_init_with' #107184

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2282,7 +2282,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}

fn dominators(&self) -> &Dominators<BasicBlock> {
self.dominators.get_or_init(|| self.body.basic_blocks.dominators())
self.dominators.get_or_init_with(|| self.body.basic_blocks.dominators())
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D

// FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context.
fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
*debug_context(cx).recursion_marker_type.get_or_init(move || {
*debug_context(cx).recursion_marker_type.get_or_init_with(move || {
unsafe {
// The choice of type here is pretty arbitrary -
// anything reading the debuginfo for a recursive
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2318,7 +2318,7 @@ fn add_native_libs_from_crate(
cmd.link_whole_staticlib(
name,
verbatim,
&search_paths.get_or_init(|| archive_search_paths(sess)),
&search_paths.get_or_init_with(|| archive_search_paths(sess)),
);
} else {
cmd.link_staticlib(name, verbatim)
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -693,12 +693,12 @@ pub fn create_global_ctxt<'tcx>(
callback(sess, &mut local_providers, &mut extern_providers);
}

let queries = queries.get_or_init(|| {
let queries = queries.get_or_init_with(|| {
TcxQueries::new(local_providers, extern_providers, query_result_on_disk_cache)
});

sess.time("setup_global_ctxt", || {
gcx_cell.get_or_init(move || {
gcx_cell.get_or_init_with(move || {
TyCtxt::create_global_ctxt(
sess,
lint_store,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ pub fn get_codegen_backend(
) -> Box<dyn CodegenBackend> {
static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();

let load = LOAD.get_or_init(|| {
let load = LOAD.get_or_init_with(|| {
let default_codegen_backend = option_env!("CFG_DEFAULT_CODEGEN_BACKEND").unwrap_or("llvm");

match backend_name.unwrap_or(default_codegen_backend) {
Expand All @@ -264,7 +264,7 @@ pub fn rustc_path<'a>() -> Option<&'a Path> {

const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");

RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_deref()
RUSTC_PATH.get_or_init_with(|| get_rustc_path_inner(BIN_PATH)).as_deref()
}

fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1297,7 +1297,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
// Slow path: We need to find out the new `DefIndex` of the provided
// `DefPathHash`, if its still exists. This requires decoding every `DefPathHash`
// stored in this crate.
let map = self.cdata.expn_hash_map.get_or_init(|| {
let map = self.cdata.expn_hash_map.get_or_init_with(|| {
let end_id = self.root.expn_hashes.size() as u32;
let mut map =
UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_middle/src/mir/basic_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl<'tcx> BasicBlocks<'tcx> {
/// Returns true if control-flow graph contains a cycle reachable from the `START_BLOCK`.
#[inline]
pub fn is_cfg_cyclic(&self) -> bool {
*self.cache.is_cyclic.get_or_init(|| graph::is_cyclic(self))
*self.cache.is_cyclic.get_or_init_with(|| graph::is_cyclic(self))
}

pub fn dominators(&self) -> Dominators<BasicBlock> {
Expand All @@ -48,7 +48,7 @@ impl<'tcx> BasicBlocks<'tcx> {
/// Returns predecessors for each basic block.
#[inline]
pub fn predecessors(&self) -> &Predecessors {
self.cache.predecessors.get_or_init(|| {
self.cache.predecessors.get_or_init_with(|| {
let mut preds = IndexVec::from_elem(SmallVec::new(), &self.basic_blocks);
for (bb, data) in self.basic_blocks.iter_enumerated() {
if let Some(term) = &data.terminator {
Expand All @@ -64,7 +64,7 @@ impl<'tcx> BasicBlocks<'tcx> {
/// Returns basic blocks in a postorder.
#[inline]
pub fn postorder(&self) -> &[BasicBlock] {
self.cache.postorder.get_or_init(|| {
self.cache.postorder.get_or_init_with(|| {
Postorder::new(&self.basic_blocks, START_BLOCK).map(|(bb, _)| bb).collect()
})
}
Expand All @@ -73,7 +73,7 @@ impl<'tcx> BasicBlocks<'tcx> {
/// values that lead to a `target` block from a `switch` block.
#[inline]
pub fn switch_sources(&self) -> &SwitchSources {
self.cache.switch_sources.get_or_init(|| {
self.cache.switch_sources.get_or_init_with(|| {
let mut switch_sources: SwitchSources = FxHashMap::default();
for (bb, data) in self.basic_blocks.iter_enumerated() {
if let Some(Terminator {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_dataflow/src/framework/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ where
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: OnceLock<regex::Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new($re).unwrap())
RE.get_or_init_with(|| Regex::new($re).unwrap())
}};
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/coverage/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ const RUSTC_COVERAGE_DEBUG_OPTIONS: &str = "RUSTC_COVERAGE_DEBUG_OPTIONS";
pub(super) fn debug_options<'a>() -> &'a DebugOptions {
static DEBUG_OPTIONS: OnceLock<DebugOptions> = OnceLock::new();

&DEBUG_OPTIONS.get_or_init(DebugOptions::from_env)
&DEBUG_OPTIONS.get_or_init_with(DebugOptions::from_env)
}

/// Parses and maintains coverage-specific debug options captured from the environment variable
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/cell/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl<T, F: FnOnce() -> T> LazyCell<T, F> {
#[inline]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn force(this: &LazyCell<T, F>) -> &T {
this.cell.get_or_init(|| match this.init.take() {
this.cell.get_or_init_with(|| match this.init.take() {
Some(f) => f(),
None => panic!("`Lazy` instance has previously been poisoned"),
})
Expand Down
16 changes: 8 additions & 8 deletions library/core/src/cell/once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::mem;
/// let cell = OnceCell::new();
/// assert!(cell.get().is_none());
///
/// let value: &String = cell.get_or_init(|| {
/// let value: &String = cell.get_or_init_with(|| {
/// "Hello, World!".to_string()
/// });
/// assert_eq!(value, "Hello, World!");
Expand Down Expand Up @@ -122,18 +122,18 @@ impl<T> OnceCell<T> {
/// use std::cell::OnceCell;
///
/// let cell = OnceCell::new();
/// let value = cell.get_or_init(|| 92);
/// let value = cell.get_or_init_with(|| 92);
/// assert_eq!(value, &92);
/// let value = cell.get_or_init(|| unreachable!());
/// let value = cell.get_or_init_with(|| unreachable!());
/// assert_eq!(value, &92);
/// ```
#[inline]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
pub fn get_or_init_with<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
match self.get_or_try_init(|| Ok::<T, !>(f())) {
match self.get_or_try_init_with(|| Ok::<T, !>(f())) {
Ok(val) => val,
}
}
Expand All @@ -158,16 +158,16 @@ impl<T> OnceCell<T> {
/// use std::cell::OnceCell;
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
/// assert_eq!(cell.get_or_try_init_with(|| Err(())), Err(()));
/// assert!(cell.get().is_none());
/// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
/// let value = cell.get_or_try_init_with(|| -> Result<i32, ()> {
/// Ok(92)
/// });
/// assert_eq!(value, Ok(&92));
/// assert_eq!(cell.get(), Some(&92))
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
pub fn get_or_try_init_with<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
Expand Down
10 changes: 5 additions & 5 deletions library/core/tests/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use core::{
fn once_cell() {
let c = OnceCell::new();
assert!(c.get().is_none());
c.get_or_init(|| 92);
c.get_or_init_with(|| 92);
assert_eq!(c.get(), Some(&92));

c.get_or_init(|| panic!("Kabom!"));
c.get_or_init_with(|| panic!("Kabom!"));
assert_eq!(c.get(), Some(&92));
}

Expand All @@ -34,7 +34,7 @@ fn once_cell_drop() {
}

let x = OnceCell::new();
x.get_or_init(|| Dropper);
x.get_or_init_with(|| Dropper);
assert_eq!(DROP_CNT.load(SeqCst), 0);
drop(x);
assert_eq!(DROP_CNT.load(SeqCst), 1);
Expand Down Expand Up @@ -126,8 +126,8 @@ fn aliasing_in_get() {
fn reentrant_init() {
let x: OnceCell<Box<i32>> = OnceCell::new();
let dangling_ref: Cell<Option<&i32>> = Cell::new(None);
x.get_or_init(|| {
let r = x.get_or_init(|| Box::new(92));
x.get_or_init_with(|| {
let r = x.get_or_init_with(|| Box::new(92));
dangling_ref.set(Some(r));
Box::new(62)
});
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ pub struct StdinLock<'a> {
pub fn stdin() -> Stdin {
static INSTANCE: OnceLock<Mutex<BufReader<StdinRaw>>> = OnceLock::new();
Stdin {
inner: INSTANCE.get_or_init(|| {
inner: INSTANCE.get_or_init_with(|| {
Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
}),
}
Expand Down Expand Up @@ -614,7 +614,7 @@ static STDOUT: OnceLock<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> = OnceLo
pub fn stdout() -> Stdout {
Stdout {
inner: STDOUT
.get_or_init(|| ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw())))),
.get_or_init_with(|| ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw())))),
}
}

Expand All @@ -623,7 +623,7 @@ pub fn stdout() -> Stdout {
// buffering capacity.
pub fn cleanup() {
let mut initialized = false;
let stdout = STDOUT.get_or_init(|| {
let stdout = STDOUT.get_or_init_with(|| {
initialized = true;
ReentrantMutex::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw())))
});
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sync/lazy_lock/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ fn static_sync_lazy() {
fn static_sync_lazy_via_fn() {
fn xs() -> &'static Vec<i32> {
static XS: OnceLock<Vec<i32>> = OnceLock::new();
XS.get_or_init(|| {
XS.get_or_init_with(|| {
let mut xs = Vec::new();
xs.push(1);
xs.push(2);
Expand Down
20 changes: 10 additions & 10 deletions library/std/src/sync/once_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::sync::Once;
/// assert!(CELL.get().is_none());
///
/// std::thread::spawn(|| {
/// let value: &String = CELL.get_or_init(|| {
/// let value: &String = CELL.get_or_init_with(|| {
/// "Hello, World!".to_string()
/// });
/// assert_eq!(value, "Hello, World!");
Expand Down Expand Up @@ -132,7 +132,7 @@ impl<T> OnceLock<T> {
#[unstable(feature = "once_cell", issue = "74465")]
pub fn set(&self, value: T) -> Result<(), T> {
let mut value = Some(value);
self.get_or_init(|| value.take().unwrap());
self.get_or_init_with(|| value.take().unwrap());
match value {
None => Ok(()),
Some(value) => Err(value),
Expand All @@ -142,7 +142,7 @@ impl<T> OnceLock<T> {
/// Gets the contents of the cell, initializing it with `f` if the cell
/// was empty.
///
/// Many threads may call `get_or_init` concurrently with different
/// Many threads may call `get_or_init_with` concurrently with different
/// initializing functions, but it is guaranteed that only one function
/// will be executed.
///
Expand All @@ -163,18 +163,18 @@ impl<T> OnceLock<T> {
/// use std::sync::OnceLock;
///
/// let cell = OnceLock::new();
/// let value = cell.get_or_init(|| 92);
/// let value = cell.get_or_init_with(|| 92);
/// assert_eq!(value, &92);
/// let value = cell.get_or_init(|| unreachable!());
/// let value = cell.get_or_init_with(|| unreachable!());
/// assert_eq!(value, &92);
/// ```
#[inline]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
pub fn get_or_init_with<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
match self.get_or_try_init(|| Ok::<T, !>(f())) {
match self.get_or_try_init_with(|| Ok::<T, !>(f())) {
Ok(val) => val,
}
}
Expand All @@ -200,17 +200,17 @@ impl<T> OnceLock<T> {
/// use std::sync::OnceLock;
///
/// let cell = OnceLock::new();
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
/// assert_eq!(cell.get_or_try_init_with(|| Err(())), Err(()));
/// assert!(cell.get().is_none());
/// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
/// let value = cell.get_or_try_init_with(|| -> Result<i32, ()> {
/// Ok(92)
/// });
/// assert_eq!(value, Ok(&92));
/// assert_eq!(cell.get(), Some(&92))
/// ```
#[inline]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
pub fn get_or_try_init_with<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
Expand Down
19 changes: 11 additions & 8 deletions library/std/src/sync/once_lock/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ fn sync_once_cell() {
assert!(ONCE_CELL.get().is_none());

spawn_and_wait(|| {
ONCE_CELL.get_or_init(|| 92);
ONCE_CELL.get_or_init_with(|| 92);
assert_eq!(ONCE_CELL.get(), Some(&92));
});

ONCE_CELL.get_or_init(|| panic!("Kabom!"));
ONCE_CELL.get_or_init_with(|| panic!("Kabom!"));
assert_eq!(ONCE_CELL.get(), Some(&92));
}

Expand Down Expand Up @@ -59,7 +59,7 @@ fn sync_once_cell_drop() {

let x = OnceLock::new();
spawn_and_wait(move || {
x.get_or_init(|| Dropper);
x.get_or_init_with(|| Dropper);
assert_eq!(DROP_CNT.load(SeqCst), 0);
drop(x);
});
Expand All @@ -85,18 +85,21 @@ fn clone() {
}

#[test]
fn get_or_try_init() {
fn get_or_try_init_with() {
let cell: OnceLock<String> = OnceLock::new();
assert!(cell.get().is_none());

let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() }));
let res = panic::catch_unwind(|| cell.get_or_try_init_with(|| -> Result<_, ()> { panic!() }));
assert!(res.is_err());
assert!(!cell.is_initialized());
assert!(cell.get().is_none());

assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
assert_eq!(cell.get_or_try_init_with(|| Err(())), Err(()));

assert_eq!(cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())), Ok(&"hello".to_string()));
assert_eq!(
cell.get_or_try_init_with(|| Ok::<_, ()>("hello".to_string())),
Ok(&"hello".to_string())
);
assert_eq!(cell.get(), Some(&"hello".to_string()));
}

Expand Down Expand Up @@ -140,7 +143,7 @@ fn eval_once_macro() {
fn init() -> $ty {
$($body)*
}
ONCE_CELL.get_or_init(init)
ONCE_CELL.get_or_init_with(init)
}};
}

Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/itron/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Mutex {

/// Get the inner mutex's ID, which is lazily created.
fn raw(&self) -> abi::ID {
match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) {
match self.mtx.get_or_try_init_with(|| new_mtx().map(|id| (id, ()))) {
Ok((id, ())) => id,
Err(e) => fail(e, &"acre_mtx"),
}
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/itron/spin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl<T> SpinIdOnceCell<T> {
/// Warning: `f` must not perform a blocking operation, which
/// includes panicking.
#[inline]
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<(abi::ID, &T), E>
pub fn get_or_try_init_with<F, E>(&self, f: F) -> Result<(abi::ID, &T), E>
where
F: FnOnce() -> Result<(abi::ID, T), E>,
{
Expand Down
Loading