Skip to content

Commit b99113c

Browse files
committed
docs: modernize examples to unquoted macro attrs, infallible sharded API, optional map_error
- `struct_method`/`expires_per_key`: unquoted `convert` blocks; `struct_method` adds `companions_vis` - `kitchen_sink`: unquoted `create` expressions - `disk`: unquoted `map_error` closure plus a `From<RedbCacheError>` path with no `map_error` - `sharded`: correct the mislabeled `.expect` on the `load_record` Result
1 parent 0c635c5 commit b99113c

5 files changed

Lines changed: 46 additions & 13 deletions

File tree

examples/disk.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,34 @@ enum ExampleError {
2121
// When the macro constructs your RedbCache instance (the default disk engine),
2222
// the default cache files will be stored
2323
// under $system_cache_dir/<exe>_cached_disk_cache/
24+
//
25+
// `map_error` is an unquoted closure here; the legacy quoted-string form
26+
// (`map_error = r##"|e| ..."##`) is still accepted.
2427
#[concurrent_cached(
2528
disk = true,
2629
ttl_secs = 30,
27-
map_error = r##"|e| ExampleError::DiskError(format!("{:?}", e))"##
30+
map_error = |e| ExampleError::DiskError(format!("{e:?}"))
2831
)]
2932
fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
3033
std::thread::sleep(Duration::from_secs(secs));
3134
Ok(())
3235
}
3336

37+
// `map_error` is now optional: when the function's error type implements
38+
// `From<RedbCacheError>`, the macro converts store errors automatically via
39+
// `Into::into`, so no `map_error` closure is needed.
40+
impl From<cached::RedbCacheError> for ExampleError {
41+
fn from(e: cached::RedbCacheError) -> Self {
42+
ExampleError::DiskError(format!("{e:?}"))
43+
}
44+
}
45+
46+
#[concurrent_cached(disk = true, ttl_secs = 30)]
47+
fn cached_sleep_secs_from(secs: u64) -> Result<(), ExampleError> {
48+
std::thread::sleep(Duration::from_secs(secs));
49+
Ok(())
50+
}
51+
3452
fn main() {
3553
print!("1. first sync call with a 2 seconds sleep...");
3654
io::stdout().flush().unwrap();
@@ -64,4 +82,10 @@ fn main() {
6482
}
6583
cache.flush().unwrap(); // one durable commit persisting the cheap writes above
6684
println!("flushed 3 cheap writes to disk in a single durable commit");
85+
86+
// No `map_error` needed: ExampleError: From<RedbCacheError> handles conversion.
87+
print!("call without map_error (From<RedbCacheError>) ...");
88+
io::stdout().flush().unwrap();
89+
cached_sleep_secs_from(1).unwrap();
90+
println!("done");
6791
}

