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
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

pub mod lru;
pub mod recent_lfu;
pub mod removable_heap;

#[cfg(test)]
mod tests;

/// The cache algorithm should store a reference to the cached element in order
/// to link between cache store and internal data structure of cache algorithm.
/// Normally this should be simple type like pointer, or map key for the
/// element.
///
/// User may use a 32bit data type to reduce memory usage.
pub trait CacheIndexTrait: Copy + Send + MallocSizeOf {}

pub trait CacheAlgoDataTrait: Copy + Default + Send + MallocSizeOf {}

/// The cache storage interface that user should implement for cache algorithm
/// to update reference from cached object to its internal data structure.
///
/// The cache algorithm should normally call the interface sequentially.
pub trait CacheStoreUtil {
    type CacheAlgoData: CacheAlgoDataTrait;
    type ElementIndex: CacheIndexTrait;

    fn get(&self, element_index: Self::ElementIndex) -> Self::CacheAlgoData;

    fn get_most_recently_accessed(
        &self, element_index: Self::ElementIndex,
    ) -> Self::CacheAlgoData {
        self.get(element_index)
    }

    fn set(
        &mut self, element_index: Self::ElementIndex,
        algo_data: &Self::CacheAlgoData,
    );

    /// In some cases only temporary space in cache store is available for most
    /// recently accessed (new) element. This method offers possibility for this
    /// special case. Cache algorithm should always call this method to set
    /// for the most recently accessed element.
    ///
    /// Without an overriding implementation, calls to this method is forwarded
    /// to the normal set method.
    fn set_most_recently_accessed(
        &mut self, element_index: Self::ElementIndex,
        algo_data: &Self::CacheAlgoData,
    ) {
        self.set(element_index, algo_data);
    }
}

struct CacheAlgoDataAdapter<
    CacheStoreUtilT: CacheStoreUtil,
    CacheIndexT: CacheIndexTrait,
> where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    _marker_s: PhantomData<CacheStoreUtilT>,
    _marker_i: PhantomData<CacheIndexT>,
}

