view src/ploki/strhash.c @ 8916:0234daffd946

<oerjan> addquote <int-e> I couldn\'t help thinking that maybe if one considers the ramifications in full detail it will turn out that overthinking is often not helpful and therefore, not something to be proud of.
author HackBot
date Sun, 14 Aug 2016 02:31:47 +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;
}