Initial garbage colletor implementation
This commit is contained in:
@ -7,49 +7,78 @@ typedef struct A {
|
||||
int num;
|
||||
RefcountEntry refcount;
|
||||
char *str;
|
||||
struct A *next;
|
||||
} A;
|
||||
|
||||
A *make_a(RefcountContext *c, int n, const char *s) {
|
||||
A *a = counting_malloc(sizeof(A));
|
||||
a->num = n;
|
||||
a->str = counting_strdup(s);
|
||||
a->next = NULL;
|
||||
refcount_context_init_obj(c, a);
|
||||
return a;
|
||||
}
|
||||
|
||||
void destroy_callback(void *a_raw) {
|
||||
bool held_refs_callback(void *a_raw, RefcountList **out, void *ignored) {
|
||||
A *a = a_raw;
|
||||
if (a->next) {
|
||||
*out = refcount_list_push_full(*out, a->next, &COUNTING_ALLOCATOR);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void destroy_callback(void *a_raw, void *ignored) {
|
||||
A *a = a_raw;
|
||||
counting_free(a->str);
|
||||
counting_free(a);
|
||||
}
|
||||
|
||||
int main() {
|
||||
refcount_global_allocator = &COUNTING_ALLOCATOR;
|
||||
|
||||
int main(int argc, const char **argv) {
|
||||
RefcountContext *c =
|
||||
refcount_make_context(offsetof(A, refcount), NULL, destroy_callback);
|
||||
refcount_make_context(offsetof(A, refcount), held_refs_callback,
|
||||
destroy_callback, NULL, &COUNTING_ALLOCATOR);
|
||||
|
||||
A *a = make_a(c, 10, "Hello world\n");
|
||||
assert(!refcount_context_is_static(c, a));
|
||||
assert(refcount_context_num_refs(c, a) == 0);
|
||||
|
||||
refcount_context_ref(c, a);
|
||||
a = refcount_context_ref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 1);
|
||||
|
||||
refcount_context_ref(c, a);
|
||||
a = refcount_context_ref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 2);
|
||||
|
||||
refcount_context_unref(c, a);
|
||||
a = refcount_context_unref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 1);
|
||||
|
||||
refcount_context_float(c, a);
|
||||
a = refcount_context_float(c, a);
|
||||
assert(a);
|
||||
assert(refcount_context_num_refs(c, a) == 0);
|
||||
|
||||
refcount_context_ref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 1);
|
||||
|
||||
a = refcount_context_unref(c, a);
|
||||
assert(!a);
|
||||
|
||||
a = make_a(c, 10, "Hello World\n");
|
||||
A *b = make_a(c, 42, "The answer!");
|
||||
a->next = refcount_context_ref(c, b);
|
||||
assert(refcount_context_num_refs(c, a->next) == 1);
|
||||
assert(refcount_context_num_refs(c, a) == 0);
|
||||
|
||||
refcount_context_unref(c, a);
|
||||
|
||||
a = make_a(c, 'a', "a");
|
||||
a->next = refcount_context_ref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 1);
|
||||
|
||||
refcount_context_ref(c, a);
|
||||
refcount_context_unref(c, a);
|
||||
assert(refcount_context_num_refs(c, a) == 1);
|
||||
|
||||
refcount_context_garbage_collect(c);
|
||||
|
||||
refcount_context_destroy(c);
|
||||
|
||||
check_allocator_status();
|
||||
|
Reference in New Issue
Block a user