impl<
        CacheStoreUtilT: CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > CacheAlgoDataAdapter<CacheStoreUtilT, CacheIndexT>
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    fn get(
        util: &CacheStoreUtilT, index: CacheIndexT,
    ) -> CacheStoreUtilT::CacheAlgoData {
        util.get(index)
    }

    /// It's impossible to abstract get_mut directly in CacheStoreUtil,
    /// therefore we have CacheAlgoDataAdapter.
    fn get_mut(
        util: &mut CacheStoreUtilT, index: CacheIndexT,
    ) -> CacheAlgoDataSetter<CacheStoreUtilT, CacheIndexT> {
        let data = Self::get(util, index).clone();
        CacheAlgoDataSetter {
            cache_store_util: util,
            element_index: index,
            algo_data: data,
        }
    }

    #[allow(unused)]
    fn get_mut_most_recently_accessed(
        util: &mut CacheStoreUtilT, index: CacheIndexT,
    ) -> CacheAlgoDataSetterMostRecentlyAccessed<CacheStoreUtilT, CacheIndexT>
    {
        let data = util.get_most_recently_accessed(index).clone();
        CacheAlgoDataSetterMostRecentlyAccessed {
            cache_store_util: util,
            element_index: index,
            algo_data: data,
        }
    }

    unsafe fn new_mut(
        util: &mut CacheStoreUtilT, index: CacheIndexT,
    ) -> CacheAlgoDataSetter<CacheStoreUtilT, CacheIndexT> {
        CacheAlgoDataSetter {
            cache_store_util: util,
            element_index: index,
            algo_data: mem::uninitialized(),
        }
    }

    unsafe fn new_mut_most_recently_accessed(
        util: &mut CacheStoreUtilT, index: CacheIndexT,
    ) -> CacheAlgoDataSetterMostRecentlyAccessed<CacheStoreUtilT, CacheIndexT>
    {
        CacheAlgoDataSetterMostRecentlyAccessed {
            cache_store_util: util,
            element_index: index,
            algo_data: mem::uninitialized(),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum CacheAccessResult<CacheIndexT> {
    Hit,
    MissInsert,
    MissReplaced {
        evicted: Vec<CacheIndexT>,
        evicted_keep_cache_algo_data: Vec<CacheIndexT>,
    },
}

pub trait CacheAlgorithm: Send {
    type CacheIndex: CacheIndexTrait;
    type CacheAlgoData: CacheAlgoDataTrait;

    /// The cache index is the identifier for content being cached. If user want
    /// to reuse the cache storage of evicted cache element, it should be
    /// done in the cache storage.
    fn access<
        CacheStoreUtilT: CacheStoreUtil<
            ElementIndex = Self::CacheIndex,
            CacheAlgoData = Self::CacheAlgoData,
        >,
    >(
        &mut self, cache_index: Self::CacheIndex,
        cache_store_util: &mut CacheStoreUtilT,
    ) -> CacheAccessResult<Self::CacheIndex>;

    /// When an element is removed because of external logic, update the cache
    /// algorithm.
    ///
    /// Note 1: do not use cache_store_util which implements special
    /// logic for most recently accessed cache index, because the case
    /// doesn't apply in deletion.
    ///
    /// Note 2: Since the cache deletion updates cache_algo_data for the element
    /// to delete, caller must delete the item after the call to this delete
    /// method has finished.
    fn delete<
        CacheStoreUtilT: CacheStoreUtil<
            ElementIndex = Self::CacheIndex,
            CacheAlgoData = Self::CacheAlgoData,
        >,
    >(
        &mut self, cache_index: Self::CacheIndex,
        cache_store_util: &mut CacheStoreUtilT,
    );

    fn log_usage(&self, prefix: &str);
}

// TODO(yz): maybe replace it with a library.
pub trait PrimitiveNum:
    Copy
    + Debug
    + Display
    + Add<Output = Self>
    + AddAssign
    + Sub<Output = Self>
    + SubAssign
    + Div<Output = Self>
    + DivAssign
    + Mul<Output = Self>
    + PartialOrd
    + PartialEq
    + MyInto<usize>
    + MyInto<isize>
    + MyFrom<i32>
    + MyFrom<usize>
    + Send
    + MallocSizeOf
{
}

pub trait MyFrom<X> {
    fn from(x: X) -> Self;
}

pub trait MyInto<X> {
    fn into(self) -> X;
}

impl MyFrom<usize> for u32 {
    fn from(x: usize) -> Self { x as Self }
}

impl MyFrom<i32> for u32 {
    fn from(x: i32) -> Self { x as Self }
}

impl MyInto<isize> for u32 {
    fn into(self) -> isize { self as isize }
}

impl MyInto<usize> for u32 {
    fn into(self) -> usize { self as usize }
}

impl PrimitiveNum for u32 {}

struct CacheAlgoDataSetter<
    'a,
    CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
    CacheIndexT: CacheIndexTrait,
> where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    algo_data: CacheStoreUtilT::CacheAlgoData,
    element_index: CacheIndexT,
    cache_store_util: &'a mut CacheStoreUtilT,
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > Drop for CacheAlgoDataSetter<'a, CacheStoreUtilT, CacheIndexT>
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    fn drop(&mut self) {
        let (util, index, data) = (
            &mut self.cache_store_util,
            &self.element_index,
            &self.algo_data,
        );
        util.set(*index, data);
    }
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > Deref for CacheAlgoDataSetter<'a, CacheStoreUtilT, CacheIndexT>
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    type Target = CacheStoreUtilT::CacheAlgoData;

    fn deref(&self) -> &Self::Target { &self.algo_data }
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > DerefMut for CacheAlgoDataSetter<'a, CacheStoreUtilT, CacheIndexT>
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.algo_data }
}

struct CacheAlgoDataSetterMostRecentlyAccessed<
    'a,
    CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
    CacheIndexT: CacheIndexTrait,
> where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    algo_data: CacheStoreUtilT::CacheAlgoData,
    element_index: CacheIndexT,
    cache_store_util: &'a mut CacheStoreUtilT,
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > Drop
    for CacheAlgoDataSetterMostRecentlyAccessed<
        'a,
        CacheStoreUtilT,
        CacheIndexT,
    >
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    fn drop(&mut self) {
        let (util, index, data) = (
            &mut self.cache_store_util,
            &self.element_index,
            &self.algo_data,
        );
        util.set_most_recently_accessed(*index, data);
    }
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > Deref
    for CacheAlgoDataSetterMostRecentlyAccessed<
        'a,
        CacheStoreUtilT,
        CacheIndexT,
    >
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    type Target = CacheStoreUtilT::CacheAlgoData;

    fn deref(&self) -> &Self::Target { &self.algo_data }
}

impl<
        'a,
        CacheStoreUtilT: 'a + CacheStoreUtil<ElementIndex = CacheIndexT>,
        CacheIndexT: CacheIndexTrait,
    > DerefMut
    for CacheAlgoDataSetterMostRecentlyAccessed<
        'a,
        CacheStoreUtilT,
        CacheIndexT,
    >
where CacheStoreUtilT::CacheAlgoData: CacheAlgoDataTrait
{
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.algo_data }
}

use malloc_size_of::MallocSizeOf;
use std::{
    fmt::{Debug, Display},
    marker::PhantomData,
    mem,
    ops::{
        Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, Sub, SubAssign,
    },
};