Wednesday, January 19, 2011

libJudy: sparse dynamic arrays (associative arrays)

Seeing as libc has no hashmap component, I went searching and found Judy.

http://judy.sourceforge.net/index.html

libJudy allows you to create, among other things, associative arrays. I needed to store data with key/value pair and this fits the bill rather nicely. A set of macros have been defined to aid in the use of the library. A small summary of the basics can be found here.

Now, for associative arrays....

// first create a null pointer for the array
// which is allocated by Judy
Pvoid_t hash = (Pvoid_t) NULL;

// simple pointer to the value element
PWord_t PV;
char key[] = "hash_key";

// Judy macro to insert with a string key
JSLI(PV, hash, key);
*PV = value;

// now get the value back
JSLG(PV, hash, key);
value = *PV;

NOTES:


  • Judy returns values by returning a pointer to the value, not the value itself
  • The same goes to inserting values, you get a pointer to the space allocated by Judy
  • Must be careful when dealing with Judy array pointers

No comments:

Post a Comment