RPA Toolkit
73b3128187fbc4b95dff8ce7099a3e512556b5d1
[rpatk.git] / rpa2 / rpacache.c
1 #include "rpacache.h"
2 #include "rmem.h"
3 #include "rparecord.h"
4
5 #define RPA_MCACHE_BUCKET(_top_, _ruleid_) ( ( ((rulong)(_top_)) ^ ((rulong)(_ruleid_)) ) & RPA_MCACHE_MASK)
6
7
8 rpacache_t *rpa_cache_create()
9 {
10         rint i;
11         rpacache_t *cache = (rpacache_t*) r_zmalloc(sizeof(*cache));
12
13         if (!cache)
14                 return NULL;
15         for (i = 0; i < RPA_MCACHE_SIZE; i++) {
16                 cache->entry[i].records = r_array_create(sizeof(rparecord_t));
17                 if (!cache->entry[i].records) {
18                         rpa_cache_destroy(cache);
19                         return NULL;
20                 }
21         }
22
23         return cache;
24 }
25
26
27 void rpa_cache_destroy(rpacache_t *cache)
28 {
29         rint i;
30
31         if (!cache)
32                 return;
33         for (i = 0; i < RPA_MCACHE_SIZE; i++) {
34                 if (cache->entry[i].records) {
35                         r_array_destroy(cache->entry[i].records);
36                 }
37         }
38         r_free(cache);
39 }
40
41 void rpa_cache_invalidate(rpacache_t *cache)
42 {
43         ++cache->serial;
44 }
45
46
47 void rpa_cache_disable(rpacache_t *cache, rlong disable)
48 {
49         cache->disalbled = disable;
50 }
51
52
53 void rpa_cache_set(rpacache_t *cache, rlong top, rlong ruleid, rlong ret, rparecord_t* records, rsize_t nrecords)
54 {
55         rlong i;
56         rulong bucket = RPA_MCACHE_BUCKET(top, ruleid);
57
58         if (ret <= 0 || cache->disalbled)
59                 return;
60 //      r_printf("Set the cache @ %ld for: top = %ld, ret = %d, nrecors = %ld, rulename = %s\n", bucket, top, ret, nrecords, records->rule);
61         cache->entry[bucket].ruleid = ruleid;
62         cache->entry[bucket].top = top;
63         cache->entry[bucket].ret = ret;
64         cache->entry[bucket].serial = cache->serial;
65         r_array_setlength(cache->entry[bucket].records, 0);
66         for (i = 0; i < nrecords; i++)
67                 r_array_add(cache->entry[bucket].records, &records[i]);
68 }
69
70
71 rpacachedentry_t *rpa_cache_lookup(rpacache_t *cache, rlong top, rlong ruleid)
72 {
73         rulong bucket = RPA_MCACHE_BUCKET(top, ruleid);
74         rpacachedentry_t *entry = &cache->entry[bucket];
75
76         if (entry->serial == cache->serial && entry->ruleid == ruleid && entry->top == top) {
77 //              rparecord_t *prec = (rparecord_t *)r_array_slot(entry->records, 0);
78 //              r_printf("HIT the cache @ %ld,  top = %ld, ret = %ld, rulename = %s\n", bucket, entry->top, entry->ret, prec->rule);
79                 ++cache->hit;
80                 return entry;
81         }
82         return NULL;
83 }