added --debug option
[ppastats.git] / src / cache.c
1 /*
2     Copyright (C) 2011 jeanfi@gmail.com
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17     02110-1301 USA
18 */
19
20 #include "cache.h"
21 #include "ppastats.h"
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 /*
28   Stupid cache implementation but should be enough for storing LP data.
29 */
30
31 struct entry {
32         const char *key;
33         const void *value;
34         void (*fct_cleanup)(void *);
35 };
36
37 #define CAPACITY 1024
38
39 struct cache {
40         int size;
41         struct entry entries[CAPACITY];
42 };
43
44 static struct cache cache;
45
46 const void *cache_get(const char *key)
47 {
48         int i;
49
50         for (i = 0; i < cache.size; i++)
51                 if (!strcmp(cache.entries[i].key, key)) {
52                         if (debug)
53                                 printf("DEBUG: cache hit %s\n", key);
54
55                         return cache.entries[i].value;
56                 }
57
58         if (debug)
59                 printf("DEBUG: cache miss %s\n", key);
60
61         return NULL;
62 }
63
64 void cache_put(const char *key, const void *value,
65                void (*fct_cleanup)(void *))
66 {
67         if (cache.size == CAPACITY) {
68                 fprintf(stderr, "WARNING: exceed cache capacity\n");
69                 return ;
70         }
71
72         cache.entries[cache.size].key = strdup(key);
73         cache.entries[cache.size].value = value;
74         cache.entries[cache.size].fct_cleanup = fct_cleanup;
75
76         cache.size++;
77 }
78
79 void cache_cleanup()
80 {
81         int i;
82
83         for (i = 0; i < cache.size; i++) {
84                 free((char *)cache.entries[i].key);
85                 cache.entries[i].fct_cleanup((void *)cache.entries[i].value);
86         }
87 }