Skip to content

Commit 9d49a8f

Browse files
committed
Replace Option<T> with MaybeUninit<T>
This avoids unneeded tag in `Option` and addresses FIXME comment.
1 parent 7324c83 commit 9d49a8f

File tree

1 file changed

+6
-19
lines changed

1 file changed

+6
-19
lines changed

src/inline_lazy.rs

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,43 +9,30 @@ extern crate core;
99
extern crate std;
1010

1111
use self::std::cell::Cell;
12-
use self::std::hint::unreachable_unchecked;
12+
use self::std::mem::MaybeUninit;
1313
use self::std::prelude::v1::*;
1414
use self::std::sync::Once;
1515
#[allow(deprecated)]
1616
pub use self::std::sync::ONCE_INIT;
1717

18-
// FIXME: Replace Option<T> with MaybeUninit<T> (stable since 1.36.0)
19-
pub struct Lazy<T: Sync>(Cell<Option<T>>, Once);
18+
pub struct Lazy<T: Sync>(Cell<MaybeUninit<T>>, Once);
2019

2120
impl<T: Sync> Lazy<T> {
2221
#[allow(deprecated)]
23-
pub const INIT: Self = Lazy(Cell::new(None), ONCE_INIT);
22+
pub const INIT: Self = Lazy(Cell::new(MaybeUninit::uninit()), ONCE_INIT);
2423

2524
#[inline(always)]
2625
pub fn get<F>(&'static self, f: F) -> &T
2726
where
2827
F: FnOnce() -> T,
2928
{
3029
self.1.call_once(|| {
31-
self.0.set(Some(f()));
30+
self.0.set(MaybeUninit::new(f()));
3231
});
3332

34-
// `self.0` is guaranteed to be `Some` by this point
33+
// `self.0` is guaranteed to be initialized by this point
3534
// The `Once` will catch and propagate panics
36-
unsafe {
37-
match *self.0.as_ptr() {
38-
Some(ref x) => x,
39-
None => {
40-
debug_assert!(
41-
false,
42-
"attempted to dereference an uninitialized lazy static. This is a bug"
43-
);
44-
45-
unreachable_unchecked()
46-
}
47-
}
48-
}
35+
unsafe { &*(*self.0.as_ptr()).as_ptr() }
4936
}
5037
}
5138

0 commit comments

Comments
 (0)