Saturday, March 01, 2008

gperf example for keyword lookup


test_mimetype: test_mimetype.c mimetype.gperf
$(GPERF) --ignore-case --struct-type --output=mimetype.c mimetype.gperf
$(CC) $(COPTS) -o test_mimetype test_mimetype.c


%define lookup-function-name gperf_mimetype
%includes
struct mimetype_tbl { char *name; char *val; };
%%
"ai", "application/postscript"
"aif", "audio/x-aiff"
"aifc", "audio/x-aiff"
"zip", "application/zip"
%%
static char *mimetype(char *ext)
{
struct mimetype_tbl *v = gperf_mimetype(ext, strlen(ext));
return v ? v->val : NULL;
}


#include <stdio.h%gt;
#include "mimetype.c"

void t1(char *ext)
{
printf("ext=:%s: type=:%s:\n",ext, mimetype(ext));
}

int main()
{
t1("mp3");
t1("jpg");
t1("JPG");
t1("JpG");
t1("foo");
return 0;
}