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
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "logging")]
use std::fmt::Debug;
use std::marker::PhantomPinned;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::hash::{Hash, Hasher};
use std::borrow::Borrow;

use intrusive_collections::{intrusive_adapter, LinkedListLink, UnsafeRef};
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};

use crate::{bucket::Bucket, Bucketize};

/// Collects the traits a Key must implement, any user defined Key type must implement this
/// trait and any traits it derives from.
/// The 'Debug' trait is only required when the feature 'logging' is enabled.
#[cfg(not(feature = "logging"))]
pub trait KeyTraits: Eq + Clone + Bucketize + 'static {}
#[cfg(feature = "logging")]
pub trait KeyTraits: Eq + Clone + Bucketize + Debug + 'static {}

/// User data is stored behind RwLocks in an entry. Furthermore some management information
/// like the LRU list node are stored here. Entries have stable addresses and can't be moved
/// in memory.
pub(crate) struct Entry<K, V> {
    pub(crate) key:      K,
    // The Option is only used for delaying the construction with write lock held.
    pub(crate) value:    RwLock<Option<V>>,
    pub(crate) lru_link: LinkedListLink, // protected by lru_list mutex
    pub(crate) expire:   AtomicBool,
    _pin:                PhantomPinned,
}

intrusive_adapter!(pub(crate) EntryAdapter<K, V> = UnsafeRef<Entry<K, V>>: Entry<K, V> { lru_link: LinkedListLink });

impl<K: KeyTraits, V> Entry<K, V> {
    pub(crate) fn new(key: K) -> Self {
        Entry {
            key,
            value: RwLock::new(None),
            lru_link: LinkedListLink::new(),
            expire: AtomicBool::new(false),
            _pin: PhantomPinned,
        }
    }
}

// Hashes only over the key part.
impl<K: KeyTraits, V> Hash for Entry<K, V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.key.hash(state);
    }
}

// Compares only the key.
impl<K: PartialEq, V> PartialEq for Entry<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl<K: PartialEq, V> Eq for Entry<K, V> {}

// We need this to be able to lookup a Key in a HashSet containing pinboxed entries.
impl<K, V> Borrow<K> for Pin<Box<Entry<K, V>>>
where
    K: KeyTraits,
{
    fn borrow(&self) -> &K {
        &self.key
    }
}

/// Guard for the read lock. Puts unused entries into the LRU list.
pub struct EntryReadGuard<'a, K, V, const N: usize>
where
    K: KeyTraits,
{
    pub(crate) bucket: &'a Bucket<K, V>,
    pub(crate) entry:  &'a Entry<K, V>,
    pub(crate) guard:  Option<RwLockReadGuard<'a, Option<V>>>,
}

impl<K, V, const N: usize> EntryReadGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    /// Mark the entry for expiration. When dropped it will be put in front of the LRU list
    /// and by that evicted soon. Use with care, when many entries become pushed to the front,
    /// they eventually bubble up again.
    fn expire(&mut self) {
        self.entry.expire.store(true, Ordering::Relaxed);
    }
}

impl<K, V, const N: usize> Drop for EntryReadGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    fn drop(&mut self) {
        let lru_lock = self.bucket.lock_lru();
        unsafe {
            debug_assert!(self.guard.is_some());
            drop(self.guard.take().unwrap_unchecked());
        }
        self.bucket.unuse_entry(lru_lock, self.entry);
    }
}

impl<K, V, const N: usize> Deref for EntryReadGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        unsafe {
            debug_assert!(self.guard.is_some());
            let guard = self.guard.as_ref().unwrap_unchecked();

            debug_assert!(guard.is_some());
            guard.as_ref().unwrap_unchecked()
        }
    }
}

/// Guard for the write lock. Puts unused entries into the LRU list.
pub struct EntryWriteGuard<'a, K, V, const N: usize>
where
    K: KeyTraits,
{
    pub(crate) bucket: &'a Bucket<K, V>,
    pub(crate) entry:  &'a Entry<K, V>,
    pub(crate) guard:  Option<RwLockWriteGuard<'a, Option<V>>>,
}

impl<K, V, const N: usize> EntryWriteGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    /// Mark the entry for expiration. When dropped it will be put in front of the LRU list
    /// and by that evicted soon. Use with care, when many entries become pushed to the front,
    /// they eventually bubble up again.
    fn expire(&mut self) {
        self.entry.expire.store(true, Ordering::Relaxed);
    }
}

impl<K, V, const N: usize> Drop for EntryWriteGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    fn drop(&mut self) {
        let lru_lock = self.bucket.lock_lru();
        unsafe {
            debug_assert!(self.guard.is_some());
            drop(self.guard.take().unwrap_unchecked());
        }
        self.bucket.unuse_entry(lru_lock, self.entry);
    }
}

impl<K, V, const N: usize> Deref for EntryWriteGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        unsafe {
            debug_assert!(self.guard.is_some());
            let guard = self.guard.as_ref().unwrap_unchecked();

            debug_assert!(guard.is_some());
            guard.as_ref().unwrap_unchecked()
        }
    }
}

impl<K, V, const N: usize> DerefMut for EntryWriteGuard<'_, K, V, N>
where
    K: KeyTraits,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            debug_assert!(self.guard.is_some());
            let guard = self.guard.as_mut().unwrap_unchecked();

            debug_assert!(guard.is_some());
            guard.as_mut().unwrap_unchecked()
        }
    }
}