merged plib
[ppastats.git] / src / cache.c
1 /*
2  * Copyright (C) 2011-2014 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * 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 <libintl.h>
21 #define _(String) gettext(String)
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "cache.h"
28 #include <plog.h>
29 #include "ppastats.h"
30
31
32 /*
33   Simple cache implementation but should be enough for storing LP data.
34 */
35
36 struct entry {
37         const char *key;
38         const void *value;
39         void (*fct_cleanup)(void *);
40 };
41
42 #define CAPACITY 1024
43
44 struct cache {
45         int size;
46         struct entry entries[CAPACITY];
47 };
48
49 static struct cache cache;
50
51 const void *cache_get(const char *key)
52 {
53         int i;
54
55         for (i = 0; i < cache.size; i++)
56                 if (!strcmp(cache.entries[i].key, key)) {
57                         log_debug(_("cache hit %s"), key);
58
59                         return cache.entries[i].value;
60                 }
61
62         log_debug(_("memory cache miss %s"), key);
63
64         return NULL;
65 }
66
67 void cache_put(const char *key, const void *value,
68                void (*fct_cleanup)(void *))
69 {
70         if (cache.size == CAPACITY) {
71                 log_warn(_("exceed cache capacity"));
72                 return ;
73         }
74
75         cache.entries[cache.size].key = strdup(key);
76         cache.entries[cache.size].value = value;
77         cache.entries[cache.size].fct_cleanup = fct_cleanup;
78
79         cache.size++;
80 }
81
82 void cache_cleanup()
83 {
84         int i;
85
86         for (i = 0; i < cache.size; i++) {
87                 free((char *)cache.entries[i].key);
88                 cache.entries[i].fct_cleanup((void *)cache.entries[i].value);
89         }
90 }