Last active
February 1, 2018 19:50
-
-
Save courtc/5d847b45ce60fdbf624d171f0c1acdc2 to your computer and use it in GitHub Desktop.
caching api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _CACHE_H_ | |
#define _CACHE_H_ | |
#include "node.h" | |
struct cache_item { | |
void (* release)(struct cache_item *); | |
struct node mi; | |
struct node li; | |
}; | |
enum cache_policy { | |
CACHE_FIFO, | |
CACHE_LIFO, | |
CACHE_LRU, | |
CACHE_MRU, | |
CACHE_LFU, | |
}; | |
struct cache; | |
struct cache *cache_create(enum cache_policy p, unsigned int limit); | |
void cache_destroy(struct cache *c, int release); | |
struct cache_item *cache_get(struct cache *c, unsigned long key); | |
int cache_put(struct cache *c, unsigned long key, struct cache_item *ci); | |
int cache_contains(struct cache *c, unsigned long key); | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "cache.h" | |
struct data_item { | |
struct cache_item ci; | |
char *data; | |
}; | |
struct data_item *load_data(unsigned int key); | |
void unload_data(struct data_item *di); | |
unsigned long map_key(const char *name); | |
static void data_release(struct cache_item *ci) | |
{ | |
struct data_item *di = container_of(ci, struct data_item, ci); | |
unload_data(di); | |
} | |
static const char *get_data(struct cache *cache, unsigned long key) | |
{ | |
struct cache_item *ci; | |
struct data_item *di; | |
ci = cache_get(cache, key); | |
if (ci != NULL) { | |
di = container_of(ci, struct data_item, ci); | |
return di->data; | |
} | |
di = load_data(key); | |
di->ci.release = data_release; | |
cache_put(cache, key, &di->ci); | |
return di->data; | |
} | |
int main(void) | |
{ | |
struct cache *cache; | |
char name[256]; | |
cache = cache_create(CACHE_LFU, 256); | |
while (fgets(name, sizeof(name), stdin)) { | |
unsigned long key; | |
const char *data; | |
key = map_key(name); | |
if (key == -1) | |
continue; | |
data = get_data(cache, key); | |
printf(stdout, "%s", data); | |
} | |
cache_destroy(cache, 1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment