gs_rust_cache/
lib.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
//! Thread safe cache developed using [lru crate](https://crates.io/crates/lru) as its core. 
//! Supports LRU, positive and negative TTLs and miss handler function.
//! It is intended to be used using the function `retrieve_or_compute`, which will return the value if it is in the cache,
//! or compute it using the miss_handler function if it is not.
//!
//! ## Example
//!
//! ```rust
//! extern crate gs_rust_cache;
//! use gs_rust_cache::Cache;
//! use std::any::Any;
//! use std::time::Duration;
//!
//!fn miss_handler(key: &i32, data: &mut i32, adhoc_code: &mut u8, _: &[&dyn Any]) -> bool {
//!    // Your Code Here
//!    *data = 123;
//!    *adhoc_code = 200;
//!    true
//! }
//! 
//! fn main() {
//!     let mut cache = Cache::new(
//!         3,
//!         miss_handler,
//!         Duration::from_millis(200),          
//!         Duration::from_millis(100),          
//!     );
//! 
//!     let key =  456;
//!     let value = cache.retrieve_or_compute(&key); // first one is calculated
//!     let value_1 = cache.retrieve_or_compute(&key); // afterwards it is retrieved
//! 
//!     assert_eq!(value, value_1);    
//! }
//! ```

use lru::{LruCache, DefaultHasher};
use std::hash::Hash;
use std::num::NonZeroUsize;
use std::ops::DerefMut;
use std::time::{Duration, Instant};
use std::sync::{Arc, Condvar, Mutex};
use std::any::Any;

#[derive(Debug, PartialEq, Clone, Copy)]
enum EntryStatus {
    AVAILABLE,
    CALCULATING,
    READY,
    FAILED,
}

#[derive(Debug, Clone)]
struct Entry<D> {
    data: D,
    adhoc_code: u8,
    expiration: Instant,
    status: EntryStatus,
    cond_var: Arc<Condvar>
}

impl<D: PartialEq> PartialEq for Entry<D> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data &&
        self.adhoc_code == other.adhoc_code &&
        self.expiration == other.expiration &&
        self.status == other.status
    }
}


impl<D: Default> Entry<D> {

    fn default() -> Self {
        Entry {
            data: Default::default(),
            expiration: Instant::now(),
            adhoc_code: 0,
            status: EntryStatus::AVAILABLE,
            cond_var: Arc::new(Condvar::new())
        }
    }


    fn new(data: D, expiration: Instant, adhoc_code: u8) -> Self {
        Entry {
            data,
            expiration,
            adhoc_code,
            status: EntryStatus::AVAILABLE,
            cond_var: Arc::new(Condvar::new())
        }
    }

    fn is_valid(&self) -> bool {
        self.expiration > Instant::now()
    }

}

pub type MissHandler<K, D> = fn(&K, &mut D, &mut u8, &[&dyn Any]) -> bool;

pub struct Cache<K, D> {
    lru_cache: Arc<Mutex<LruCache<K, Arc<Mutex<Entry<D>>>>>>,
    miss_handler: MissHandler<K, D>,
    positive_ttl: Duration, // seconds
    negative_ttl: Duration, // seconds
}

impl<K: Eq + Hash + Clone, D: Default + Clone> Cache<K, D> {
    pub fn new(
        size: usize,
        miss_handler: MissHandler<K, D>,
        positive_ttl: Duration,
        negative_ttl: Duration,
    ) -> Self {
        let hash_builder = DefaultHasher::default();
        Cache {
            lru_cache: Arc::new(Mutex::new(LruCache::with_hasher(
                NonZeroUsize::new(size).unwrap(),
                hash_builder,
            ))),
            miss_handler,
            positive_ttl,
            negative_ttl,
        }
    }

    pub fn insert(&self, key: &K, data: D) {
        let expiration = Instant::now() + self.positive_ttl;
        let entry = Entry::new(data, expiration, 0);
        let entry_arc = Arc::new(Mutex::new(entry));
        self.lru_cache.lock().unwrap().put(key.clone(), entry_arc);     
    }

