core/set: Add functions for reading and writing sets

Signed-off-by: Anna Schumaker <Anna@OcarinaProject.net>
This commit is contained in:
Anna Schumaker 2015-11-09 08:12:28 -05:00
parent 82a74dd5ec
commit 1cd22a9454
3 changed files with 46 additions and 0 deletions

View File

@ -21,3 +21,23 @@ void set_inline_intersect(const struct set *lhs, struct set *rhs)
g_hash_table_iter_remove(&it_rhs.it_iter);
}
}
void set_read(struct file *file, struct set *set)
{
unsigned int num, val, i;
file_readf(file, "%u ", &num);
for (i = 0; i < num; i++) {
file_readf(file, "%u ", &val);
set_insert(set, val);
}
}
void set_write(struct file *file, struct set *set)
{
struct set_iter it;
file_writef(file, "%u ", set_size(set));
set_for_each(set, &it)
file_writef(file, "%u ", it.it_val);
}

View File

@ -4,6 +4,7 @@
#ifndef OCARINA_CORE_SET_H
#define OCARINA_CORE_SET_H
#include <core/file.h>
#include <glib.h>
#include <stdbool.h>
@ -60,6 +61,12 @@ void set_copy(const struct set *, struct set *);
/* Remove values from set2 that are not also in set1. */
void set_inline_intersect(const struct set *, struct set *);
/* Read values from file. */
void set_read(struct file *, struct set *);
/* Write values to file. */
void set_write(struct file *, struct set *);
static inline bool set_iter_next(struct set_iter *it)
{

View File

@ -7,6 +7,7 @@
void test_set()
{
struct file f = FILE_INIT("set", 0);
struct set set = SET_INIT();
unsigned int i, N = 10;
struct set_iter it;
@ -37,9 +38,27 @@ void test_set()
i += 2;
} test_loop_passed();
file_open(&f, OPEN_WRITE);
set_write(&f, &set);
file_close(&f);
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);
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);
} else { /* Even values. */
test_loop_equal(set_has(&set, i), (bool)false, i);
}
} test_loop_passed();
set_deinit(&set);
}