Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document library and common use cases #2

Open
jenspots opened this issue Jan 6, 2023 · 1 comment
Open

Document library and common use cases #2

jenspots opened this issue Jan 6, 2023 · 1 comment

Comments

@jenspots
Copy link
Owner

jenspots commented Jan 6, 2023

Tools

@jenspots jenspots changed the title Document library and common use cases. Document library and common use cases Jan 6, 2023
@jenspots
Copy link
Owner Author

By default, no types actually use the key/value paradigm, largely because it's redundant. Let's say we want to implement a structure alike Java's HashMap<Int, String>. A simple paradigm would be

#define LIBWHEEL_KEY   int
#define LIBWHEEL_VALUE char*
#define LIBWHEEL_ALIAS int2string

However, this brings quite a lot of complexity with it, mostly in terms of specific macros for this specific hashtable structure. Therefore, the following alternative is proposed.

typedef struct entry {
   int key;
   char* value;
}

#define LIBWHEEL_TYPE  entry
#define LIBWHEEL_ALIAS int2string

// Use only the key field when comparing instances.
int64_t compare(entry *a, entry *b) {
    return b->key - a->key;
}

Similarly, in libwheel, we always compute the hash value whenever it is required. It is never buffered. However, a user might decide to do so themselves.

typedef struct entry {
   int64_t hash_value;
   const char* string;
}

// User will compute hash manually and assign it to the field.
uint64_t hash(entry *e) {
    return e->hash_value;
}

The initialization function would then be something like

entry* entry_init(const char* s) {
    entry r = malloc(sizeof(entry));
    r->string = s;
    r->hash_value = desired_hash_function(s);
    return r;
}

Despite being somewhat more complex, these paradigms give users the greatest amount of freedom while being consistent as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant