-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathcache.rs
More file actions
321 lines (286 loc) · 8.82 KB
/
cache.rs
File metadata and controls
321 lines (286 loc) · 8.82 KB
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
// Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
use std::{collections::HashMap, mem, ptr::NonNull};
use bytes::Bytes;
use crate::pipe_log::FileBlockHandle;
struct CacheEntry {
key: FileBlockHandle,
data: Bytes,
}
struct Node {
prev: NonNull<Node>,
next: NonNull<Node>,
entry: CacheEntry,
#[cfg(test)]
_leak_check: self::tests::LeakCheck,
}
pub struct LruCache {
cache: HashMap<FileBlockHandle, NonNull<Node>>,
cap: usize,
free: usize,
head: *mut Node,
tail: *mut Node,
#[cfg(test)]
leak_check: self::tests::LeakCheck,
}
#[inline]
fn need_size(payload: &[u8]) -> usize {
mem::size_of::<Node>() + payload.len()
}
#[inline]
unsafe fn promote(mut node: NonNull<Node>, head: &mut *mut Node, tail: &mut *mut Node) {
if node.as_ptr() == *tail {
return;
}
let mut prev = unsafe { node.as_ref().prev };
let mut next = unsafe { node.as_ref().next };
if node.as_ptr() == *head {
*head = next.as_ptr();
next.as_mut().prev = NonNull::dangling();
} else {
prev.as_mut().next = next;
next.as_mut().prev = prev;
}
(**tail).next = node;
node.as_mut().prev = NonNull::new_unchecked(*tail);
node.as_mut().next = NonNull::dangling();
*tail = node.as_ptr();
}
impl LruCache {
#[inline]
pub fn with_capacity(cap: usize) -> Self {
Self {
cache: HashMap::default(),
cap,
free: cap,
head: std::ptr::null_mut(),
tail: std::ptr::null_mut(),
#[cfg(test)]
leak_check: self::tests::LeakCheck::default(),
}
}
#[inline]
pub fn insert(&mut self, key: FileBlockHandle, data: Bytes) -> Option<Bytes> {
match self.cache.get_mut(&key) {
None => (),
Some(node) => {
unsafe {
// Technically they should be exact the same. Using the new version
// to avoid potential bugs.
assert_eq!(data.len(), node.as_ref().entry.data.len());
node.as_mut().entry.data = data.clone();
promote(*node, &mut self.head, &mut self.tail);
return Some(data);
}
}
}
let need_size = need_size(&data);
if need_size > self.cap {
return Some(data);
}
while self.free < need_size && self.remove_head() {}
let node = Box::new(Node {
prev: NonNull::dangling(),
next: NonNull::dangling(),
entry: CacheEntry { key, data },
#[cfg(test)]
_leak_check: self.leak_check.clone(),
});
let node = Box::into_raw(node);
if self.head.is_null() {
self.head = node;
self.tail = node;
} else {
unsafe {
(*self.tail).next = NonNull::new_unchecked(node);
(*node).prev = NonNull::new_unchecked(self.tail);
self.tail = node;
}
}
self.free -= need_size;
self.cache
.insert(key, unsafe { NonNull::new_unchecked(node) });
None
}
#[inline]
pub fn get(&mut self, key: &FileBlockHandle) -> Option<Bytes> {
let node = self.cache.get(key)?;
unsafe {
promote(*node, &mut self.head, &mut self.tail);
Some(node.as_ref().entry.data.clone())
}
}
#[inline]
fn remove_head(&mut self) -> bool {
if self.head.is_null() {
return false;
}
let mut head = unsafe { Box::from_raw(self.head) };
if self.head != self.tail {
self.head = head.next.as_ptr();
head.prev = NonNull::dangling();
} else {
self.head = std::ptr::null_mut();
self.tail = std::ptr::null_mut();
}
self.free += need_size(&head.entry.data);
self.cache.remove(&head.entry.key);
true
}
#[inline]
pub fn resize(&mut self, new_cap: usize) {
while (self.cap - self.free) > new_cap {
self.remove_head();
}
self.free = new_cap - (self.cap - self.free);
self.cap = new_cap;
}
#[inline]
pub fn clear(&mut self) {
for (_, node) in self.cache.drain() {
unsafe {
drop(Box::from_raw(node.as_ptr()));
}
}
self.head = std::ptr::null_mut();
self.tail = std::ptr::null_mut();
self.free = self.cap;
}
}
impl Drop for LruCache {
fn drop(&mut self) {
self.clear();
}
}
unsafe impl Sync for LruCache {}
unsafe impl Send for LruCache {}
#[cfg(test)]
mod tests {
use std::sync::{
atomic::{AtomicIsize, Ordering},
Arc,
};
use crate::internals::LogQueue;
use super::*;
pub struct LeakCheck {
cnt: Arc<AtomicIsize>,
}
impl LeakCheck {
pub fn clone(&self) -> Self {
self.cnt.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Self {
cnt: self.cnt.clone(),
}
}
}
impl Default for LeakCheck {
fn default() -> Self {
Self {
cnt: Arc::new(AtomicIsize::new(1)),
}
}
}
impl Drop for LeakCheck {
fn drop(&mut self) {
self.cnt.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
#[test]
fn test_basic_lru() {
let mut cache = LruCache::with_capacity(1024);
let lc = cache.leak_check.clone();
let mut key = FileBlockHandle::dummy(LogQueue::Append);
for offset in 0..100 {
key.offset = offset;
cache.insert(key, vec![offset as u8; 10].into());
}
for offset in 0..100 {
key.offset = offset;
cache.insert(key, vec![offset as u8; 10].into());
}
let entry_len = need_size(&[0; 10]);
let entries_fit = (1024 / entry_len) as u64;
assert_eq!(cache.cap, 1024);
assert_eq!(cache.free, 1024 % entry_len);
for offset in 0..(100 - entries_fit) {
key.offset = offset;
assert_eq!(cache.get(&key).as_deref(), None, "{offset}");
}
for offset in (100 - entries_fit)..100 {
key.offset = offset;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8]),
"{offset}"
);
}
let offset = 100 - entries_fit;
key.offset = offset;
// Get will promote the entry and it will be the last to be removed.
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8]),
"{offset}"
);
for i in 1..entries_fit {
key.offset = 200 + i;
cache.insert(key, vec![key.offset as u8; 10].into());
key.offset = offset + i;
assert_eq!(cache.get(&key).as_deref(), None, "{i}");
}
key.offset = offset;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8]),
"{offset}"
);
cache.resize(2048);
assert_eq!(cache.cap, 2048);
assert_eq!(cache.free, 2048 - (entries_fit as usize * entry_len));
key.offset = 201;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[key.offset as u8; 10] as &[u8])
);
key.offset = offset;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8])
);
cache.resize(entry_len);
assert_eq!(cache.cap, entry_len);
assert_eq!(cache.free, 0);
key.offset = 201;
assert_eq!(cache.get(&key).as_deref(), None);
key.offset = offset;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8])
);
cache.resize(entry_len - 1);
assert_eq!(cache.cap, entry_len - 1);
assert_eq!(cache.free, entry_len - 1);
key.offset = offset;
assert_eq!(cache.get(&key).as_deref(), None);
cache.resize(1024);
cache.clear();
for offset in 0..100 {
key.offset = offset;
cache.insert(key, vec![offset as u8; 10].into());
}
for offset in 0..(100 - entries_fit) {
key.offset = offset;
assert_eq!(cache.get(&key).as_deref(), None, "{offset}");
}
for offset in (100 - entries_fit)..100 {
key.offset = offset;
assert_eq!(
cache.get(&key).as_deref(),
Some(&[offset as u8; 10] as &[u8]),
"{offset}"
);
}
drop(cache);
// If there is leak or double free, the count will unlikely to be 1.
assert_eq!(lc.cnt.load(Ordering::Relaxed), 1);
}
}