#lazy-evaluation #initialization #cache

sloth

Provides a generic wrapper struct for lazy initialization

5 releases

0.2.0 Sep 3, 2019
0.1.3 Sep 1, 2019
0.1.2 Sep 1, 2019
0.1.1 Aug 31, 2019
0.1.0 Aug 31, 2019

#233 in Caching

Download history 26/week @ 2024-03-14 34/week @ 2024-03-21 35/week @ 2024-03-28 43/week @ 2024-04-04 39/week @ 2024-04-11 12/week @ 2024-04-18 30/week @ 2024-04-25 132/week @ 2024-05-02 23/week @ 2024-05-09 9/week @ 2024-05-16 37/week @ 2024-05-23 38/week @ 2024-05-30 8/week @ 2024-06-06 8/week @ 2024-06-13 45/week @ 2024-06-20 11/week @ 2024-06-27

82 downloads per month

MIT/Apache

23KB
384 lines

docs.rs Build Status

sloth

This crate provides a generic pointer-like Lazy<T, Eval> struct for lazily initialized values. It can be used for expensive-to-calculate values to ensure that the evaluation logic runs only once and only if needed.

For example:

use sloth::Lazy;

fn get_expensive_string() -> String {
    // do something expensive here to obtain the result,
    // such as read and process file contents
    String::from("some expensive string we got from a file or something")
}

fn get_expensive_number() -> i32 {
    // do something expensive here to calculate the result,
    // such as build a supercomputer and wait 7.5 million years
    42
}

let lazy_string = Lazy::new(get_expensive_string);
let lazy_number = Lazy::new(get_expensive_number);

//...
let must_use_string = true;
//...

if must_use_string {
    println!("Expensive string is: {}", *lazy_string);
    println!("It has length: {}", lazy_string.len());

    // get_expensive_string() has been called only once,
    // get_expensive_number() has not been called
} else {
    println!("Expensive number is: {}", *lazy_number);
    println!("Its square is {}", lazy_number.pow(2));

    // get_expensive_string() has not been called,
    // get_expensive_number() has been called only once
}

The evaluated value of a mutable Lazy can be modified:

use sloth::Lazy;

let mut lazy_vec = Lazy::new(|| vec![2, -5, 6, 0]);

lazy_vec.retain(|n| *n > 0);

assert_eq!(*lazy_vec, vec![2, 6]);

Lazy can be consumed and turned into its value via unwrap():

use sloth::Lazy;

let lazy_value = Lazy::new(|| "moo");

let output = String::from("a cow goes ") + lazy_value.unwrap();

No runtime deps