1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
//! 惰性值和静态数据的一次性初始化。
use crate::cell::{Cell, UnsafeCell};
use crate::fmt;
use crate::mem;
use crate::ops::Deref;
/// 一个 cell 只能写入一次。
///
/// 与 `RefCell` 不同,`OnceCell` 仅为其值提供共享的 `&T` 引用。
/// 与 `Cell` 不同,`OnceCell` 不需要复制或替换值即可访问它。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// assert!(cell.get().is_none());
///
/// let value: &String = cell.get_or_init(|| {
/// "Hello, World!".to_string()
/// });
/// assert_eq!(value, "Hello, World!");
/// assert!(cell.get().is_some());
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub struct OnceCell<T> {
// 不变量:最多写入一次。
inner: UnsafeCell<Option<T>>,
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T> Default for OnceCell<T> {
fn default() -> Self {
Self::new()
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.get() {
Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
None => f.write_str("OnceCell(Uninit)"),
}
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: Clone> Clone for OnceCell<T> {
fn clone(&self) -> OnceCell<T> {
let res = OnceCell::new();
if let Some(value) = self.get() {
match res.set(value.clone()) {
Ok(()) => (),
Err(_) => unreachable!(),
}
}
res
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: PartialEq> PartialEq for OnceCell<T> {
fn eq(&self, other: &Self) -> bool {
self.get() == other.get()
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: Eq> Eq for OnceCell<T> {}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T> const From<T> for OnceCell<T> {
fn from(value: T) -> Self {
OnceCell { inner: UnsafeCell::new(Some(value)) }
}
}
impl<T> OnceCell<T> {
/// 创建一个新的空 cell。
#[unstable(feature = "once_cell", issue = "74465")]
#[must_use]
pub const fn new() -> OnceCell<T> {
OnceCell { inner: UnsafeCell::new(None) }
}
/// 获取对底层值的引用。
///
/// 如果 cell 为空,则返回 `None`。
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get(&self) -> Option<&T> {
// SAFETY: 由于 `inner` 的不变性而安全
unsafe { &*self.inner.get() }.as_ref()
}
/// 获取对底层值的可变引用。
///
/// 如果 cell 为空,则返回 `None`。
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_mut(&mut self) -> Option<&mut T> {
self.inner.get_mut().as_mut()
}
/// 将 cell 的内容设置为 `value`。
///
/// # Errors
///
/// 如果 cell 为空,则此方法返回 `Ok(())`; 如果 cell 已满,则返回 `Err(value)`。
///
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// assert!(cell.get().is_none());
///
/// assert_eq!(cell.set(92), Ok(()));
/// assert_eq!(cell.set(62), Err(62));
///
/// assert!(cell.get().is_some());
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn set(&self, value: T) -> Result<(), T> {
// SAFETY: 很安全,因为我们不能有重叠的可变借用
let slot = unsafe { &*self.inner.get() };
if slot.is_some() {
return Err(value);
}
// SAFETY: 这是我们设置插槽的唯一地方,由于 reentrancy/concurrency 不可能发生竞争,并且我们检查了插槽当前是否为 `None`,因此此写入维护了 `inner` 的不变性。
//
//
//
let slot = unsafe { &mut *self.inner.get() };
*slot = Some(value);
Ok(())
}
/// 获取 cell 的内容,如果 cell 为空,则使用 `f` 对其进行初始化。
///
/// # Panics
///
/// 如果 `f` panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
///
///
/// 重新从 `f` 初始化 cell 是错误的。这样做会导致 panic。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// let value = cell.get_or_init(|| 92);
/// assert_eq!(value, &92);
/// let value = cell.get_or_init(|| unreachable!());
/// assert_eq!(value, &92);
/// ```
///
///
#[unstable(feature = "once_cell", issue = "74465")]
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
match self.get_or_try_init(|| Ok::<T, !>(f())) {
Ok(val) => val,
}
}
/// 获取 cell 的内容,如果 cell 为空,则使用 `f` 对其进行初始化。
/// 如果 cell 为空并且 `f` 失败,则返回错误。
///
/// # Panics
///
/// 如果 `f` panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
///
///
/// 重新从 `f` 初始化 cell 是错误的。这样做会导致 panic。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
/// assert!(cell.get().is_none());
/// let value = cell.get_or_try_init(|| -> 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>
where
F: FnOnce() -> Result<T, E>,
{
if let Some(val) = self.get() {
return Ok(val);
}
/// 避免将初始化闭包内联到获取已初始化值的公共路径中
///
#[cold]
fn outlined_call<F, T, E>(f: F) -> Result<T, E>
where
F: FnOnce() -> Result<T, E>,
{
f()
}
let val = outlined_call(f)?;
// 请注意,某些形式的可重入初始化可能会导致 UB (请参见 `reentrant_init` 测试)。
// 我相信,仅删除此 `assert`,同时保留 `set/get` 听起来是不错的选择,但对于 panic 似乎更好,而不是默默地使用旧值。
//
//
assert!(self.set(val).is_ok(), "reentrant init");
Ok(self.get().unwrap())
}
/// 消费 cell,返回包装后的值。
///
/// 如果 cell 为空,则返回 `None`。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let cell: OnceCell<String> = OnceCell::new();
/// assert_eq!(cell.into_inner(), None);
///
/// let cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.into_inner(), Some("hello".to_string()));
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn into_inner(self) -> Option<T> {
// 因为 `into_inner` 按值取 `self`,所以编译器将静态验证它当前是否未被借用。
// 因此,移动 `Option<T>` 是安全的。
self.inner.into_inner()
}
/// 从 `OnceCell` 中取出值,将其移回未初始化状态。
///
/// 无效,如果尚未初始化 `OnceCell`,则返回 `None`。
///
/// 通过要求可变引用来保证安全。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::OnceCell;
///
/// let mut cell: OnceCell<String> = OnceCell::new();
/// assert_eq!(cell.take(), None);
///
/// let mut cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.take(), Some("hello".to_string()));
/// assert_eq!(cell.get(), None);
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn take(&mut self) -> Option<T> {
mem::take(self).into_inner()
}
}
/// 在首次访问时初始化的值。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::Lazy;
///
/// let lazy: Lazy<i32> = Lazy::new(|| {
/// println!("initializing");
/// 92
/// });
/// println!("ready");
/// println!("{}", *lazy);
/// println!("{}", *lazy);
///
/// // Prints:
/// // 准备初始化
/////
/// // 92
/// // 92
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub struct Lazy<T, F = fn() -> T> {
cell: OnceCell<T>,
init: Cell<Option<F>>,
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: fmt::Debug, F> fmt::Debug for Lazy<T, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
}
}
impl<T, F> Lazy<T, F> {
/// 使用给定的初始化函数创建一个新的惰性值。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// # fn main() {
/// use std::lazy::Lazy;
///
/// let hello = "Hello, World!".to_string();
///
/// let lazy = Lazy::new(|| hello.to_uppercase());
///
/// assert_eq!(&*lazy, "HELLO, WORLD!");
/// # }
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub const fn new(init: F) -> Lazy<T, F> {
Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
}
}
impl<T, F: FnOnce() -> T> Lazy<T, F> {
/// 强制对此延迟值求值,并向结果返回引用。
///
///
/// 这等效于 `Deref` impl,但是是显式的。
///
/// # Examples
///
/// ```
/// #![feature(once_cell)]
///
/// use std::lazy::Lazy;
///
/// let lazy = Lazy::new(|| 92);
///
/// assert_eq!(Lazy::force(&lazy), &92);
/// assert_eq!(&*lazy, &92);
/// ```
#[unstable(feature = "once_cell", issue = "74465")]
pub fn force(this: &Lazy<T, F>) -> &T {
this.cell.get_or_init(|| match this.init.take() {
Some(f) => f(),
None => panic!("`Lazy` instance has previously been poisoned"),
})
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
type Target = T;
fn deref(&self) -> &T {
Lazy::force(self)
}
}
#[unstable(feature = "once_cell", issue = "74465")]
impl<T: Default> Default for Lazy<T> {
/// 使用 `Default` 作为初始化函数创建一个新的惰性值。
fn default() -> Lazy<T> {
Lazy::new(T::default)
}
}