Skip to content

Commit

Permalink
util/uuid: add a hash function
Browse files Browse the repository at this point in the history
Add hash function to uuid module using the
djb2 hash algorithm.

Add a couple simple unit tests for the hash
function, checking collisions for similar UUIDs.

Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Signed-off-by: Albert Esteve <aesteve@redhat.com>
Message-Id: <20231002065706.94707-2-aesteve@redhat.com>
Reviewed-by: Michael S. Tsirkin <mst@redhat.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
  • Loading branch information
aesteve-rh authored and mstsirkin committed Oct 4, 2023
1 parent 44dc21c commit 78d39da
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/qemu/uuid.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,6 @@ int qemu_uuid_parse(const char *str, QemuUUID *uuid);

QemuUUID qemu_uuid_bswap(QemuUUID uuid);

uint32_t qemu_uuid_hash(const void *uuid);

#endif
27 changes: 27 additions & 0 deletions tests/unit/test-uuid.c
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,32 @@ static void test_uuid_unparse_strdup(void)
}
}

static void test_uuid_hash(void)
{
QemuUUID uuid;
int i;

for (i = 0; i < 100; i++) {
qemu_uuid_generate(&uuid);
/* Obtain the UUID hash */
uint32_t hash_a = qemu_uuid_hash(&uuid);
int data_idx = g_random_int_range(0, 15);
/* Change a single random byte of the UUID */
if (uuid.data[data_idx] < 0xFF) {
uuid.data[data_idx]++;
} else {
uuid.data[data_idx]--;
}
/* Obtain the UUID hash again */
uint32_t hash_b = qemu_uuid_hash(&uuid);
/*
* Both hashes shall be different (avoid collision)
* for any change in the UUID fields
*/
g_assert_cmpint(hash_a, !=, hash_b);
}
}

int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
Expand All @@ -179,6 +205,7 @@ int main(int argc, char **argv)
g_test_add_func("/uuid/parse", test_uuid_parse);
g_test_add_func("/uuid/unparse", test_uuid_unparse);
g_test_add_func("/uuid/unparse_strdup", test_uuid_unparse_strdup);
g_test_add_func("/uuid/hash", test_uuid_hash);

return g_test_run();
}
14 changes: 14 additions & 0 deletions util/uuid.c
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,17 @@ QemuUUID qemu_uuid_bswap(QemuUUID uuid)
bswap16s(&uuid.fields.time_high_and_version);
return uuid;
}

/* djb2 hash algorithm */
uint32_t qemu_uuid_hash(const void *uuid)
{
QemuUUID *qid = (QemuUUID *) uuid;
uint32_t h = 5381;
int i;

for (i = 0; i < ARRAY_SIZE(qid->data); i++) {
h = (h << 5) + h + qid->data[i];
}

return h;
}

0 comments on commit 78d39da

Please sign in to comment.