Spider2/tests/hset_add.c

70 lines
2.1 KiB
C

#include <stdbool.h>
#include <string.h>
#include "util.h"
#include "unit.h"
size_t charp_parityhash(char **ptr) {
return parityhash(*ptr, strlen(*ptr));
}
bool charp_cmp(char **lhs, char **rhs) {
return strcmp(*lhs, *rhs) == 0;
}
int tests_hset_add(int argc, char **argv) {
charp_hset_t hset1;
hset_init(charp_hset_t, hset1, charp_parityhash, charp_cmp);
char *ptr = "hello";
chi_assert("\"hello\" should not be apart of the set", !hset_add(hset1, ptr));
chi_assert("\"hello\" should be apart of the set", hset_add(hset1, ptr));
ptr = "ehllo";
chi_assert("\"ehllo\" should not be apart of the set", !hset_add(hset1, ptr));
char *heap = xmalloc(strlen(ptr) + 1);
strcpy(heap, ptr);
chi_assert("\"ehllo\" should be apart of the set", hset_add(hset1, heap));
xfree(heap);
hset_destroy(hset1);
charp_hset_t hset2;
hset_init(charp_hset_t, hset2, charp_parityhash, charp_cmp);
#define MAX_STR_SIZE 3
ptr = xmalloc(MAX_STR_SIZE + 2);
strcpy(ptr, "0");
char buf[100];
for(int len = 1; len < MAX_STR_SIZE + 1;) {
snprintf(buf, sizeof(buf)-1, "\"%s\" shouldn't be apart of the set", ptr);
char *tmp = xmalloc(strlen(ptr) + 1);
strcpy(tmp, ptr);
chi_assert(buf, !hset_add(hset2, tmp));
int c = 1;
for (int i = len - 1, s = 0; i >= 0; i--)
s = (ptr[i] - '0') + c, c = s > 9, ptr[i] = s % 10 + '0';
if (c != 0) {
memmove(ptr + 1, ptr, (len++) + 1);
*ptr = '1';
}
}
strcpy(ptr, "0");
for(int len = 1; len < MAX_STR_SIZE + 1;) {
snprintf(buf, sizeof(buf)-1, "\"%s\" should be apart of the set", ptr);
chi_assert(buf, hset_find(hset2, ptr));
chi_assert(buf, hset_add(hset2, ptr));
int c = 1;
for (int i = len - 1, s = 0; i >= 0; i--)
s = (ptr[i] - '0') + c, c = s > 9, ptr[i] = s % 10 + '0';
if (c != 0) {
memmove(ptr + 1, ptr, (len++) + 1);
*ptr = '1';
}
}
xfree(ptr);
hset_destroy(hset2);
return 0;
}