Skip to content

Instantly share code, notes, and snippets.

@courtc
Last active February 1, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save courtc/5d847b45ce60fdbf624d171f0c1acdc2 to your computer and use it in GitHub Desktop.
Save courtc/5d847b45ce60fdbf624d171f0c1acdc2 to your computer and use it in GitHub Desktop.
caching api
#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
#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