    pub fn get(&self, key: &K) -> Option<D> {
        if let Some(entry_arc) = self.get_entry(&key) {
            let entry = entry_arc.lock().unwrap();
            return Some(entry.data.clone());
        }
        None
    }

    fn get_entry(&self, key: &K) -> Option<Arc<Mutex<Entry<D>>>> {
        // lock the cache
        let mut cache = self.lru_cache.lock().unwrap();
        // check if the entry exists and is valid
        if let Some(entry_arc) = cache.get(key) {
            let entry = entry_arc.lock().unwrap();
            if entry.is_valid() {
                return Some(Arc::clone(&entry_arc));
            }
        }
        // if the entry is not valid or does not exist, remove it
        cache.pop(key);
        None
    }

    pub fn len(&self) -> usize {
        self.lru_cache.lock().unwrap().len()
    }

    fn handle_hit(&self, key: &K) -> Option<(D, u8)> {
        // check if the the entry exists and is valid
        if let Some(entry_arc) = self.get_entry(key) {
            let entry_arc_clone = Arc::clone(&entry_arc);
            let entry = entry_arc.lock().unwrap();
            match entry.status {
                EntryStatus::AVAILABLE => {
                    // should not happen
                    eprintln!("Error: entry should not be available at this point");
                    return None;
                }
                EntryStatus::CALCULATING => {
                    println!("CALCULATING");
                    match entry.cond_var.wait_while(
                        entry_arc_clone.lock().unwrap(), 
                        |entry: &mut Entry<D>| entry.status == EntryStatus::CALCULATING)
                        {
                            Ok(_) => {}
                            Err(e) => {
                                eprintln!("Error while waiting: {:?}", e);
                                return None;
                            }
                        }
                }
                _ => {}
            }
            return Some((entry.data.clone(), entry.adhoc_code));
        }
        return None;
    }

    pub fn retrieve_or_compute(&self, key: &K) -> Option<(D, u8)> {
        self.retrieve_or_compute_with_params(key, &[])
    }

    pub fn retrieve_or_compute_with_params(&self, key: &K, params: &[&dyn Any]) -> Option<(D, u8)> {
        let miss_handler = self.miss_handler;
        let positive_ttl = self.positive_ttl;
        let negative_ttl = self.negative_ttl;

        if let Some((data, adhoc_code)) = self.handle_hit(&key) {
            return Some((data, adhoc_code));
        }

        // Miss
        let entry_arc = {
            let mut locked_cache = self.lru_cache.lock().unwrap();
            let entry_arc = locked_cache.get_or_insert_mut(key.clone(), || Arc::new(Mutex::new(Entry::default())));
            Arc::clone(&entry_arc)
        };

        let mut locked_entry = entry_arc.lock().unwrap();
        let entry_arc_clone = Arc::clone(&entry_arc);
        let locked_entry = locked_entry.deref_mut();

        match locked_entry.status {
            EntryStatus::AVAILABLE => {
                {
                    locked_entry.status = EntryStatus::CALCULATING;
                    if miss_handler(&key, &mut locked_entry.data, &mut locked_entry.adhoc_code, params) {
                        locked_entry.expiration = Instant::now() + positive_ttl;
                        locked_entry.status = EntryStatus::READY;
                    } else {
                        locked_entry.expiration = Instant::now() + negative_ttl;
                        locked_entry.status = EntryStatus::FAILED;
                    }
                }
                locked_entry.cond_var.notify_all();
            }
            EntryStatus::CALCULATING => {
                println!("CALCULATING");
                match locked_entry.cond_var.wait_while(
                    entry_arc_clone.lock().unwrap(), 
                    |entry: &mut Entry<D>| entry.status == EntryStatus::CALCULATING)
                    {
                        Ok(_) => {}
                        Err(e) => {
                            eprintln!("Error while waiting: {:?}", e);
                            return None;
                        }
                    }
            }
            EntryStatus::READY | EntryStatus::FAILED => {}
        }
        
        
        Some((locked_entry.data.clone(), locked_entry.adhoc_code))
    }
}

// ===============================================================
// =============================TESTS=============================
// ===============================================================

#[cfg(test)]
mod tests {

    use std::thread;

    use super::*;
    use rstest::*;

    #[fixture]
    fn simple_cache() -> Cache<i32, i32> {
        fn miss_handler(key: &i32, data: &mut i32, adhoc_code: &mut u8, _: &[&dyn Any]) -> bool {
            // FAIL if key is -1
            if *key == -1 {
                return false
            }
            *data = key * 2;
            *adhoc_code += 1; // should always be 1
            true
        }
        Cache::new(
            3,
            miss_handler,
            Duration::from_millis(200),          
            Duration::from_millis(100),          
        )
    }

    #[rstest]
    fn insert_value(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key = 1;
        let value = 2;

        // Act
        simple_cache.insert(&key, value);

        // Assert
        assert_eq!(simple_cache.len(), 1);
    }

    #[rstest]
    fn insert_same_key(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key = 1;
        let value = 2;

        // Act
        simple_cache.insert(&key, value);
        simple_cache.insert(&key, value);

        // Assert
        assert_eq!(simple_cache.len(), 1);
    }

    #[rstest]
    fn get_value(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key = 1;
        let value = 2;

        // Act
        simple_cache.insert(&key, value);

        // Assert
        assert_eq!(simple_cache.get(&key), Some(value));
    }

    #[rstest]
    fn get_value_not_found(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key = 1;

        // Assert
        assert_eq!(simple_cache.get(&key), None);
    }

    #[rstest]
    fn insert_max_capacity(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key1 = 1;
        let key2 = 2;
        let key3 = 3;
        let key4 = 4;
        let value = 2;

        // Act
        simple_cache.insert(&key1, value);
        simple_cache.insert(&key2, value);
        simple_cache.insert(&key3, value);
        simple_cache.insert(&key4, value);

        // Assert
        assert_eq!(simple_cache.len(), 3);
        assert_eq!(simple_cache.get(&key1), None); // lru is removed
    }

    #[rstest]
    fn get_lru_change(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key1 = 1;
        let key2 = 2;
        let key3 = 3;
        let key4 = 4;
        let value = 2;

        // Act
        simple_cache.insert(&key1, value);
        simple_cache.insert(&key2, value);
        simple_cache.get(&key1); // key2 is now the lru
        simple_cache.insert(&key3, value);
        simple_cache.insert(&key4, value);

        // Assert
        assert_eq!(simple_cache.len(), 3);
        assert_eq!(simple_cache.get(&key2), None); // lru is removed
    }

    #[rstest]
    fn ttl_expired(simple_cache: Cache<i32, i32>) {
        // Arrange
        let key = 1;
        let value = 2;

        // Act
        simple_cache.insert(&key, value);
        std::thread::sleep(std::time::Duration::from_millis(250));

        // Assert
        assert_eq!(simple_cache.get(&key), None);
    }

    #[rstest]
    fn retrieve_or_compute_not_in_cache(simple_cache: Cache<i32, i32>){
        // Arrange
        let key = 1;

        // Act
        let (data, adhoc_code) = simple_cache.retrieve_or_compute(&key).unwrap();

        // Assert
        assert_eq!(data, 2);
        assert_eq!(adhoc_code, 1);
        assert_eq!(simple_cache.len(), 1);
    }

    #[rstest]
    fn retrieve_or_compute_already_in_cache(simple_cache: Cache<i32, i32>){
        // Arrange
        let key = 1;

        // Act
        simple_cache.retrieve_or_compute(&key);
        simple_cache.retrieve_or_compute(&key);
        simple_cache.retrieve_or_compute(&key);
        simple_cache.retrieve_or_compute(&key);
        let (data, adhoc_code) = simple_cache.retrieve_or_compute(&key).unwrap();

        // Assert
        assert_eq!(data, 2);
        assert_eq!(adhoc_code, 1);
        assert_eq!(simple_cache.len(), 1);
    }

