Skip to content

Commit

Permalink
support non copyable types and emit error for unsupported flag combo
Browse files Browse the repository at this point in the history
  • Loading branch information
Raz-Hemo committed Mar 3, 2024
1 parent 6a42aea commit 79e022f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 5 additions & 1 deletion cached_proc_macro/src/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ pub fn cached(args: TokenStream, input: TokenStream) -> TokenStream {
_ => panic!("the result and option attributes are mutually exclusive"),
};

if args.result_fallback && args.sync_writes {
panic!("the result_fallback and sync_writes attributes are mutually exclusive");
}

let set_cache_and_return = quote! {
#set_cache_block
result
Expand Down Expand Up @@ -255,7 +259,7 @@ pub fn cached(args: TokenStream, input: TokenStream) -> TokenStream {
let old_val = {
#lock
let (result, has_expired) = cache.cache_get_expired(&key);
if let (Some(result), false) = (result, has_expired) {
if let (Some(result), false) = (result.clone(), has_expired) {
#return_cache_block
}
result
Expand Down
16 changes: 10 additions & 6 deletions tests/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1571,8 +1571,12 @@ fn test_expiring_value_unexpired_article_returned_with_hit() {
}
}

#[cached::proc_macro::cached(result = true, time = 1, result_fallback = true)]
fn always_failing() -> Result<i64, ()> {
#[cached::proc_macro::cached(
result = true,
time = 1,
result_fallback = true
)]
fn always_failing() -> Result<String, ()> {
Err(())
}

Expand All @@ -1586,8 +1590,8 @@ fn test_result_fallback() {
}

// Pretend it succeeded once
ALWAYS_FAILING.lock().unwrap().cache_set((), 1);
assert_eq!(always_failing(), Ok(1));
ALWAYS_FAILING.lock().unwrap().cache_set((), "abc".to_string());
assert_eq!(always_failing(), Ok("abc".to_string()));
{
let cache = ALWAYS_FAILING.lock().unwrap();
assert_eq!(cache.cache_hits(), Some(1));
Expand All @@ -1597,14 +1601,14 @@ fn test_result_fallback() {
std::thread::sleep(std::time::Duration::from_millis(2000));

// Even though the cache should've expired, the `result_fallback` flag means it refreshes the cache with the last valid result
assert_eq!(always_failing(), Ok(1));
assert_eq!(always_failing(), Ok("abc".to_string()));
{
let cache = ALWAYS_FAILING.lock().unwrap();
assert_eq!(cache.cache_hits(), Some(1));
assert_eq!(cache.cache_misses(), Some(2));
}

assert_eq!(always_failing(), Ok(1));
assert_eq!(always_failing(), Ok("abc".to_string()));
{
let cache = ALWAYS_FAILING.lock().unwrap();
assert_eq!(cache.cache_hits(), Some(2));
Expand Down

0 comments on commit 79e022f

Please sign in to comment.