2 releases (1 stable)
1.0.0 | Mar 13, 2024 |
---|---|
0.2.2 | Jul 9, 2020 |
#448 in Memory management
170 downloads per month
Used in 2 crates
(via kontroli)
9KB
98 lines
lazy-st
This crate provides single-threaded lazy evaluation for Rust.
It is an adaptation of the lazy crate,
removing support for multi-threaded operation,
adding support for no_std
environments, and
making it compatible with newer Rust versions.
To share lazy values between threads, please consider using the lazy-mt crate.
Example
fn expensive() -> i32 {
println!("I am only evaluated once!"); 7
}
fn main() {
let a = lazy!(expensive());
// Thunks are just smart pointers!
assert_eq!(*a, 7); // "I am only evaluated once!" is printed here
let b = [*a, *a]; // Nothing is printed.
assert_eq!(b, [7, 7]);
}
lib.rs
:
Single-threaded lazy evaluation.
Lazy evaluation allows you to define computations whose evaluation is deferred to when they are actually needed. This can be also achieved with closures; however, in case of lazy evaluation, the output of computations is calculated only once and stored in a cache.
Lazy evaluation is useful if you have an expensive computation of which you might need the result more than once during runtime, but you do not know in advance whether you will need it at all.
Let us consider an example, where we first use a closure to defer evaluation:
fn expensive() -> i32 {
println!("I am expensive to evaluate!"); 7
}
fn main() {
let a = || expensive(); // Nothing is printed.
assert_eq!(a(), 7); // "I am expensive to evaluate!" is printed here
let b = [a(), a()]; // "I am expensive to evaluate!" is printed twice
assert_eq!(b, [7, 7]);
}
Contrast this with using lazy evaluation:
fn expensive() -> i32 {
println!("I am expensive to evaluate!"); 7
}
fn main() {
let a = lazy!(expensive()); // Nothing is printed.
// Thunks are just smart pointers!
assert_eq!(*a, 7); // "I am expensive to evaluate!" is printed here
let b = [*a, *a]; // Nothing is printed.
assert_eq!(b, [7, 7]);
}
Lazy values from this crate cannot be shared between threads.
If you need this, please consider using the lazy-mt
crate.