-
Notifications
You must be signed in to change notification settings - Fork 94
/
kitchen_sink_proc_macro.rs
369 lines (344 loc) · 11.5 KB
/
kitchen_sink_proc_macro.rs
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use cached::proc_macro::cached;
use cached::Return;
use cached::{Cached, SizedCache, UnboundCache};
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;
use std::thread::{sleep, spawn};
use std::time::Duration;
// cached shorthand, uses the default unbounded cache.
// Equivalent to specifying `ty = "UnboundCache<(u32), u32>", create= "{ UnboundCache::new() }"`
#[cached]
fn fib(n: u32) -> u32 {
if n == 0 || n == 1 {
return n;
}
fib(n - 1) + fib(n - 2)
}
#[cached(name = "FLIB")]
fn fib_2(n: u32) -> u32 {
if n == 0 || n == 1 {
return n;
}
fib(n - 1) + fib(n - 2)
}
// Same as above, but preallocates some space.
#[cached(
ty = "UnboundCache<u32, u32>",
create = "{ UnboundCache::with_capacity(50) }"
)]
fn fib_specific(n: u32) -> u32 {
if n == 0 || n == 1 {
return n;
}
fib_specific(n - 1) + fib_specific(n - 2)
}
// Specify a specific cache type
// Note that the cache key type is a tuple of function argument types.
#[cached(
ty = "SizedCache<(u32, u32), u32>",
create = "{ SizedCache::with_size(100) }"
)]
fn slow(a: u32, b: u32) -> u32 {
sleep(Duration::new(2, 0));
a * b
}
// Specify a specific cache type and an explicit key expression
// Note that the cache key type is a `String` created from the borrow arguments
// Note that key is not used, convert requires either key or type to be set.
#[cached(
ty = "SizedCache<String, usize>",
create = "{ SizedCache::with_size(100) }",
convert = r#"{ format!("{}{}", a, b) }"#
)]
fn keyed(a: &str, b: &str) -> usize {
let size = a.len() + b.len();
sleep(Duration::new(size as u64, 0));
size
}
#[cached(key = "String", convert = r#"{ format!("{}{}", a, b) }"#)]
fn keyed_key(a: &str, b: &str) -> usize {
let size = a.len() + b.len();
sleep(Duration::new(size as u64, 0));
size
}
// Implement our own cache type
struct MyCache<K: Hash + Eq, V> {
store: HashMap<K, V>,
capacity: usize,
}
impl<K: Hash + Eq, V> MyCache<K, V> {
pub fn with_capacity(size: usize) -> MyCache<K, V> {
MyCache {
store: HashMap::with_capacity(size),
capacity: size,
}
}
}
impl<K: Hash + Eq, V> Cached<K, V> for MyCache<K, V> {
fn cache_get<Q>(&mut self, k: &Q) -> Option<&V>
where
K: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + ?Sized,
{
self.store.get(k)
}
fn cache_get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where
K: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + ?Sized,
{
self.store.get_mut(k)
}
fn cache_get_or_set_with<F: FnOnce() -> V>(&mut self, k: K, f: F) -> &mut V {
self.store.entry(k).or_insert_with(f)
}
fn cache_set(&mut self, k: K, v: V) -> Option<V> {
self.store.insert(k, v)
}
fn cache_remove<Q>(&mut self, k: &Q) -> Option<V>
where
K: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + ?Sized,
{
self.store.remove(k)
}
fn cache_clear(&mut self) {
self.store.clear();
}
fn cache_reset(&mut self) {
self.store = HashMap::with_capacity(self.capacity);
}
fn cache_size(&self) -> usize {
self.store.len()
}
}
// Specify our custom cache and supply an instance to use
#[cached(ty = "MyCache<u32, ()>", create = "{ MyCache::with_capacity(50) }")]
fn custom(n: u32) {
if n == 0 {
return;
}
custom(n - 1);
}
// handle results, don't cache errors
#[cached(result = true)]
fn slow_result(a: u32, b: u32) -> Result<u32, ()> {
sleep(Duration::new(2, 0));
Ok(a * b)
}
// return a flag indicated whether the result was cached
#[cached(with_cached_flag = true)]
fn with_cached_flag(a: String) -> Return<String> {
sleep(Duration::new(1, 0));
Return::new(a)
}
// return a flag indicated whether the result was cached, with a result type
#[cached(result = true, with_cached_flag = true)]
fn with_cached_flag_result(a: String) -> Result<cached::Return<String>, ()> {
sleep(Duration::new(1, 0));
Ok(Return::new(a))
}
// return a flag indicated whether the result was cached, with an option type
#[cached(option = true, with_cached_flag = true)]
fn with_cached_flag_option(a: String) -> Option<Return<String>> {
sleep(Duration::new(1, 0));
Some(Return::new(a))
}
// A simple cache that expires after a second. We'll keep the
// value fresh by priming it in a separate thread.
#[cached(time = 1)]
fn expires_for_priming(a: i32) -> i32 {
a
}
// NOTE:
// The following fails with compilation error
// ```
// error:
// When specifying `with_cached_flag = true`, the return type must be wrapped in `cached::Return<T>`.
// The following return types are supported:
// | `cached::Return<T>`
// | `std::result::Result<cachedReturn<T>, E>`
// | `std::option::Option<cachedReturn<T>>`
// Found type: std::result::Result<u32,()>.
// ```
//
// #[cached(with_cached_flag = true)]
// fn with_cached_flag_requires_return_type(a: u32) -> std::result::Result<u32, ()> {
// Ok(1)
// }
pub fn main() {
println!("\n ** default cache with default name **");
fib(3);
fib(3);
{
let cache = FIB.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 2);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(4));
// make sure lock is dropped
}
fib(10);
fib(10);
println!("\n ** default cache with explicit name **");
fib_2(3);
fib_2(3);
{
let cache = FLIB.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(1));
// make sure lock is dropped
}
println!("\n ** specific cache **");
fib_specific(20);
fib_specific(20);
{
let cache = FIB_SPECIFIC.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 19);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(21));
// make sure lock is dropped
}
fib_specific(20);
fib_specific(20);
println!("\n ** custom cache **");
custom(25);
{
let cache = CUSTOM.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits(), None);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), None);
//custom cache doesn't implement these so they're None
// make sure lock is dropped
}
println!("\n ** slow func **");
println!(" - first run `slow(10)`");
slow(10, 10);
println!(" - second run `slow(10)`");
slow(10, 10);
{
let cache = SLOW.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses().unwrap(), 1);
// make sure the cache-lock is dropped
}
println!("\n ** slow result func **");
println!(" - first run `slow_result(10)`");
let _ = slow_result(10, 10);
println!(" - second run `slow_result(10)`");
let _ = slow_result(10, 10);
{
let cache = SLOW_RESULT.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(1));
// make sure the cache-lock is dropped
}
println!("\n ** with cached flag func **");
println!(" - first run `with_cached_flag(\"a\")`");
let r = with_cached_flag("a".to_string());
println!("was cached: {}", r.was_cached);
println!(" - second run `with_cached_flag(\"a\")`");
let r = with_cached_flag("a".to_string());
println!("was cached: {}", r.was_cached);
println!("derefs to inner, *r == \"a\" : {}", *r == "a");
println!(
"derefs to inner, r.as_str() == \"a\" : {}",
r.as_str() == "a"
);
{
let cache = WITH_CACHED_FLAG.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(1));
// make sure the cache-lock is dropped
}
println!("\n ** with cached flag result func **");
println!(" - first run `with_cached_flag_result(\"a\")`");
let r = with_cached_flag_result("a".to_string()).expect("with_cached_flag_result failed");
println!("was cached: {}", r.was_cached);
println!(" - second run `with_cached_flag_result(\"a\")`");
let r = with_cached_flag_result("a".to_string()).expect("with_cached_flag_result failed");
println!("was cached: {}", r.was_cached);
println!("derefs to inner, *r : {:?}", *r);
println!("derefs to inner, *r == \"a\" : {}", *r == "a");
println!(
"derefs to inner, r.as_str() == \"a\" : {}",
r.as_str() == "a"
);
{
let cache = WITH_CACHED_FLAG_RESULT.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(1));
// make sure the cache-lock is dropped
}
println!("\n ** with cached flag option func **");
println!(" - first run `with_cached_flag_option(\"a\")`");
let r = with_cached_flag_option("a".to_string()).expect("with_cached_flag_result failed");
println!("was cached: {}", r.was_cached);
println!(" - second run `with_cached_flag_option(\"a\")`");
let r = with_cached_flag_option("a".to_string()).expect("with_cached_flag_result failed");
println!("was cached: {}", r.was_cached);
println!("derefs to inner, *r : {:?}", *r);
println!("derefs to inner, *r == \"a\" : {}", *r == "a");
println!(
"derefs to inner, r.as_str() == \"a\" : {}",
r.as_str() == "a"
);
{
let cache = WITH_CACHED_FLAG_OPTION.lock().unwrap();
println!("hits: {:?}", cache.cache_hits());
assert_eq!(cache.cache_hits().unwrap(), 1);
println!("misses: {:?}", cache.cache_misses());
assert_eq!(cache.cache_misses(), Some(1));
// make sure the cache-lock is dropped
}
println!("\n ** refresh by priming **");
let h = spawn(|| {
for _ in 1..6 {
expires_for_priming_prime_cache(1);
sleep(Duration::from_millis(500));
}
});
sleep(Duration::from_millis(200));
for n in 1..6 {
assert_eq!(1, expires_for_priming(1));
{
let c = EXPIRES_FOR_PRIMING.lock().unwrap();
assert_eq!(n, c.cache_hits().unwrap());
assert_eq!(0, c.cache_misses().unwrap());
println!(
"primed cache hits: {}, misses: {}",
c.cache_hits().unwrap(),
c.cache_misses().unwrap()
);
}
sleep(Duration::from_millis(500));
}
h.join().unwrap();
println!("now wait for expiration");
sleep(Duration::from_millis(1000));
assert_eq!(1, expires_for_priming(1));
{
let c = EXPIRES_FOR_PRIMING.lock().unwrap();
assert_eq!(5, c.cache_hits().unwrap());
assert_eq!(1, c.cache_misses().unwrap());
println!(
"primed cache hits: {}, misses: {}",
c.cache_hits().unwrap(),
c.cache_misses().unwrap()
);
}
println!("\ndone!");
}