2 releases (1 stable)

1.0.0 Mar 13, 2024
0.2.2 Jul 9, 2020

#385 in Memory management

Download history 18/week @ 2024-07-20 64/week @ 2024-07-27 76/week @ 2024-08-03 21/week @ 2024-08-10 14/week @ 2024-08-17 30/week @ 2024-08-24 17/week @ 2024-08-31 10/week @ 2024-09-07 5/week @ 2024-09-14 49/week @ 2024-09-21 32/week @ 2024-09-28 50/week @ 2024-10-05 31/week @ 2024-10-12 18/week @ 2024-10-19 32/week @ 2024-10-26 32/week @ 2024-11-02

119 downloads per month
Used in 2 crates (via kontroli)

MIT license

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.

No runtime deps