    #[rstest]
    fn retrieve_or_compute_ttl_expired(simple_cache: Cache<i32, i32>){
        // Arrange
        let key = 1;
        // Act
        simple_cache.retrieve_or_compute(&key);
        let entry_1 = simple_cache.lru_cache.lock().unwrap().peek(&key).unwrap().lock().unwrap().clone();
        std::thread::sleep(std::time::Duration::from_millis(100));
        simple_cache.retrieve_or_compute(&key);
        let entry_2 = simple_cache.lru_cache.lock().unwrap().peek(&key).unwrap().lock().unwrap().clone();
        std::thread::sleep(std::time::Duration::from_millis(150));
        simple_cache.retrieve_or_compute(&key);
        let entry_3 = simple_cache.lru_cache.lock().unwrap().peek(&key).unwrap().lock().unwrap().clone();
        
        // Assert
        assert_eq!(entry_1.status, EntryStatus::READY);
        assert_eq!(entry_1, entry_2); // not expired
        assert_ne!(entry_1, entry_3); // expired 
    }

    #[rstest]
    fn retrieve_or_compute_negative_ttl(simple_cache: Cache<i32, i32>){
        // Arrange
        let key = -1;

        // Act
        simple_cache.retrieve_or_compute(&key);
        let entry_1 = simple_cache.lru_cache.lock().unwrap().peek(&key).unwrap().lock().unwrap().clone();
        std::thread::sleep(std::time::Duration::from_millis(105));
        simple_cache.retrieve_or_compute(&key);
        let entry_2 = simple_cache.lru_cache.lock().unwrap().peek(&key).unwrap().lock().unwrap().clone();
        
        // Assert
        assert_ne!(entry_1, entry_2); // expired because negative ttl is lower
        assert_eq!(entry_1.status, EntryStatus::FAILED);
    }

    #[fixture]
    fn simple_cache_with_params () -> Cache<i32, i32> {
        fn miss_handler(key: &i32, data: &mut i32, adhoc_code: &mut u8, params: &[&dyn Any]) -> bool {
            
            // FAIL if key is -1
            if *key == -1 {
                return false
            }
            *data = key * 2;
            for param in params {
                if let Some(param) = param.downcast_ref::<i32>() {
                    *data += param;
                }
            }
            if params[0].downcast_ref::<&str>().is_some() {
                *adhoc_code += 1;
            }
            *adhoc_code += 1; // should always be 1
            true
        }
        Cache::new(
            3,
            miss_handler,
            Duration::from_millis(200),          
            Duration::from_millis(100),          
        )
    }

    #[rstest]
    fn retrieve_or_compute_with_params(simple_cache_with_params: Cache<i32, i32>){
        // Arrange
        let key = 1;
        let param = 3;

        // Act
        let (data, adhoc_code) = simple_cache_with_params.retrieve_or_compute_with_params(&key, &[&param]).unwrap();

        // Assert
        assert_eq!(data, 5);
        assert_eq!(adhoc_code, 1);
        assert_eq!(simple_cache_with_params.len(), 1);
    }

    #[rstest]
    fn retrieve_or_compute_with_multiple_params(simple_cache_with_params: Cache<i32, i32>){
        // Arrange
        let key = 1;
        let param1 = 3;
        let param2 = 4;

        // Act
        let (data, adhoc_code) = simple_cache_with_params.retrieve_or_compute_with_params(&key, &[&param1, &param2]).unwrap();

        // Assert
        assert_eq!(data, 9);
        assert_eq!(adhoc_code, 1);
        assert_eq!(simple_cache_with_params.len(), 1);
    }
    
    #[rstest]
    fn retrieve_or_compute_with_multiple_params_different_types(simple_cache_with_params: Cache<i32, i32>){
        // Arrange
        let key = 1;
        let param1 = "hola";
        let param2 = 3;
        let param3 = 4;

        // Act
        let (data, adhoc_code) = simple_cache_with_params.retrieve_or_compute_with_params(&key, &[&param1, &param2, &param3]).unwrap();

        // Assert
        assert_eq!(data, 9);
        assert_eq!(adhoc_code, 2);
        assert_eq!(simple_cache_with_params.len(), 1);
    }

