1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! Simple memoization for pure functions with cloneable inputs/outputs.
//!
//! Provides [`memoize`] to wrap a pure function so that repeated calls with the
//! same argument return a cached result instead of recomputing.
//!
//! Notes and caveats:
//! - Inputs must implement `Eq + Hash + Clone`; outputs must implement `Clone`.
//! - Cache is stored in a `Mutex<HashMap<..>>`, so cloned closures are
//! shareable across threads but concurrent access is serialized.
//! - This is best for small, frequently repeated computations; unbounded cache
//! growth may not be suitable for long-running processes.
//!
//! Basic example:
//! ```rust
//! use toolchest::functions::memoize;
//!
//! fn slow_square(n: u32) -> u32 { n * n }
//! let sq = memoize(slow_square);
//! assert_eq!(sq(3), 9);
//! assert_eq!(sq(3), 9); // cached
//! ```
use HashMap;
use Hash;
use ;
/// Memoize a pure function with cloneable inputs/outputs.
///
/// Returns a closure that caches results by input argument. The cache lives as
/// long as the returned closure is alive, and is shared across clones of the
/// closure.