root / mainbox / cache.c @ ddd50354
History | View | Annotate | Download (1.53 KB)
1 | cc7646f9 | Tom Mullins | #include "cache.h" |
---|---|---|---|
2 | #include "log.h" |
||
3 | #include <stdlib.h> |
||
4 | |||
5 | struct entry_t {
|
||
6 | unsigned int key; |
||
7 | unsigned int value; |
||
8 | time_t retrieved; |
||
9 | struct entry_t *next;
|
||
10 | }; |
||
11 | |||
12 | struct entry_t *cache[CACHE_SIZE];
|
||
13 | |||
14 | void cache_foreach(cache_func f) {
|
||
15 | struct entry_t *entry;
|
||
16 | int i;
|
||
17 | |||
18 | for (i = 0; i < CACHE_SIZE; i++) { |
||
19 | for (entry = cache[i]; entry; entry = entry->next)
|
||
20 | f(entry->key); |
||
21 | } |
||
22 | } |
||
23 | |||
24 | void cache_clear() {
|
||
25 | struct entry_t *entry, *next;
|
||
26 | int i;
|
||
27 | |||
28 | for (i = 0; i < CACHE_SIZE; i++) { |
||
29 | for (entry = cache[i]; entry; entry = next) {
|
||
30 | next = entry->next; |
||
31 | free(entry); |
||
32 | } |
||
33 | cache[i] = NULL;
|
||
34 | } |
||
35 | } |
||
36 | |||
37 | struct entry_t *cache_find(unsigned int key) { |
||
38 | struct entry_t *entry;
|
||
39 | |||
40 | for (entry = cache[key % CACHE_SIZE]; entry; entry = entry->next) {
|
||
41 | if (entry->key == key)
|
||
42 | return entry;
|
||
43 | } |
||
44 | |||
45 | return NULL; |
||
46 | } |
||
47 | |||
48 | void cache_add(unsigned int key, unsigned int value) { |
||
49 | struct entry_t *entry;
|
||
50 | int i;
|
||
51 | |||
52 | entry = malloc(sizeof(struct entry_t)); |
||
53 | if (!entry) {
|
||
54 | log_print("ERROR: Out of memory; clearing cache");
|
||
55 | cache_clear(); |
||
56 | return;
|
||
57 | } |
||
58 | |||
59 | i = key % CACHE_SIZE; |
||
60 | entry->key = key; |
||
61 | entry->value = value; |
||
62 | entry->next = cache[i]; |
||
63 | cache[i] = entry; |
||
64 | } |
||
65 | |||
66 | int cache_lookup(unsigned int key, unsigned int *value) { |
||
67 | struct entry_t *entry;
|
||
68 | |||
69 | entry = cache_find(key); |
||
70 | if (entry) {
|
||
71 | *value = entry->value; |
||
72 | return 1; |
||
73 | } else
|
||
74 | return 0; |
||
75 | } |
||
76 | |||
77 | void cache_update(unsigned int key, unsigned int value) { |
||
78 | struct entry_t *entry;
|
||
79 | |||
80 | entry = cache_find(key); |
||
81 | if (entry)
|
||
82 | entry->value = value; |
||
83 | else
|
||
84 | cache_add(key, value); |
||
85 | } |