    #[fixture]
    fn time_consuming_mh() -> Cache<i32, i32> {
        fn miss_handler(key: &i32, data: &mut i32, adhoc_code: &mut u8, _: &[&dyn Any]) -> bool {

            std::thread::sleep(std::time::Duration::from_millis(500));

            *data = key * 2;
            *adhoc_code += 1; // should always be 1
            true
        }
        Cache::new(
            200,
            miss_handler,
            Duration::from_secs(60),          
            Duration::from_secs(60),          
        )
    }

    #[rstest]
    fn test_thread_safe_cache_same_key(time_consuming_mh: Cache<i32, i32>) {        
        // Arrange            
        let cache = Arc::new(time_consuming_mh);
        let n_threads: i32 = 200;
        let start = Instant::now();

        // Act
        let handles: Vec<_> = (0..n_threads).map(|i| {
            let cache_clone = Arc::clone(&cache);
            thread::Builder::new().name(format!("Thread {}", i)).spawn(move || {
            let key = 456;
            cache_clone.retrieve_or_compute(&key)
            })
        }).collect();

        // Assert
        let results = handles.into_iter().map(|handle| handle.unwrap().join());
        for res in results {
            // assert res is ok
            assert!(res.is_ok());
            if let Some((data, adhoc_code)) = res.unwrap() {
                assert_eq!(data, 456 * 2);
                assert_eq!(adhoc_code, 1);
            }
        }        
        let duration = start.elapsed();
        assert!(cache.len() == 1);
        assert!(duration.as_secs() < 1);
        
    }

    #[rstest]
    fn test_thread_safe_cache_different_keys(time_consuming_mh: Cache<i32, i32>) {
        // Arrange
        let cache = Arc::new(time_consuming_mh);
        let n_threads = 20;
        let start = Instant::now();

        // Act
        let handles: Vec<_> = (0..n_threads).map(|i| {
            let cache_clone = Arc::clone(&cache);
            thread::spawn(move || {
                let key = 456 + i;
                cache_clone.retrieve_or_compute(&key);
            })
        }).collect();

        for handle in handles {
            let res = handle.join();
            // assert res is ok
            assert!(res.is_ok());
            res.unwrap();
        }

        // Assert        
        for i in 0..n_threads {
            let key = 456 + i;
            let data = cache.get(&key);
            assert_eq!(data, Some(key * 2));
        }
        assert!(cache.len() == n_threads.try_into().unwrap());
        let duration = start.elapsed();
        assert!(duration.as_secs() < 1);
    }

    #[rstest]
    fn test_thread_safe_cache_maximum_capacity(time_consuming_mh: Cache<i32, i32>) {
        // Arrange
        let cache = Arc::new(time_consuming_mh);
        let n_threads = 202;
        let start = Instant::now();

        // Act
        let handles: Vec<_> = (0..n_threads).map(|i| {
            let cache_clone = Arc::clone(&cache);
            thread::spawn(move || {
                let key = 456 + i;
                cache_clone.retrieve_or_compute(&key);
            })
        }).collect();

        for handle in handles {
            let res = handle.join();
            // assert res is ok
            assert!(res.is_ok());
            res.unwrap();
        }

        // Assert
        let mut not_in_cache_count = 0;      
        for i in 0..n_threads {
            let key = 456 + i;
            let data = cache.get(&key);
            if data == None {
                not_in_cache_count += 1;
            } else {
                let key = 456 + i;
                let data = cache.get(&key);
                assert_eq!(data, Some(key * 2));
            }
        }
        let duration = start.elapsed();
        assert!(cache.len() == 200);
        assert!(duration.as_secs() < 1);
        assert_eq!(not_in_cache_count, 2);
    }

