Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Borrowed keys and values for IOCached::set_cache #196

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions cached_proc_macro/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use quote::quote;
use std::ops::Deref;
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::TypeReference;
use syn::TypeTuple;
use syn::{
parse_quote, parse_str, Attribute, Block, FnArg, Pat, PatType, PathArguments, ReturnType,
Signature, Type,
Expand Down Expand Up @@ -102,7 +104,9 @@ pub(super) fn make_cache_key_type(
) -> (TokenStream2, TokenStream2) {
match (key, convert, cache_type) {
(Some(key_str), Some(convert_str), _) => {
let cache_key_ty = parse_str::<Type>(key_str).expect("unable to parse cache key type");
let cache_key_ty = dereference_type(
parse_str::<Type>(key_str).expect("unable to parse cache key type"),
);

let key_convert_block =
parse_str::<Block>(convert_str).expect("unable to parse key convert block");
Expand All @@ -115,15 +119,34 @@ pub(super) fn make_cache_key_type(

(quote! {}, quote! {#key_convert_block})
}
(None, None, _) => (
quote! {(#(#input_tys),*)},
quote! {(#(#input_names.clone()),*)},
),
(None, None, _) => {
let input_tys = input_tys.into_iter().map(dereference_type);
(quote! {(#(#input_tys),*)}, quote! {(#(#input_names),*)})
}
(Some(_), None, _) => panic!("key requires convert to be set"),
(None, Some(_), None) => panic!("convert requires key or type to be set"),
}
}

/// Convert a type `&T` into a type `T`.
///
/// If the input is a tuple, the elements are dereferenced.
///
/// Otherwise, the input is returned unchanged.
pub(super) fn dereference_type(ty: Type) -> Type {
match ty {
Type::Reference(TypeReference { elem, .. }) => *elem,
Type::Tuple(TypeTuple { paren_token, elems }) => Type::Tuple(TypeTuple {
paren_token,
elems: elems
.iter()
.map(|ty| dereference_type(ty.clone()))
.collect(),
}),
_ => ty,
}
}

// if you define arguments as mutable, e.g.
// #[once]
// fn mutable_args(mut a: i32, mut b: i32) -> (i32, i32) {
Expand Down
12 changes: 6 additions & 6 deletions cached_proc_macro/src/io_cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,34 +336,34 @@ pub fn io_cached(args: TokenStream, input: TokenStream) -> TokenStream {
if asyncness.is_some() && !args.disk {
quote! {
if let Ok(result) = &result {
cache.cache_set(key, result.value.clone()).await.map_err(#map_error)?;
cache.cache_set(key, result.value).await.map_err(#map_error)?;
}
}
} else {
quote! {
if let Ok(result) = &result {
cache.cache_set(key, result.value.clone()).map_err(#map_error)?;
cache.cache_set(key, result.value).map_err(#map_error)?;
}
}
},
quote! { let mut r = ::cached::Return::new(result.clone()); r.was_cached = true; return Ok(r) },
quote! { let mut r = ::cached::Return::new(result); r.was_cached = true; return Ok(r) },
)
} else {
(
if asyncness.is_some() && !args.disk {
quote! {
if let Ok(result) = &result {
cache.cache_set(key, result.clone()).await.map_err(#map_error)?;
cache.cache_set(key, result).await.map_err(#map_error)?;
}
}
} else {
quote! {
if let Ok(result) = &result {
cache.cache_set(key, result.clone()).map_err(#map_error)?;
cache.cache_set(key, result).map_err(#map_error)?;
}
}
},
quote! { return Ok(result.clone()) },
quote! { return Ok(result) },
)
};
(set_cache_block, return_cache_block)
Expand Down
10 changes: 5 additions & 5 deletions examples/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,25 @@ enum ExampleError {
time = 30,
map_error = r##"|e| ExampleError::DiskError(format!("{:?}", e))"##
)]
fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
fn cached_sleep_secs(secs: &u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(())
}

fn main() {
print!("1. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");

use cached::IOCached;
CACHED_SLEEP_SECS.cache_remove(&2).unwrap();
print!("third sync call with a 2 seconds sleep (slow, after cache-remove)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");
}
2 changes: 1 addition & 1 deletion examples/kitchen_sink_proc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ fn slow_result(a: u32, b: u32) -> Result<u32, ()> {

// return a flag indicated whether the result was cached
#[cached(with_cached_flag = true)]
fn with_cached_flag(a: String) -> Return<String> {
fn with_cached_flag(a: &str) -> Return<&String> {
sleep(Duration::new(1, 0));
Return::new(a)
}
Expand Down
28 changes: 15 additions & 13 deletions examples/redis-async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ enum ExampleError {
cache_prefix_block = r##"{ "cache-redis-example-1" }"##,
map_error = r##"|e| ExampleError::RedisError(format!("{:?}", e))"##
)]
async fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
async fn cached_sleep_secs(secs: &u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(())
}

Expand All @@ -45,8 +45,8 @@ async fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
.expect("error building example redis cache")
} "##
)]
async fn async_cached_sleep_secs(secs: u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
async fn async_cached_sleep_secs(secs: &u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(secs.to_string())
}

Expand Down Expand Up @@ -75,38 +75,40 @@ static CONFIG: Lazy<Config> = Lazy::new(Config::load);
.expect("error building example redis cache")
} "##
)]
async fn async_cached_sleep_secs_config(secs: u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
async fn async_cached_sleep_secs_config(secs: &u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(secs.to_string())
}

#[tokio::main]
async fn main() {
print!("1. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).await.unwrap();
cached_sleep_secs(&2).await.unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).await.unwrap();
cached_sleep_secs(&2).await.unwrap();
println!("done");

print!("2. first async call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
async_cached_sleep_secs(2).await.unwrap();
async_cached_sleep_secs(&2).await.unwrap();
println!("done");
print!("second async call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
async_cached_sleep_secs(2).await.unwrap();
async_cached_sleep_secs(&2).await.unwrap();
println!("done");

async_cached_sleep_secs_config_prime_cache(2).await.unwrap();
async_cached_sleep_secs_config_prime_cache(&2)
.await
.unwrap();
print!("3. first primed async call with a 2 seconds sleep (should be fast)...");
io::stdout().flush().unwrap();
async_cached_sleep_secs_config(2).await.unwrap();
async_cached_sleep_secs_config(&2).await.unwrap();
println!("done");
print!("second async call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
async_cached_sleep_secs_config(2).await.unwrap();
async_cached_sleep_secs_config(&2).await.unwrap();
println!("done");
}
28 changes: 14 additions & 14 deletions examples/redis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ enum ExampleError {
cache_prefix_block = r##"{ "cache-redis-example-1" }"##,
map_error = r##"|e| ExampleError::RedisError(format!("{:?}", e))"##
)]
fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
fn cached_sleep_secs(secs: &u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(())
}

Expand All @@ -41,8 +41,8 @@ fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
time = 30,
map_error = r##"|e| ExampleError::RedisError(format!("{:?}", e))"##
)]
fn cached_sleep_secs_example_2(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
fn cached_sleep_secs_example_2(secs: &u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(())
}

Expand Down Expand Up @@ -70,45 +70,45 @@ static CONFIG: Lazy<Config> = Lazy::new(Config::load);
.expect("error building example redis cache")
} "##
)]
fn cached_sleep_secs_config(secs: u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
fn cached_sleep_secs_config(secs: &u64) -> Result<String, ExampleError> {
std::thread::sleep(Duration::from_secs(*secs));
Ok(secs.to_string())
}

#[tokio::main]
async fn main() {
print!("1. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");

use cached::IOCached;
CACHED_SLEEP_SECS.cache_remove(&2).unwrap();
print!("third sync call with a 2 seconds sleep (slow, after cache-remove)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
cached_sleep_secs(&2).unwrap();
println!("done");

print!("2. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs_example_2(2).unwrap();
cached_sleep_secs_example_2(&2).unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs_example_2(2).unwrap();
cached_sleep_secs_example_2(&2).unwrap();
println!("done");

cached_sleep_secs_config_prime_cache(2).unwrap();
cached_sleep_secs_config_prime_cache(&2).unwrap();
print!("3. first primed async call with a 2 seconds sleep (should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs_config(2).unwrap();
cached_sleep_secs_config(&2).unwrap();
println!("done");
print!("second async call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs_config(2).unwrap();
cached_sleep_secs_config(&2).unwrap();
println!("done");
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ pub trait IOCached<K, V> {
/// # Errors
///
/// Should return `Self::Error` if the operation fails
fn cache_set(&self, k: K, v: V) -> Result<Option<V>, Self::Error>;
fn cache_set(&self, k: &K, v: &V) -> Result<Option<V>, Self::Error>;

/// Remove a cached value
///
Expand Down Expand Up @@ -431,7 +431,7 @@ pub trait IOCachedAsync<K, V> {
type Error;
async fn cache_get(&self, k: &K) -> Result<Option<V>, Self::Error>;

async fn cache_set(&self, k: K, v: V) -> Result<Option<V>, Self::Error>;
async fn cache_set(&self, k: &K, v: &V) -> Result<Option<V>, Self::Error>;

/// Remove a cached value
async fn cache_remove(&self, k: &K) -> Result<Option<V>, Self::Error>;
Expand Down
26 changes: 13 additions & 13 deletions src/stores/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ where
}
}

fn cache_set(&self, key: K, value: V) -> Result<Option<V>, DiskCacheError> {
fn cache_set(&self, key: &K, value: &V) -> Result<Option<V>, DiskCacheError> {
let key = key.to_string();
let value = rmp_serde::to_vec(&CachedDiskValue::new(value))?;

Expand Down Expand Up @@ -312,10 +312,10 @@ mod tests {
let cached = cache.cache_get(&6).unwrap();
assert!(cached.is_none());

let cached = cache.cache_set(6, 4444).unwrap();
let cached = cache.cache_set(&6, &4444).unwrap();
assert_eq!(cached, None);

let cached = cache.cache_set(6, 5555).unwrap();
let cached = cache.cache_set(&6, &5555).unwrap();
assert_eq!(cached, Some(4444));

let cached = cache.cache_get(&6).unwrap();
Expand All @@ -340,23 +340,23 @@ mod tests {

assert!(c.cache_get(&1).unwrap().is_none());

assert!(c.cache_set(1, 100).unwrap().is_none());
assert!(c.cache_set(&1, &100).unwrap().is_none());
assert!(c.cache_get(&1).unwrap().is_some());

sleep(Duration::new(2, 500000));
assert!(c.cache_get(&1).unwrap().is_none());

let old = c.cache_set_lifespan(1).unwrap();
assert_eq!(2, old);
assert!(c.cache_set(1, 100).unwrap().is_none());
assert!(c.cache_set(&1, &100).unwrap().is_none());
assert!(c.cache_get(&1).unwrap().is_some());

sleep(Duration::new(1, 600000));
assert!(c.cache_get(&1).unwrap().is_none());

c.cache_set_lifespan(10).unwrap();
assert!(c.cache_set(1, 100).unwrap().is_none());
assert!(c.cache_set(2, 100).unwrap().is_none());
assert!(c.cache_set(&1, &100).unwrap().is_none());
assert!(c.cache_set(&2, &100).unwrap().is_none());
assert_eq!(c.cache_get(&1).unwrap().unwrap(), 100);
assert_eq!(c.cache_get(&1).unwrap().unwrap(), 100);
}
Expand All @@ -369,9 +369,9 @@ mod tests {
.build()
.unwrap();

assert!(cache.cache_set(1, 100).unwrap().is_none());
assert!(cache.cache_set(2, 200).unwrap().is_none());
assert!(cache.cache_set(3, 300).unwrap().is_none());
assert!(cache.cache_set(&1, &100).unwrap().is_none());
assert!(cache.cache_set(&2, &200).unwrap().is_none());
assert!(cache.cache_set(&3, &300).unwrap().is_none());

assert_eq!(100, cache.cache_remove(&1).unwrap().unwrap());

Expand All @@ -385,9 +385,9 @@ mod tests {
.build()
.unwrap();

assert!(cache.cache_set(1, 100).unwrap().is_none());
assert!(cache.cache_set(2, 200).unwrap().is_none());
assert!(cache.cache_set(3, 300).unwrap().is_none());
assert!(cache.cache_set(&1, &100).unwrap().is_none());
assert!(cache.cache_set(&2, &200).unwrap().is_none());
assert!(cache.cache_set(&3, &300).unwrap().is_none());

assert_eq!(100, cache.cache_remove(&1).unwrap().unwrap());

Expand Down
Loading