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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//! Cache and memoization utilities for improved performance
//!
//! This module provides caching and memoization utilities to improve performance
//! by avoiding redundant computations.
use cached::{proc_macro::cached, Cached, SizedCache};
use std::hash::Hash;
use std::time::{Duration, Instant};
/// Cache configuration for the library
#[derive(Debug, Clone, Copy)]
pub struct CacheConfig {
/// Default cache size (number of items)
pub default_size: usize,
/// Default time-to-live for cached items (seconds)
pub default_ttl: u64,
/// Whether to enable caching by default
pub enable_caching: bool,
}
impl Default for CacheConfig {
fn default() -> Self {
Self {
default_size: 1024,
default_ttl: 3600, // 1 hour
enable_caching: true,
}
}
}
/// A sized cache with time-to-live (TTL) functionality
pub struct TTLSizedCache<K, V> {
/// Internal cache
cache: SizedCache<K, (V, Instant)>,
/// Time-to-live for cache entries
ttl: Duration,
}
impl<K, V> TTLSizedCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
/// Create a new TTL cache with specified size and TTL
#[must_use]
pub fn new(size: usize, ttlseconds: u64) -> Self {
Self {
cache: SizedCache::with_size(size),
ttl: Duration::from_secs(ttlseconds),
}
}
/// Insert a key-value pair into the cache
pub fn insert(&mut self, key: K, value: V) {
let now = Instant::now();
self.cache.cache_set(key, (value, now));
}
/// Get a value from the cache if it exists and hasn't expired
#[must_use]
pub fn get(&mut self, key: &K) -> Option<V> {
match self.cache.cache_get(key) {
Some((value, timestamp)) if timestamp.elapsed() < self.ttl => Some(value.clone()),
Some(_) => {
// Value has expired, remove it from cache
self.cache.cache_remove(key);
None
}
None => None,
}
}
/// Remove a key-value pair from the cache
pub fn remove(&mut self, key: &K) {
self.cache.cache_remove(key);
}
/// Clear the cache
pub fn clear(&mut self) {
self.cache.cache_clear();
}
/// Get the number of items in the cache
#[must_use]
pub fn len(&self) -> usize {
(self.cache.cache_misses().unwrap_or(0) + self.cache.cache_hits().unwrap_or(0)) as usize
}
/// Check if the cache is empty
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// A thread-safe cache builder
///
/// This struct provides a fluent interface for configuring and building
/// various types of caches.
pub struct CacheBuilder {
/// Cache size
size: Option<usize>,
/// Time-to-live in seconds
ttl: Option<u64>,
/// Whether to make the cache thread-safe
thread_safe: bool,
}
impl Default for CacheBuilder {
fn default() -> Self {
Self::new()
}
}
impl CacheBuilder {
/// Create a new cache builder
#[must_use]
pub fn new() -> Self {
Self {
size: None,
ttl: None,
thread_safe: false,
}
}
/// Set the cache size
#[must_use]
pub fn with_size(mut self, size: usize) -> Self {
self.size = Some(size);
self
}
/// Set the time-to-live in seconds
#[must_use]
pub fn with_ttl(mut self, ttl: u64) -> Self {
self.ttl = Some(ttl);
self
}
/// Make the cache thread-safe
#[must_use]
pub fn thread_safe(mut self) -> Self {
self.thread_safe = true;
self
}
/// Build a sized cache
#[must_use]
pub fn build_sized_cache<K, V>(self) -> TTLSizedCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
let config = CacheConfig::default();
let size = self.size.unwrap_or(config.default_size);
let ttl = self.ttl.unwrap_or(config.default_ttl);
TTLSizedCache::new(size, ttl)
}
}
/// Example of how to use the cached attribute
///
/// ```ignore
/// // Example disabled due to missing cached dependency
/// use cached::proc_macro::cached;
///
/// #[cached(size = 100)]
/// pub fn expensive_calculation(x: u64) -> u64 {
/// // Expensive computation here
/// x * x
/// }
/// ```
/// Example of using TTL cache for memoization
///
/// This example shows how to use the TTL cache for memoizing expensive operations.
///
/// ```rust
/// use scirs2_core::cache::TTLSizedCache;
/// use std::time::Duration;
///
/// // Create a TTL cache
/// let mut cache = TTLSizedCache::<String, String>::new(100, 60);
///
/// // Cache a value
/// let key = "example_key";
/// let value = "example_value";
/// cache.insert(key.to_string(), value.to_string());
///
/// // Retrieve a value
/// let retrieved_value = cache.get(&key.to_string());
/// ```
/// Compute Fibonacci numbers with memoization
///
/// This function demonstrates the use of memoization for computing
/// Fibonacci numbers efficiently.
///
/// # Example
///
/// ```ignore
/// use cached::proc_macro::cached;
///
/// #[cached(size = 100)]
/// pub fn fibonacci_prime_cache(n: u64) -> u64 {
/// match n {
/// 0 => 0,
/// 1 => 1,
/// n => fibonacci_prime_cache(n - 1) + fibonacci_prime_cache(n - 2),
/// }
/// }
/// ```
///
/// # Arguments
///
/// * `n` - The Fibonacci number to compute
///
/// # Returns
///
/// * The nth Fibonacci number
#[cached]
#[must_use]
#[allow(dead_code)]
pub fn fibonacci(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
#[test]
fn test_ttl_sized_cache() {
let mut cache = TTLSizedCache::<i32, &str>::new(5, 1);
// Test insertion and retrieval
cache.insert(1, "one");
cache.insert(2, "two");
assert_eq!(cache.get(&1), Some("one"));
assert_eq!(cache.get(&2), Some("two"));
assert_eq!(cache.get(&3), None);
// Test TTL expiration
thread::sleep(Duration::from_secs(2));
assert_eq!(cache.get(&1), None);
assert_eq!(cache.get(&2), None);
// Test size limit
for i in 0..10 {
cache.insert(i, "test");
}
// Only the last 5 should be in the cache due to size limit
for i in 0..5 {
assert_eq!(cache.get(&i), None);
}
for i in 5..10 {
assert_eq!(cache.get(&i), Some("test"));
}
}
#[test]
fn test_cache_builder() {
let cache = CacheBuilder::new()
.with_size(10)
.with_ttl(60)
.build_sized_cache::<String, i32>();
assert!(cache.is_empty());
}
#[test]
fn test_fibonacci() {
// Compute fibonacci numbers with memoization
let fib10 = fibonacci(10);
let fib20 = fibonacci(20);
assert_eq!(fib10, 55);
assert_eq!(fib20, 6765);
// The second call should be much faster due to memoization
let start = Instant::now();
let fib20_again = fibonacci(20);
let _elapsed = start.elapsed();
assert_eq!(fib20_again, 6765);
// The second call should be very fast (less than 1ms)
assert!(_elapsed.as_millis() < 10);
}
}