diff --git a/Cargo.toml b/Cargo.toml index 28dce54..9960cb1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -139,3 +139,7 @@ required-features = ["async", "proc_macro"] [[example]] name = "expiring_sized_cache" required-features = ["async_tokio_rt_multi_thread"] + +[[example]] +name = "dyn_trait_pass" +required-features = [ "default" ] diff --git a/examples/dyn_trait_pass.rs b/examples/dyn_trait_pass.rs new file mode 100644 index 0000000..9f29c3e --- /dev/null +++ b/examples/dyn_trait_pass.rs @@ -0,0 +1,62 @@ +use cached::proc_macro::cached; +use thiserror::Error; + +#[allow(dead_code)] +#[derive(Error, Debug, PartialEq, Clone)] +enum ProcessorError { + #[error("error wile processing task :{0}")] + TaskError(String), +} + +trait AnyTaskProcessor { + type Error; + + fn execute(&self) -> Result; +} + +struct CustomProcessor; + +impl AnyTaskProcessor for CustomProcessor { + type Error = ProcessorError; + + fn execute(&self) -> Result { + Ok(String::from("hello world")) + } +} + +#[cached( + time = 100, // Expires after 100 seconds + size = 1, // Cache size (1) elements + result = true, // Cache the Result type + key = "i32", // Necessary option for caching method result + convert = r##"{ 1 }"## // Necessary option for key -> used static integer for example only +)] +fn cached_execute( + processor: &(dyn AnyTaskProcessor + Send + Sync), +) -> Result { + std::thread::sleep(std::time::Duration::from_secs(2)); + let result = processor.execute()?; + Ok(result) +} + +fn main() -> Result<(), Box> { + let mean_delay = 100u128; + + let custom_processor = CustomProcessor {}; + + let start_time = std::time::Instant::now(); + let result = cached_execute(&custom_processor)?; + let elapsed = start_time.elapsed(); + assert_eq!(&result, "hello world"); + assert!(elapsed.as_millis() >= mean_delay); + + let start_time = std::time::Instant::now(); + let result = cached_execute(&custom_processor)?; + let elapsed = start_time.elapsed(); + assert_eq!(&result, "hello world"); + assert!(elapsed.as_millis() < mean_delay); + + println!("done!"); + + Ok(()) +}