9 releases

Uses old Rust 2015

0.5.3 Mar 11, 2015
0.5.2 Feb 9, 2015
0.5.0 Dec 16, 2014
0.4.1 Dec 2, 2014
0.3.2 Nov 19, 2014
Download history 8/week @ 2023-10-19 34/week @ 2023-10-26 11/week @ 2023-11-02 13/week @ 2023-11-09 17/week @ 2023-11-16 24/week @ 2023-11-23 66/week @ 2023-11-30 24/week @ 2023-12-07 25/week @ 2023-12-14 26/week @ 2023-12-21 8/week @ 2023-12-28 21/week @ 2024-01-04 15/week @ 2024-01-11 34/week @ 2024-01-18 18/week @ 2024-01-25 28/week @ 2024-02-01

95 downloads per month
Used in stream

MIT license

10KB
179 lines

Lazy

Lazy evaluation in Rust.

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]);
}

API

lazy!($expr)

Expands to Thunk::new(|| { $expr })

Thunk::new(|| -> T)

Takes an FnOnce closure, creates a delayed computation.

Thunk::force()

Forces the evaluation of the thunk so subsequent accesses are cheap. Values are stored unboxed.

Thunk::unwrap()

Consumes and forces the evaluation of the thunk and returns the contained value.

Thunk::deref() / Thunk::deref_mut()

Gets the value out of the thunk by evaluating the closure or grabbing it from the cache. Allows you to call methods on the thunk as if it was an instance of the contained valued through auto-deref.

There is also an equivalent API for SyncThunk, which is Send + Sync and usable for safe, concurrent laziness, except that they are created using sync_lazy! or by doing use lazy::SyncThunk as Thunk and using lazy!.

Dependencies

~19KB