core/containers/set: Add set_alloc() and set_free() functions

Signed-off-by: Anna Schumaker <Anna@OcarinaProject.net>
This commit is contained in:
Anna Schumaker 2016-04-29 07:55:25 -04:00 committed by Anna Schumaker
parent da3dd60ef3
commit ee4bbacf81
2 changed files with 34 additions and 21 deletions

View File

@ -34,6 +34,19 @@ static inline void set_deinit(struct set *set)
g_hash_table_destroy(set->s_set);
}
static inline struct set *set_alloc()
{
struct set *set = g_malloc(sizeof(struct set));
set_init(set);
return set;
}
static inline void set_free(void *set)
{
set_deinit((struct set *)set);
g_free(set);
}
static inline bool set_insert(struct set *set, unsigned int value)
{
return g_hash_table_add(set->s_set, GUINT_TO_POINTER(value));

View File

@ -7,59 +7,59 @@
void test_set()
{
struct file f = FILE_INIT("set", 0, 0);
struct set set = SET_INIT();
struct file f = FILE_INIT("set", 0, 0);
struct set *set = set_alloc();
unsigned int i, N = 10;
struct set_iter it;
/* Insert N items. */
for (i = 0; i < N; i++) {
test_loop_equal(set_insert(&set, i), (bool)true, i);
test_loop_equal(set_insert(&set, i), (bool)false, i);
test_loop_equal(set_size(&set), i + 1, i);
test_loop_equal(set_has(&set, i), (bool)true, i);
test_loop_equal(set_insert(set, i), (bool)true, i);
test_loop_equal(set_insert(set, i), (bool)false, i);
test_loop_equal(set_size(set), i + 1, i);
test_loop_equal(set_has(set, i), (bool)true, i);
} test_loop_passed();
set_insert(&set, 0);
test_equal(set_size(&set), N);
set_insert(set, 0);
test_equal(set_size(set), N);
/* Remove even items. */
for (i = 0; i < N; i += 2) {
test_loop_equal(set_remove(&set, i), (bool)true, i);
test_loop_equal(set_remove(&set, i), (bool)false, i);
test_loop_equal(set_has(&set, i), (bool)false, i);
test_loop_equal(set_remove(set, i), (bool)true, i);
test_loop_equal(set_remove(set, i), (bool)false, i);
test_loop_equal(set_has(set, i), (bool)false, i);
} test_loop_passed();
test_equal(set_size(&set), N / 2);
test_equal(set_size(set), N / 2);
/* Test iterating. */
i = 1;
set_for_each(&set, &it) {
set_for_each(set, &it) {
test_loop_equal(it.it_val, i, i);
i += 2;
} test_loop_passed();
file_open(&f, OPEN_WRITE);
set_write(&f, &set);
set_write(&f, set);
file_close(&f);
set_clear(&set);
test_equal(set_size(&set), 0);
set_clear(set);
test_equal(set_size(set), 0);
file_open(&f, OPEN_READ);
set_read(&f, &set);
test_equal(set_size(&set), N / 2);
set_read(&f, set);
test_equal(set_size(set), N / 2);
file_close(&f);
/* Check values. */
for (i = 0; i < N; i++) {
if (i % 2) { /* Odd values. */
test_loop_equal(set_has(&set, i), (bool)true, i);
test_loop_equal(set_has(set, i), (bool)true, i);
} else { /* Even values. */
test_loop_equal(set_has(&set, i), (bool)false, i);
test_loop_equal(set_has(set, i), (bool)false, i);
}
} test_loop_passed();
set_deinit(&set);
set_free(set);
}
void test_copy()