Skip to content
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

Rename OnceCell methods to be more consistent with std conventions #78943

Closed
wants to merge 2 commits 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_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,7 @@ pub fn create_global_ctxt<'tcx>(
}

let gcx = sess.time("setup_global_ctxt", || {
global_ctxt.get_or_init(|| {
global_ctxt.get_or_insert_with(|| {
TyCtxt::create_global_ctxt(
sess,
lint_store,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,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_ref().map(|v| &**v)
RUSTC_PATH.get_or_insert_with(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
}

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 @@ -1713,7 +1713,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
}
};

self.cdata.source_map_import_info.get_or_init(|| {
self.cdata.source_map_import_info.get_or_insert_with(|| {
let external_source_map = self.root.source_map.decode(self);

external_source_map
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/predecessors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl PredecessorCache {
&self,
basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
) -> &Predecessors {
self.cache.get_or_init(|| {
self.cache.get_or_insert_with(|| {
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
for (bb, data) in basic_blocks.iter_enumerated() {
if let Some(term) = &data.terminator {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/query/on_disk_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ impl<'sess> OnDiskCache<'sess> {
T: Decodable<CacheDecoder<'a, 'tcx>>,
{
let cnum_map =
self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
self.cnum_map.get_or_insert_with(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));

let mut decoder = CacheDecoder {
tcx,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir/src/dataflow/framework/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ where
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: SyncOnceCell<regex::Regex> = SyncOnceCell::new();
RE.get_or_init(|| Regex::new($re).unwrap())
RE.get_or_insert_with(|| Regex::new($re).unwrap())
}};
}

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

&DEBUG_OPTIONS.get_or_init(|| DebugOptions::from_env())
&DEBUG_OPTIONS.get_or_insert_with(|| DebugOptions::from_env())
}

/// Parses and maintains coverage-specific debug options captured from the environment variable
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_build/src/thir/pattern/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
}

fn head_ctor<'a>(&'a self, cx: &MatchCheckCtxt<'p, 'tcx>) -> &'a Constructor<'tcx> {
self.head_ctor.get_or_init(|| pat_constructor(cx, self.head()))
self.head_ctor.get_or_insert_with(|| pat_constructor(cx, self.head()))
}

fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
Expand Down
38 changes: 29 additions & 9 deletions library/core/src/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::ops::Deref;
/// let cell = OnceCell::new();
/// assert!(cell.get().is_none());
///
/// let value: &String = cell.get_or_init(|| {
/// let value: &String = cell.get_or_insert_with(|| {
/// "Hello, World!".to_string()
/// });
/// assert_eq!(value, "Hello, World!");
Expand Down Expand Up @@ -163,21 +163,31 @@ impl<T> OnceCell<T> {
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// let value = cell.get_or_init(|| 92);
/// let value = cell.get_or_insert_with(|| 92);
/// assert_eq!(value, &92);
/// let value = cell.get_or_init(|| unreachable!());
/// let value = cell.get_or_insert_with(|| unreachable!());
/// assert_eq!(value, &92);
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
pub fn get_or_insert_with<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
match self.get_or_try_init(|| Ok::<T, !>(f())) {
match self.try_get_or_insert_with(|| Ok::<T, !>(f())) {
Ok(val) => val,
}
}

/// Deprecated, use `get_or_insert_with` instead.
#[rustc_deprecated = "use get_or_insert_with instead"]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
self.get_or_insert_with(f)
}

/// Gets the contents of the cell, initializing it with `f` if
/// the cell was empty. If the cell was empty and `f` failed, an
/// error is returned.
Expand All @@ -198,16 +208,16 @@ impl<T> OnceCell<T> {
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
/// assert_eq!(cell.try_get_or_insert_with(|| Err(())), Err(()));
/// assert!(cell.get().is_none());
/// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
/// let value = cell.try_get_or_insert_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 try_get_or_insert_with<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
Expand All @@ -223,6 +233,16 @@ impl<T> OnceCell<T> {
Ok(self.get().unwrap())
}

/// Deprecated, use `try_get_or_insert_with` instead.
#[rustc_deprecated = "use try_get_or_insert_with instead"]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
self.try_get_or_insert_with(f)
}

/// Consumes the cell, returning the wrapped value.
///
/// Returns `None` if the cell was empty.
Expand Down Expand Up @@ -355,7 +375,7 @@ impl<T, F: FnOnce() -> T> Lazy<T, F> {
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn force(this: &Lazy<T, F>) -> &T {
this.cell.get_or_init(|| match this.init.take() {
this.cell.get_or_insert_with(|| match this.init.take() {
Some(f) => f(),
None => panic!("`Lazy` instance has previously been poisoned"),
})
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 @@ -8,10 +8,10 @@ use core::{
fn once_cell() {
let c = OnceCell::new();
assert!(c.get().is_none());
c.get_or_init(|| 92);
c.get_or_insert_with(|| 92);
assert_eq!(c.get(), Some(&92));

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

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

let x = OnceCell::new();
x.get_or_init(|| Dropper);
x.get_or_insert_with(|| Dropper);
assert_eq!(DROP_CNT.load(SeqCst), 0);
drop(x);
assert_eq!(DROP_CNT.load(SeqCst), 1);
Expand Down Expand Up @@ -115,8 +115,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_insert_with(|| {
let r = x.get_or_insert_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 @@ -310,7 +310,7 @@ pub struct StdinLock<'a> {
pub fn stdin() -> Stdin {
static INSTANCE: SyncOnceCell<Mutex<BufReader<StdinRaw>>> = SyncOnceCell::new();
Stdin {
inner: INSTANCE.get_or_init(|| {
inner: INSTANCE.get_or_insert_with(|| {
Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
}),
}
Expand Down Expand Up @@ -549,7 +549,7 @@ pub fn stdout() -> Stdout {
static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> =
SyncOnceCell::new();
Stdout {
inner: INSTANCE.get_or_init(|| unsafe {
inner: INSTANCE.get_or_insert_with(|| unsafe {
let _ = sys_common::at_exit(|| {
if let Some(instance) = INSTANCE.get() {
// Flush the data and disable buffering during shutdown
Expand Down Expand Up @@ -764,7 +764,7 @@ pub fn stderr() -> Stderr {
static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<StderrRaw>>> = SyncOnceCell::new();

Stderr {
inner: INSTANCE.get_or_init(|| unsafe {
inner: INSTANCE.get_or_insert_with(|| unsafe {
let r = ReentrantMutex::new(RefCell::new(stderr_raw()));
r.init();
r
Expand Down
42 changes: 31 additions & 11 deletions library/std/src/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub use core::lazy::*;
/// assert!(CELL.get().is_none());
///
/// std::thread::spawn(|| {
/// let value: &String = CELL.get_or_init(|| {
/// let value: &String = CELL.get_or_insert_with(|| {
/// "Hello, World!".to_string()
/// });
/// assert_eq!(value, "Hello, World!");
Expand Down Expand Up @@ -201,7 +201,7 @@ impl<T> SyncOnceCell<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_insert_with(|| value.take().unwrap());
match value {
None => Ok(()),
Some(value) => Err(value),
Expand All @@ -211,7 +211,7 @@ impl<T> SyncOnceCell<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_insert_with` concurrently with different
/// initializing functions, but it is guaranteed that only one function
/// will be executed.
///
Expand All @@ -232,21 +232,31 @@ impl<T> SyncOnceCell<T> {
/// use std::lazy::SyncOnceCell;
///
/// let cell = SyncOnceCell::new();
/// let value = cell.get_or_init(|| 92);
/// let value = cell.get_or_insert_with(|| 92);
/// assert_eq!(value, &92);
/// let value = cell.get_or_init(|| unreachable!());
/// let value = cell.get_or_insert_with(|| unreachable!());
/// assert_eq!(value, &92);
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
pub fn get_or_insert_with<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
match self.get_or_try_init(|| Ok::<T, !>(f())) {
match self.try_get_or_insert_with(|| Ok::<T, !>(f())) {
Ok(val) => val,
}
}

/// Deprecated, use `get_or_insert_with` instead.
#[rustc_deprecated = "use get_or_insert_with instead"]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
self.get_or_insert_with(f)
}

/// Gets the contents of the cell, initializing it with `f` if
/// the cell was empty. If the cell was empty and `f` failed, an
/// error is returned.
Expand All @@ -268,16 +278,16 @@ impl<T> SyncOnceCell<T> {
/// use std::lazy::SyncOnceCell;
///
/// let cell = SyncOnceCell::new();
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
/// assert_eq!(cell.try_get_or_insert_with(|| Err(())), Err(()));
/// assert!(cell.get().is_none());
/// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
/// let value = cell.try_get_or_insert_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 try_get_or_insert_with<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
Expand All @@ -297,6 +307,16 @@ impl<T> SyncOnceCell<T> {
Ok(unsafe { self.get_unchecked() })
}

/// Deprecated, use `try_get_or_insert_with` instead.
#[rustc_deprecated = "use try_get_or_insert_with instead"]
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
self.try_get_or_insert_with(f)
}

/// Consumes the `SyncOnceCell`, returning the wrapped value. Returns
/// `None` if the cell was empty.
///
Expand Down Expand Up @@ -499,7 +519,7 @@ impl<T, F: FnOnce() -> T> SyncLazy<T, F> {
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn force(this: &SyncLazy<T, F>) -> &T {
this.cell.get_or_init(|| match this.init.take() {
this.cell.get_or_insert_with(|| match this.init.take() {
Some(f) => f(),
None => panic!("Lazy instance has previously been poisoned"),
})
Expand Down
21 changes: 12 additions & 9 deletions library/std/src/lazy/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ fn sync_once_cell() {
assert!(ONCE_CELL.get().is_none());

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

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

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

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

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

let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() }));
let res = panic::catch_unwind(|| cell.try_get_or_insert_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.try_get_or_insert_with(|| Err(())), Err(()));

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

Expand Down Expand Up @@ -224,7 +227,7 @@ fn static_sync_lazy() {
fn static_sync_lazy_via_fn() {
fn xs() -> &'static Vec<i32> {
static XS: SyncOnceCell<Vec<i32>> = SyncOnceCell::new();
XS.get_or_init(|| {
XS.get_or_insert_with(|| {
let mut xs = Vec::new();
xs.push(1);
xs.push(2);
Expand Down Expand Up @@ -261,7 +264,7 @@ fn eval_once_macro() {
fn init() -> $ty {
$($body)*
}
ONCE_CELL.get_or_init(init)
ONCE_CELL.get_or_insert_with(init)
}};
}

Expand Down
Loading