    #[rstest]
    fn test_thread_safe_heavy_threads(time_consuming_mh: Cache<i32, i32>) {
        let cache = Arc::new(time_consuming_mh);
        for _ in 0..50 {
            // Arrange
            let n_keys = 5;
            let entries_per_key = 20;
            let results = vec![(0,0); n_keys * entries_per_key];
            let results_arc = Arc::new(Mutex::new(results));
            let mut threads = Vec::<thread::JoinHandle<_>>::with_capacity(n_keys * entries_per_key);

            // Act
            for i in 0..n_keys {
                for j in 0..entries_per_key {
                    let cache_clone = Arc::clone(&cache);
                    let results_clone = Arc::clone(&results_arc);
                    threads.push(thread::spawn(move || {
                        let key = (i + 1) as i32;
                        let (data, adhoc_code) = cache_clone.retrieve_or_compute(&key).unwrap();
                        let mut results = results_clone.lock().unwrap();
                        results[i*entries_per_key+j] = (data, adhoc_code);
                    }));
                }
            }
            for handle in threads {
                let res = handle.join();
                // assert res is ok
                assert!(res.is_ok());
                res.unwrap();
            }

            // Assert
            for i in (0..n_keys * entries_per_key).step_by(entries_per_key) {
                let results = results_arc.lock().unwrap();
                let res_i = results[i];
                for j in 1..entries_per_key {
                    let res_j = results[i+j];
                    assert_eq!(res_i, res_j);
                }
            }
            assert!(cache.len() == n_keys);
        }
    }

    #[derive(Debug, PartialEq, Eq, Clone, Hash, Copy, Default)]
    struct SimpleStruct {
        value: i32,
    }
    #[derive(Debug, PartialEq, Eq, Clone, Hash, Default)]
    struct ComplexKey {
        id: i32,
        name: String,
        nested: SimpleStruct,
        array: Vec<i32>,

    }

  #[derive(Debug, PartialEq, Eq, Clone, Hash, Default)]
    struct ComplexData {
        value: i32,
        description: String,
        nested: SimpleStruct,
        array: Vec<i32>,
    }

    #[fixture]
    fn complex_key_and_data_cache() -> Cache<ComplexKey, ComplexData> {
        fn miss_handler(key: &ComplexKey, data: &mut ComplexData, adhoc_code: &mut u8, _: &[&dyn Any]) -> bool {
            // wait 500 ms
            std::thread::sleep(std::time::Duration::from_millis(500));
            // FAIL if key.id is -1
            if key.id == -1 {
                return false
            }
            data.value = key.id * 2;
            data.description = key.name.clone();
            data.nested = key.nested.clone();
            data.array = key.array.clone();
            *adhoc_code += 1; // should always be 1
            true
        }
        Cache::new(
            200,
            miss_handler,
            Duration::from_secs(1),          
            Duration::from_secs(1),          
        )
    }

    #[rstest]
    fn complex_key_and_data_cache_insert(complex_key_and_data_cache: Cache<ComplexKey, ComplexData>) {
        // Arrange
        let key = ComplexKey {
            id: 1,
            name: "name".to_string(),
            nested: SimpleStruct { value: 1 },
            array: vec![1, 2, 3],
        };
        let data = ComplexData {
            value: 2,
            description: "name".to_string(),
            nested: SimpleStruct { value: 1 },
            array: vec![1, 2, 3],
        };

        // Act
        complex_key_and_data_cache.insert(&key, data);

        // Assert
        assert_eq!(complex_key_and_data_cache.len(), 1);
    }

    #[rstest]
    fn complex_key_data_retrieve_or_compute(complex_key_and_data_cache: Cache<ComplexKey, ComplexData>) {
        // Arrange
        let key = ComplexKey {
            id: 1,
            name: "name".to_string(),
            nested: SimpleStruct { value: 1 },
            array: vec![1, 2, 3],
        };

        // Act
        let (data, adhoc_code) = complex_key_and_data_cache.retrieve_or_compute(&key).unwrap();

        // Assert
        assert_eq!(data.value, 2);
        assert_eq!(data.description, "name");
        assert_eq!(data.nested, SimpleStruct { value: 1 });
        assert_eq!(data.array, vec![1, 2, 3]);
        assert_eq!(adhoc_code, 1);
        assert_eq!(complex_key_and_data_cache.len(), 1);    
    }

