source: mainline/uspace/lib/c/include/adt/hash.h@ cd1e3fc0

Last change on this file since cd1e3fc0 was d7f7a4a, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 3 years ago

Replace some license headers with SPDX identifier

Headers are replaced using tools/transorm-copyright.sh only
when it can be matched verbatim with the license header used
throughout most of the codebase.

  • Property mode set to 100644
File size: 2.2 KB
Line 
1/*
2 * SPDX-FileCopyrightText: 2012 Adam Hraska
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7/** @addtogroup libc
8 * @{
9 */
10/** @file
11 */
12#ifndef _LIBC_ADT_HASH_H_
13#define _LIBC_ADT_HASH_H_
14
15#include <stdint.h>
16#include <types/common.h>
17
18/** Produces a uniform hash affecting all output bits from the skewed input. */
19static inline uint32_t hash_mix32(uint32_t hash)
20{
21 /*
22 * Thomas Wang's modification of Bob Jenkin's hash mixing function:
23 * http://www.concentric.net/~Ttwang/tech/inthash.htm
24 * Public domain.
25 */
26 hash = ~hash + (hash << 15);
27 hash = hash ^ (hash >> 12);
28 hash = hash + (hash << 2);
29 hash = hash ^ (hash >> 4);
30 hash = hash * 2057;
31 hash = hash ^ (hash >> 16);
32 return hash;
33}
34
35/** Produces a uniform hash affecting all output bits from the skewed input. */
36static inline uint64_t hash_mix64(uint64_t hash)
37{
38 /*
39 * Thomas Wang's public domain 64-bit hash mixing function:
40 * http://www.concentric.net/~Ttwang/tech/inthash.htm
41 */
42 hash = (hash ^ 61) ^ (hash >> 16);
43 hash = hash + (hash << 3);
44 hash = hash ^ (hash >> 4);
45 hash = hash * 0x27d4eb2d;
46 hash = hash ^ (hash >> 15);
47 /*
48 * Lower order bits are mixed more thoroughly. Swap them with
49 * the higher order bits and make the resulting higher order bits
50 * more usable.
51 */
52 return (hash << 32) | (hash >> 32);
53}
54
55/** Produces a uniform hash affecting all output bits from the skewed input. */
56static inline size_t hash_mix(size_t hash)
57{
58#ifdef __32_BITS__
59 return hash_mix32(hash);
60#elif defined(__64_BITS__)
61 return hash_mix64(hash);
62#else
63#error Unknown size_t size - cannot select proper hash mix function.
64#endif
65}
66
67/** Use to create a hash from multiple values.
68 *
69 * Typical usage:
70 * @code
71 * int car_id;
72 * bool car_convertible;
73 * // ..
74 * size_t hash = 0;
75 * hash = hash_combine(hash, car_id);
76 * hash = hash_combine(hash, car_convertible);
77 * // Now use hash as a hash of both car_id and car_convertible.
78 * @endcode
79 */
80static inline size_t hash_combine(size_t seed, size_t hash)
81{
82 /*
83 * todo: use Bob Jenkin's proper mixing hash pass:
84 * http://burtleburtle.net/bob/c/lookup3.c
85 */
86 seed ^= hash + 0x9e3779b9 +
87 ((seed << 5) | (seed >> (sizeof(size_t) * 8 - 5)));
88 return seed;
89}
90
91#endif
Note: See TracBrowser for help on using the repository browser.