examples/expires_per_key.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ impl Expires for MyValue {
4848
// Add `max_size = N` to switch to an LRU-bounded ExpiringLruCache.
4949
// `key`/`convert` narrow the cache key to just user_id so expiry_offset_ms only
5050
// influences the token's lifetime, not which cache slot it occupies.
51-
#[cached(expires = true, key = "u64", convert = "{ user_id }")]
51+
#[cached(expires = true, key = "u64", convert = { user_id })]
5252
fn fetch_token(user_id: u64, expiry_offset_ms: u64) -> MyValue {
5353
println!(" -> [fetch_token] generating new token for user {user_id}...");
5454
let n = CALL_N.fetch_add(1, Ordering::Relaxed);
@@ -72,7 +72,7 @@ fn get_session_token(expiry_offset_ms: u64) -> MyValue {
7272
// `expires = true` composes with a `Result` return: only the `Ok(MyValue)` is
7373
// cached (and expires per-value via `Expires`); an `Err` is never cached, so a
7474
// failing call always re-executes.
75-
#[cached(expires = true, key = "u64", convert = "{ user_id }")]
75+
#[cached(expires = true, key = "u64", convert = { user_id })]
7676
fn fetch_token_result(user_id: u64, expiry_offset_ms: u64, fail: bool) -> Result<MyValue, String> {
7777
println!(" -> [fetch_token_result] generating token for user {user_id} (fail={fail})...");
7878
if fail {
@@ -88,7 +88,7 @@ fn fetch_token_result(user_id: u64, expiry_offset_ms: u64, fail: bool) -> Result
8888
// `expires = true` composes with an `Option` return: only `Some(MyValue)` is
8989
// cached (and expires per-value); a `None` is never cached, so a miss keeps
9090
// re-executing until a `Some` is produced.
91-
#[cached(expires = true, key = "u64", convert = "{ user_id }")]
91+
#[cached(expires = true, key = "u64", convert = { user_id })]
9292
fn fetch_token_option(user_id: u64, expiry_offset_ms: u64, found: bool) -> Option<MyValue> {
9393
println!(" -> [fetch_token_option] generating token for user {user_id} (found={found})...");
9494
if !found {

examples/kitchen_sink.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ fn fib(n: u32) -> u32 {
2929
// Note that the cache key type is a tuple of function argument types.
3030
#[cached(
3131
ty = "UnboundCache<u32, u32>",
32-
create = "{ UnboundCache::builder().capacity(50).build().unwrap() }"
32+
create = UnboundCache::builder().capacity(50).build().unwrap()
3333
)]
3434
fn fib_specific(n: u32) -> u32 {
3535
if n == 0 || n == 1 {
@@ -50,7 +50,7 @@ fn slow(a: u32, b: u32) -> u32 {
5050
// Note that the cache key type is a `String` created from the borrow arguments
5151
#[cached(
5252
ty = "LruCache<String, usize>",
53-
create = "{ LruCache::builder().max_size(100).build().unwrap() }",
53+
create = LruCache::builder().max_size(100).build().unwrap(),
5454
convert = r#"{ format!("{a}{b}") }"#
5555
)]
5656
fn keyed(a: &str, b: &str) -> usize {
@@ -137,7 +137,7 @@ impl<K: Hash + Eq, V> Cached<K, V> for MyCache<K, V> {
137137
#[cached(
138138
name = "CUSTOM",
139139
ty = "MyCache<u32, ()>",
140-
create = "{ MyCache::with_capacity(50) }"
140+
create = MyCache::with_capacity(50)
141141
)]
142142
fn custom(n: u32) {
143143
if n == 0 {

examples/sharded.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ fn main() {
9292
// Result: only Ok is cached
9393
let r1 = load_record(42);
9494
let r2 = load_record(42);
95-
assert_eq!(r1.as_deref().expect("infallible"), "record_42");
96-
assert_eq!(r2.as_deref().expect("infallible"), "record_42");
95+
assert_eq!(r1.as_deref().expect("load_record returns Ok"), "record_42");
96+
assert_eq!(r2.as_deref().expect("load_record returns Ok"), "record_42");
9797
println!("load_record(42) = {:?} (cached)", r1);
9898

9999
// Option: None is NOT cached by default; the function re-executes each time

examples/struct_method.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,19 @@ impl Worker {
5454
/// `convert` folds `self.id` into the key so different instances
5555
/// do not share cache entries.
5656
///
57-
/// A `compute_no_cache` sibling is also generated (same visibility)
58-
/// for calling the raw computation without touching the cache.
57+
/// A `compute_no_cache` sibling is also generated for calling the raw
58+
/// computation without touching the cache. Its visibility defaults to the
59+
/// method's own; `companions_vis = "pub(crate)"` overrides it independently.
5960
/// The `_prime_cache` companion is NOT generated for `in_impl` methods.
60-
#[cached(in_impl = true, key = "(u64, u32)", convert = "{ (self.id, n) }")]
61+
///
62+
/// `convert` is an unquoted block here (`{ (self.id, n) }`); the legacy
63+
/// quoted-string form (`convert = "{ (self.id, n) }"`) is still accepted.
64+
#[cached(
65+
in_impl = true,
66+
key = "(u64, u32)",
67+
convert = { (self.id, n) },
68+
companions_vis = "pub(crate)"
69+
)]
6170
fn compute(&self, n: u32) -> u32 {
6271
println!(" [miss] Worker(id={}) compute(n={n})", self.id);
6372
self.factor * n
@@ -128,7 +137,7 @@ trait Processor {
128137

129138
/// Cached computation for any `Processor`-like object.
130139
/// Key: `(id, input)`. `factor` is only used on a cache miss.
131-
#[cached(key = "(u64, u32)", convert = "{ (id, input) }")]
140+
#[cached(key = "(u64, u32)", convert = { (id, input) })]
132141
fn processor_compute(id: u64, factor: u32, input: u32) -> u32 {
133142
println!(" [miss] processor_compute(id={id}, factor={factor}, input={input})");
134143
input * factor

0 commit comments

Comments
 (0)