-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.c
86 lines (60 loc) · 1.71 KB
/
lru.c
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
#include "lru.h"
struct lru_list *lru_init(int max_sz) {
struct lru_list *list = (struct lru_list *)malloc(sizeof(struct lru_list));
list->size = 0;
list->head = (struct lru_node *)malloc(sizeof(struct lru_node));
list->head->value = NULL;
list->head->next = list->head;
list->head->prev = list->head;
return list;
}
int lru_free(struct lru_list *list) {
while (list->size > 0) {
lru_pop(list);
}
free(list->head);
free(list);
return 0;
}
struct lru_node *lru_push(struct lru_list *list, void *value) {
struct lru_node *node = (struct lru_node *)malloc(sizeof(struct lru_node));
node->value = value;
node->next = list->head->next;
node->prev = list->head;
node->next->prev = node;
node->prev->next = node; // list->head->next = node
++list->size;
return node;
}
void *lru_pop(struct lru_list *list) {
struct lru_node *node;
void *value;
if (list->size == 0) { // list->head->next == list->head
return NULL;
}
node = list->head->prev;
node->prev->next = node->next;
node->next->prev = node->prev; // list->head->next = node->prev
value = node->value;
free(node);
--list->size;
return value;
}
int lru_update(struct lru_list *list, struct lru_node *pos) {
pos->prev->next = pos->next;
pos->next->prev = pos->prev;
pos->next = list->head->next;
pos->prev = list->head;
pos->next->prev = pos;
pos->prev->next = pos;
return 0;
}
void *lru_front(struct lru_list *list) {
return list->head->next->value;
}
void *lru_back(struct lru_list *list) {
return list->head->prev->value;
}
void *lru_get_victim(struct lru_list *list) {
return lru_back(list);
}