1 /*
2  * Copyright (c) 2022 Meta
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/ztest.h>
8 #include <zephyr/sys/hash_map.h>
9 
10 #include "_main.h"
11 
ZTEST(hash_map,test_remove_true)12 ZTEST(hash_map, test_remove_true)
13 {
14 	int ret;
15 
16 	for (size_t i = 0; i < MANY; ++i) {
17 		ret = sys_hashmap_insert(&map, i, i, NULL);
18 		zassert_equal(1, ret, "failed to insert (%zu, %zu): %d", i, i, ret);
19 		zassert_equal(i + 1, sys_hashmap_size(&map));
20 	}
21 
22 	for (size_t i = MANY; i > 0; --i) {
23 		zassert_equal(true, sys_hashmap_remove(&map, i - 1, NULL));
24 		zassert_equal(i - 1, sys_hashmap_size(&map));
25 	}
26 
27 	/* after removing the last node, buckets should also be freed */
28 	zassert_equal(map.data->buckets, NULL);
29 	zassert_equal(map.data->n_buckets, 0);
30 }
31 
ZTEST(hash_map,test_remove_false)32 ZTEST(hash_map, test_remove_false)
33 {
34 	zassert_true(sys_hashmap_is_empty(&map));
35 	zassert_false(sys_hashmap_remove(&map, 42, NULL));
36 
37 	zassert_equal(1, sys_hashmap_insert(&map, 1, 1, NULL));
38 	zassert_false(sys_hashmap_remove(&map, 42, NULL));
39 }
40 
ZTEST(hash_map,test_remove_entry)41 ZTEST(hash_map, test_remove_entry)
42 {
43 	uint64_t entry = 0xF00DF00DF00DF00DU;
44 	uint64_t old_value;
45 
46 	/* Fill hashmap so that the rehashing condition is not always met when running the test */
47 	for (size_t i = 0; i < 20; ++i) {
48 		zassert_false(sys_hashmap_insert(&map, i, i, NULL) < 0);
49 	}
50 
51 	/* Remove key 16, expecting its entry to be erased */
52 	old_value = 0;
53 	zassert_true(sys_hashmap_remove(&map, 16, &old_value));
54 	zassert_equal(16, old_value);
55 
56 	/* Insert an entry at key 16, expecting no old entry to be returned */
57 	old_value = 0;
58 	zassert_equal(1, sys_hashmap_insert(&map, 16, entry, &old_value));
59 	zassert_equal(0, old_value);
60 }
61