    #[rstest]
    fn complex_key_data_retrieve_or_compute_change_key(complex_key_and_data_cache: Cache<ComplexKey, ComplexData>) {
        // Arrange
        let key = ComplexKey {
            id: 1,
            name: "name".to_string(),
            nested: SimpleStruct { value: 1 },
            array: vec![1, 2, 3],
        };
        let key_clone = key.clone();
        let mut key_change = key.clone();
        key_change.id = 2;

        // Act
        let (data, _) = complex_key_and_data_cache.retrieve_or_compute(&key).unwrap();
        let (data1, _) = complex_key_and_data_cache.retrieve_or_compute(&key_clone).unwrap();
        let (data2, _) = complex_key_and_data_cache.retrieve_or_compute(&key_change).unwrap();

        // Assert
        assert_eq!(data, data1);
        assert_ne!(data, data2);
        assert_eq!(complex_key_and_data_cache.len(), 2);
    }

    #[rstest]
    fn complex_key_data_thread_safe_cache_same_key(complex_key_and_data_cache: Cache<ComplexKey, ComplexData>) {
        // Arrange
        let cache = Arc::new(complex_key_and_data_cache);
        let n_threads: i32 = 200;
        let start = Instant::now();
        let key = ComplexKey {
            id: 1,
            name: "name".to_string(),
            nested: SimpleStruct { value: 1 },
            array: vec![1, 2, 3],
        };

        // Act
        let handles: Vec<_> = (0..n_threads).map(|i| {
            let cache_clone = Arc::clone(&cache);
            thread::Builder::new().name(format!("Thread {}", i)).spawn({
            let value = key.clone();
            move || {
            cache_clone.retrieve_or_compute(&value)
            }
            })
        }).collect();

        // Assert
        let results = handles.into_iter().map(|handle| handle.unwrap().join());
        for res in results {
            // assert res is ok
            assert!(res.is_ok());
            if let Some((data, adhoc_code)) = res.unwrap() {
                assert_eq!(data.value, 2);
                assert_eq!(data.description, "name");
                assert_eq!(data.nested, SimpleStruct { value: 1 });
                assert_eq!(data.array, vec![1, 2, 3]);
                assert_eq!(adhoc_code, 1);
            }
        }        
        let duration = start.elapsed();
        assert!(cache.len() == 1);
        assert!(duration.as_secs() < 1);
        
    }

    #[rstest]
    fn complex_key_data_thread_safe_cache_different_keys(complex_key_and_data_cache: Cache<ComplexKey, ComplexData>) {
        // Arrange
        let cache = Arc::new(complex_key_and_data_cache);
        let n_threads = 200;
        let start = Instant::now();

        // Act
        let handles: Vec<_> = (0..n_threads).map(|i| {
            let cache_clone = Arc::clone(&cache);
            let key: ComplexKey = ComplexKey {
                id: 1 + i,
                name: "name".to_string(),
                nested: SimpleStruct { value: 1 },
                array: vec![1, 2, 3],
            };
            thread::spawn({ move || {
            cache_clone.retrieve_or_compute(&key)
            }
            })
        }).collect();

        for handle in handles {
            let res = handle.join();
            // assert res is ok
            assert!(res.is_ok());
            res.unwrap();
        }

        // Assert        
        for i in 0..n_threads {
            let key = ComplexKey {
                id: 1 + i,
                name: "name".to_string(),
                nested: SimpleStruct { value: 1 },
                array: vec![1, 2, 3],
            };
            let data = cache.get(&key);

            assert_eq!(data, Some(ComplexData {
                value: (1 + i) * 2,
                description: "name".to_string(),
                nested: SimpleStruct { value: 1 },
                array: vec![1, 2, 3],
            }));
        }
        assert!(cache.len() == n_threads.try_into().unwrap());
        let duration = start.elapsed();
        assert!(duration.as_secs() < 1);
    }


}