1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
6 Copyright 2014 Michal Schmidt
11 #include "hash-funcs.h"
12 #include "path-util.h"
14 void string_hash_func(const void *p, struct siphash *state) {
15 siphash24_compress(p, strlen(p) + 1, state);
18 int string_compare_func(const void *a, const void *b) {
22 const struct hash_ops string_hash_ops = {
23 .hash = string_hash_func,
24 .compare = string_compare_func
28 void path_hash_func(const void *p, struct siphash *state) {
35 /* Calculates a hash for a path in a way this duplicate inner slashes don't make a differences, and also
36 * whether there's a trailing slash or not. This fits well with the semantics of path_compare(), which does
37 * similar checks and also doesn't care for trailing slashes. Note that relative and absolute paths (i.e. those
38 * which begin in a slash or not) will hash differently though. */
41 if (n > 0) { /* Eat up initial slashes, and add one "/" to the hash for all of them */
42 siphash24_compress(q, 1, state);
47 /* Determine length of next component */
49 if (n == 0) /* Reached the end? */
52 /* Add this component to the hash and skip over it */
53 siphash24_compress(q, n, state);
56 /* How many slashes follow this component? */
58 if (q[n] == 0) /* Is this a trailing slash? If so, we are at the end, and don't care about the slashes anymore */
61 /* We are not add the end yet. Hash exactly one slash for all of the ones we just encountered. */
62 siphash24_compress(q, 1, state);
67 int path_compare_func(const void *a, const void *b) {
68 return path_compare(a, b);
71 const struct hash_ops path_hash_ops = {
72 .hash = path_hash_func,
73 .compare = path_compare_func
76 void trivial_hash_func(const void *p, struct siphash *state) {
77 siphash24_compress(&p, sizeof(p), state);
80 int trivial_compare_func(const void *a, const void *b) {
81 return a < b ? -1 : (a > b ? 1 : 0);
84 const struct hash_ops trivial_hash_ops = {
85 .hash = trivial_hash_func,
86 .compare = trivial_compare_func
89 void uint64_hash_func(const void *p, struct siphash *state) {
90 siphash24_compress(p, sizeof(uint64_t), state);
93 int uint64_compare_func(const void *_a, const void *_b) {
95 a = *(const uint64_t*) _a;
96 b = *(const uint64_t*) _b;
97 return a < b ? -1 : (a > b ? 1 : 0);
100 const struct hash_ops uint64_hash_ops = {
101 .hash = uint64_hash_func,
102 .compare = uint64_compare_func
105 #if SIZEOF_DEV_T != 8
106 void devt_hash_func(const void *p, struct siphash *state) {
107 siphash24_compress(p, sizeof(dev_t), state);
110 int devt_compare_func(const void *_a, const void *_b) {
112 a = *(const dev_t*) _a;
113 b = *(const dev_t*) _b;
114 return a < b ? -1 : (a > b ? 1 : 0);
117 const struct hash_ops devt_hash_ops = {
118 .hash = devt_hash_func,
119 .compare = devt_compare_func