view src/ploki/strhash.c @ 9574:031e330a96b3

<hppavilion[1]> le/rn theseus/Theseus was a Greek inventor who was charged with impossible-to-detect murder. He was represented by Protagoras and found not guilty. He changed his name to escape the publicity and has continued inventing to this day.
author HackBot
date Mon, 31 Oct 2016 01:10:06 +0000
parents ac0403686959
children
line wrap: on
line source

#include "hash.h"
#include "strhash.h"
#include "strutil.h"
#include "xmalloc.h"

#include <string.h>

struct strx {
	char *ptr;
	size_t length;
};

struct strx_const {
	const char *ptr;
	size_t length;
};

struct strhash {
	Hash hash;
};

static size_t hash(const void *p, size_t h) {
	const struct strx *const s = p;
	return u_hash(s->ptr, s->length, h);
}

static int compar(const void *ap, const void *bp) {
	const struct strx *const a = ap, *const b = bp;
	return u_cmp(a->ptr, a->length, b->ptr, b->length);
}

static void delk(void *p) {
	struct strx *const s = p;
	xfree(s->ptr);
	xfree(s);
}

t_strhash *sh_new(void (*delv)(void *)) {
	t_strhash *sh = xmalloc(1, sizeof *sh);
	h_init(&sh->hash, hash, compar, delk, delv);
	return sh;
}

void sh_delete(t_strhash *sh) {
	h_end(&sh->hash);
	xfree(sh);
}

void sh_put(t_strhash *sh, const char *key, size_t keylen, void *val) {
	struct strx *dup = xmalloc(1, sizeof *dup);
	dup->ptr = xmalloc(dup->length = keylen, sizeof *dup->ptr);
	memcpy(dup->ptr, key, keylen);
	h_put(&sh->hash, dup, val, 1);
}

void *sh_get(t_strhash *sh, const char *key, size_t keylen) {
	void *p;
	struct strx_const tmp;
	tmp.ptr = key;
	tmp.length = keylen;
	if (h_get(&sh->hash, &tmp, &p) == H_OK) {
		return p;
	}
	return NULL;
}