Added driver interface, loading, hashmap
This commit is contained in:
76
src/utils/hashmap.c
Normal file
76
src/utils/hashmap.c
Normal file
@@ -0,0 +1,76 @@
|
||||
#include "hashmap.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
#define HASHMAP_ARRAY_SIZE 512
|
||||
|
||||
struct HASHMAP_ENTRY
|
||||
{
|
||||
uint32_t key;
|
||||
void* elem;
|
||||
struct HASHMAP_ENTRY* next;
|
||||
};
|
||||
|
||||
struct HASHMAP
|
||||
{
|
||||
struct HASHMAP_ENTRY** array;
|
||||
};
|
||||
|
||||
size_t _hashmap_hash(uint32_t key)
|
||||
{
|
||||
return key % HASHMAP_ARRAY_SIZE;
|
||||
}
|
||||
|
||||
hashmap_t* hashmap_alloc()
|
||||
{
|
||||
hashmap_t* tr = malloc(sizeof(hashmap_t));
|
||||
tr->array = calloc(sizeof(struct HASHMAP_ENTRY*), HASHMAP_ARRAY_SIZE);
|
||||
return tr;
|
||||
}
|
||||
|
||||
void hashmap_free(hashmap_t* hashmap)
|
||||
{
|
||||
for(size_t i = 0; i < HASHMAP_ARRAY_SIZE; i++)
|
||||
{
|
||||
struct HASHMAP_ENTRY* current = hashmap->array[i];
|
||||
|
||||
while(current)
|
||||
{
|
||||
struct HASHMAP_ENTRY* old = current;
|
||||
current = current->next;
|
||||
free(old);
|
||||
}
|
||||
}
|
||||
|
||||
free(hashmap->array);
|
||||
free(hashmap);
|
||||
}
|
||||
|
||||
void hashmap_put(hashmap_t* hashmap, uint32_t key, void* elem)
|
||||
{
|
||||
size_t index = _hashmap_hash(key);
|
||||
struct HASHMAP_ENTRY** current = &hashmap->array[index];
|
||||
|
||||
while(*current)
|
||||
{
|
||||
current = &(*current)->next;
|
||||
}
|
||||
|
||||
(*current) = malloc(sizeof(struct HASHMAP_ENTRY));
|
||||
(*current)->key = key;
|
||||
(*current)->elem = elem;
|
||||
(*current)->next = 0;
|
||||
}
|
||||
|
||||
void* hashmap_get(hashmap_t* hashmap, uint32_t key)
|
||||
{
|
||||
size_t index = _hashmap_hash(key);
|
||||
struct HASHMAP_ENTRY* current = hashmap->array[index];
|
||||
|
||||
while(current)
|
||||
{
|
||||
if(current->key == key) return current->elem;
|
||||
current = current->next;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
15
src/utils/hashmap.h
Normal file
15
src/utils/hashmap.h
Normal file
@@ -0,0 +1,15 @@
|
||||
#ifndef HASHMAP_H
|
||||
#define HASHMAP_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct HASHMAP hashmap_t;
|
||||
|
||||
hashmap_t* hashmap_alloc();
|
||||
void hashmap_free(hashmap_t* hashmap);
|
||||
|
||||
void hashmap_put(hashmap_t* hashmap, uint32_t key, void* elem);
|
||||
void* hashmap_get(hashmap_t* hashmap, uint32_t key);
|
||||
|
||||
#endif
|
Reference in New Issue
Block a user