2 releases (1 stable)

1.0.0 Mar 13, 2024
0.2.2 Jul 9, 2020

#448 in Memory management

Download history 3/week @ 2024-09-02 10/week @ 2024-09-09 3/week @ 2024-09-16 53/week @ 2024-09-23 31/week @ 2024-09-30 67/week @ 2024-10-07 13/week @ 2024-10-14 26/week @ 2024-10-21 29/week @ 2024-10-28 44/week @ 2024-11-04 12/week @ 2024-11-11 49/week @ 2024-11-18 50/week @ 2024-11-25 17/week @ 2024-12-02 36/week @ 2024-12-09 52/week @ 2024-12-16

170 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