Browse Source Download (without any required ccan dependencies)




map from indices to values (based on libJudy)


Rusty Russell <>


External dependencies:


This provides a convenient wrapper for using JudyL arrays; using integers or pointers as an index, Judy arrays provide an efficient map to integers or pointers.

You define a struct for your particular index and value types using the JMAP_MEMBERS macro, then use the jmap routines to manipulate the mapping.


// Silly example of associating data with arguments by pointer and int.
#include <string.h>
#include <stdio.h>
#include <ccan/jmap/jmap.h>

struct opt_detail {
     bool is_long;
     size_t length; // == 1 if !is_long.

// Define map type for int -> argv.
struct arg_map {
     JMAP_MEMBERS(int, char *);
// Define map type for argv -> struct opt_detail *.
struct opt_map {
     JMAP_MEMBERS(char *, struct opt_detail *);

int main(int argc, char *argv[])
     int i;
     // This map is equivalent to the argv[] array.  Silly example.
     struct arg_map *arg = jmap_new(struct arg_map);
     struct opt_map *opt = jmap_new(struct opt_map);
     struct opt_detail *d;

     // Note: this is not correct for real parsing!
     for (i = 1; i < argc; i++) {
             jmap_add(arg, i, argv[i]);
             if (argv[i][0] != '-')
             d = malloc(sizeof(*d));
             if (argv[i][1] == '-') {
                     // --<stuff>
                     d->is_long = true;
                     d->length = strlen(argv[i]+2);
             } else {
                     // -<opt1>
                     d->is_long = false;
                     d->length = 1;
             jmap_add(opt, argv[i], d);

     printf("Found %lu options:\n", jmap_count(opt));
     for (i = jmap_first(arg); i; i = jmap_next(arg,i)) {
             char *a = jmap_get(arg, i);
             d = jmap_get(opt, a);
             printf("  Arg %i ('%s') is a %s of %zu chars\n",
                    i, a,
                    d == NULL ? "normal arg"
                    : d->is_long ? "long opt"
                    : "short opt",
                    d == NULL ? strlen(a) : d->length);
             // We no longer need it, so free it here.
     return 0;
// Given "--help" output contains "Arg 1 ('--help') is a long opt of 4 chars\n"
// Given "-h" output contains "Arg 1 ('-h') is a short opt of 1 chars\n"
// Given "foo" output contains "Arg 1 ('foo') is a normal arg of 3 chars\n"


LGPL (v2.1 or any later version)