lazy_rc/lib.rs
1/*
2 * lazy_rc - Rc<T> and Arc<T> with *lazy* initialization
3 * This is free and unencumbered software released into the public domain.
4 */
5
6//! **lazy_rc** provides implementations of [`Rc<T>`](std::rc::Rc) and
7//! [`Arc<T>`](std::sync::Arc) with ***lazy*** initialization.
8//!
9//! In other words, the "inner" value of an [**`LazyRc<T>`**](LazyRc) or
10//! [**`LazyArc<T>`**](LazyArc) instance is created when it is accessed for the
11//! *first* time, using the supplied initialization function. Initialization
12//! may fail, in which case the error is passed through.
13//!
14//! # Thread Safety
15//!
16//! `LazyRc<T>` is *single-threaded*, because so is `Rc<T>`. Therefore, an
17//! `LazyRc<T>` instance can **not** be shared by multiple threads, and you can
18//! **not** use `LazyRc<T>` for **`static`** variables. However, it ***can***
19//! be used for [`thread_local!`](std::thread_local) variables.
20//!
21//! `LazyArc<T>` is *thread-safe*, because so is `Arc<T>`. Therefore, an
22//! `LazyArc<T>` instance can be shared by multiple threads, and you can even
23//! use `LazyArc<T>` for *global* **`static`** variables.
24//!
25//! # Const Warning
26//!
27//! Do **not** use `LazyRc<T>` or `LazyArc<T>` as a **`const`** value! That is
28//! because, in Rust, **`const`** values are "inlined", effectively creating a
29//! *new* instance at every place where the **`const`** value is used. This
30//! obviously breaks "lazy" initialization 😨
31//!
32//! # Example
33//!
34//! ```
35//! use lazy_rc::{LazyRc, LazyArc};
36//!
37//! static GLOBAL_INSTANCE: LazyArc<MyStruct> = LazyArc::empty();
38//!
39//! thread_local! {
40//! static THREAD_INSTANCE: LazyRc<MyStruct> = LazyRc::empty();
41//! }
42//!
43//! struct MyStruct {
44//! /* ... */
45//! }
46//!
47//! impl MyStruct {
48//! fn new() -> Result<Self> {
49//! /* ... */
50//! }
51//!
52//! /// Returns a thread-local instance that will be created on first access.
53//! /// If the initialization function fails, then an Error will be returned.
54//! pub fn instance() -> Result<Rc<Self>> {
55//! THREAD_INSTANCE.with(|lazy| lazy.or_try_init_with(Self::new))
56//! }
57//! }
58//! ```
59
60mod lazy_arc;
61mod lazy_rc;
62
63pub(crate) mod utils;
64
65pub use lazy_arc::LazyArc;
66pub use lazy_rc::LazyRc;
67pub use utils::InitError;