From ace7d8eff3df026f07e42122caaf35880d8289bb Mon Sep 17 00:00:00 2001 From: Kimplul Date: Thu, 16 Oct 2025 13:21:13 +0300 Subject: add stable vector + Allows references to elements to be stable over insertion + Doesn't implement all of the regular vec interface at the moment and requires slightly different iteration handling unfortunately, but maybe it's not too bad? --- tests/spvec.c | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 tests/spvec.c (limited to 'tests') diff --git a/tests/spvec.c b/tests/spvec.c new file mode 100644 index 0000000..aa9b96c --- /dev/null +++ b/tests/spvec.c @@ -0,0 +1,81 @@ +#include +#include +#include "test.h" + +/* required defs */ +#define SPVEC_TYPE int +#define SPVEC_NAME ints + +/* optional defs */ +#define SPVEC_MALLOC mallocc +#define SPVEC_CALLOC callocc +#define SPVEC_REALLOC reallocc +#define SPVEC_FREE free + +#include + +int main() +{ +#if defined(COVERAGE) + assert(!covsrv_init()); + atexit(covsrv_destroy); +#endif + struct ints ints = ints_create(); + + /* ensure stability before we do anything else */ + assert(ints_reserve(&ints, 1)); + int *p = ints_at(&ints, 0); + + /* should allocate at least a few extra buckets */ + assert(ints_reserve(&ints, 256)); + assert(p == ints_at(&ints, 0)); + + /* test out resetting as well while we're at it*/ + assert(ints_len(&ints) == 256); + ints_reset(&ints); + assert(ints_len(&ints) == 0); + + for (int i = 0; i < 1000000; ++i) { + if (!ints_append(&ints, i)) { + fprintf(stderr, "failed appending %d to vec\n", i); + ints_destroy(&ints); + return -1; + } + } + assert(ints_len(&ints) == 1000000); + + for (int i = 0; i < 1000000; ++i) { + int *v = ints_at(&ints, i); + assert(v && *v == i); + } + + int i = 0; + foreach(ints, iter, &ints) { + assert(iter.v && *iter.v == i); + i++; + } + + /* TEN million !!1! */ + if (!ints_reserve(&ints, 10000000)) { + fprintf(stderr, "failed reserving vec\n"); + ints_destroy(&ints); + return -1; + } + + /* set size back to keep test runtime reasonable + * (is shrink necessary when we already have reserve? I + * guess it shows intention a bit better and just asserts instead of + * maybe fails?) */ + ints_shrink(&ints, 1000000); + + /* so the above is equivalent to */ + assert(ints_reserve(&ints, 1000000)); + assert(ints_len(&ints) == 1000000); + + for (int i = 1000000 - 1; i >= 0; --i) { + ints_remove(&ints, i); + } + assert(ints_len(&ints) == 0); + + ints_destroy(&ints); +} -- cgit v1.2.3