Zephyr Project API  3.4.0
A Scalable Open Source RTOS
hash_function.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2022 Meta
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7#ifndef ZEPHYR_INCLUDE_SYS_HASH_FUNCTION_H_
8#define ZEPHYR_INCLUDE_SYS_HASH_FUNCTION_H_
9
10#include <stddef.h>
11#include <stdint.h>
12
13#include <zephyr/sys/__assert.h>
15
16#ifdef __cplusplus
17extern "C" {
18#endif
19
35typedef uint32_t (*sys_hash_func32_t)(const void *str, size_t n);
36
52static inline uint32_t sys_hash32_identity(const void *str, size_t n)
53{
54 switch (n) {
55 case sizeof(uint8_t):
56 return *(uint8_t *)str;
57 case sizeof(uint16_t):
58 return *(uint16_t *)str;
59 case sizeof(uint32_t):
60 return *(uint32_t *)str;
61 case sizeof(uint64_t):
62 return (uint32_t)(*(uint64_t *)str);
63 default:
64 break;
65 }
66
67 __ASSERT(false, "invalid str length %zu", n);
68
69 return 0;
70}
71
89uint32_t sys_hash32_djb2(const void *str, size_t n);
90
103uint32_t sys_hash32_murmur3(const void *str, size_t n);
104
113static inline uint32_t sys_hash32(const void *str, size_t n)
114{
115 if (IS_ENABLED(CONFIG_SYS_HASH_FUNC32_CHOICE_IDENTITY)) {
116 return sys_hash32_identity(str, n);
117 }
118
119 if (IS_ENABLED(CONFIG_SYS_HASH_FUNC32_CHOICE_DJB2)) {
120 return sys_hash32_djb2(str, n);
121 }
122
123 if (IS_ENABLED(CONFIG_SYS_HASH_FUNC32_CHOICE_MURMUR3)) {
124 return sys_hash32_murmur3(str, n);
125 }
126
127 __ASSERT(0, "No default 32-bit hash. See CONFIG_SYS_HASH_FUNC32_CHOICE");
128
129 return 0;
130}
131
132#ifdef __cplusplus
133}
134#endif
135
136#endif /* ZEPHYR_INCLUDE_SYS_HASH_FUNCTION_H_ */
#define IS_ENABLED(config_macro)
Check for macro definition in compiler-visible expressions.
Definition: util_macro.h:124
uint32_t(* sys_hash_func32_t)(const void *str, size_t n)
32-bit Hash function interface
Definition: hash_function.h:35
static uint32_t sys_hash32_identity(const void *str, size_t n)
The naive identity hash function.
Definition: hash_function.h:52
uint32_t sys_hash32_djb2(const void *str, size_t n)
Daniel J. Bernstein's hash function.
uint32_t sys_hash32_murmur3(const void *str, size_t n)
Murmur3 hash function.
static uint32_t sys_hash32(const void *str, size_t n)
System default 32-bit hash function.
Definition: hash_function.h:113
__UINT32_TYPE__ uint32_t
Definition: stdint.h:90
__UINT64_TYPE__ uint64_t
Definition: stdint.h:91
__UINT8_TYPE__ uint8_t
Definition: stdint.h:88
__UINT16_TYPE__ uint16_t
Definition: stdint.h:89
Macro utilities.