2 releases (1 stable)

1.0.0 Mar 13, 2024
0.2.2 Jul 9, 2020

#429 in Memory management

Download history 12/week @ 2024-08-18 42/week @ 2024-08-25 6/week @ 2024-09-01 11/week @ 2024-09-08 3/week @ 2024-09-15 50/week @ 2024-09-22 31/week @ 2024-09-29 53/week @ 2024-10-06 29/week @ 2024-10-13 19/week @ 2024-10-20 31/week @ 2024-10-27 40/week @ 2024-11-03 21/week @ 2024-11-10 35/week @ 2024-11-17 63/week @ 2024-11-24 18/week @ 2024-12-01

140 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