aboutsummaryrefslogtreecommitdiff
path: root/subprojects/d2tk/src/mum.c
blob: d988418aba1ee684d7916b80f64ba11dabd3e26c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * Copyright (c) 2018-2019 Hanspeter Portner (dev@open-music-kontrollers.ch)
 *
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the Artistic License 2.0 as published by
 * The Perl Foundation.
 *
 * This source is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Artistic License 2.0 for more details.
 *
 * You should have received a copy of the Artistic License 2.0
 * along the source as a COPYING file. If not, obtain it from
 * http://www.perlfoundation.org/artistic_license_2_0.
 */

#include <stdarg.h>
#include <stdio.h>

#include <d2tk/hash.h>

#include "mum.h"

#define SEED 12345

__attribute__((always_inline))
static inline size_t
_sz(const void *data, ssize_t nbytes)
{
	if(nbytes == -1) // is a null-terminated string
	{
		return strlen((const char *)data);
	}

	return nbytes;
}

D2TK_API uint64_t
d2tk_hash(const void *data, ssize_t nbytes)
{
	nbytes = _sz(data, nbytes);

	return mum_hash(data, nbytes, SEED);
}

D2TK_API uint64_t
d2tk_hash_foreach(const void *data, ssize_t nbytes, ...)
{
	va_list args;
	const void *src;

	nbytes = _sz(data, nbytes);

	// derive total temporary buffer size
	size_t sz = nbytes;

	va_start(args, nbytes);

	while( (src = va_arg(args, const void *)) )
	{
		sz += _sz(src, va_arg(args, int));
	}

	va_end(args);

	// fill temporary bufffer
	uint8_t *dst = alloca(sz);
	if(dst)
	{
		size_t off = 0;

		memcpy(&dst[off], data, nbytes);
		off += nbytes;

		va_start(args, nbytes);

		while( (src = va_arg(args, const void *)) )
		{
			nbytes = _sz(src, va_arg(args, int));

			memcpy(&dst[off], src, nbytes);
			off += nbytes;
		}

		va_end(args);

		return mum_hash(dst, sz, SEED);
	}

	return 0;
}