From ee76d39f385330d10c2dd31169d98a8d8ed9a94a Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Tue, 24 Apr 2018 15:08:39 -0700 Subject: [PATCH] Remove un-thread safe shared reference count. --- include/refcount.h | 6 +++++- src/refcount.c | 26 +++++++++++++------------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/include/refcount.h b/include/refcount.h index 3339c3b..c6c1ed8 100644 --- a/include/refcount.h +++ b/include/refcount.h @@ -34,7 +34,11 @@ struct libab_ref_s { /** * Whether this reference is a strong reference. */ - int strong; + unsigned int strong:1; + /** + * Whether this reference is a NULL reference. + */ + unsigned int null:1; /** * The reference count struct keeping track * of how many references are pointing to the value. diff --git a/src/refcount.c b/src/refcount.c index d926161..93a2963 100644 --- a/src/refcount.c +++ b/src/refcount.c @@ -5,6 +5,7 @@ libab_result libab_ref_new(libab_ref* ref, void* data, void (*free_func)(void* data)) { libab_result result = LIBAB_SUCCESS; + ref->null = 0; ref->strong = 1; ref->data = data; if ((ref->count = malloc(sizeof(*(ref->count))))) { @@ -16,13 +17,8 @@ libab_result libab_ref_new(libab_ref* ref, void* data, return result; } -static libab_ref_count null_count = {NULL, 0, 1}; - void libab_ref_null(libab_ref* ref) { - ref->strong = 0; - ref->data = NULL; - ref->count = &null_count; - null_count.weak++; + ref->null = 1; } void _libab_ref_changed(libab_ref* ref) { @@ -38,7 +34,7 @@ void _libab_ref_changed(libab_ref* ref) { } void libab_ref_weaken(libab_ref* ref) { - if (ref->strong) { + if (!ref->null && ref->strong) { ref->count->strong--; ref->strong = 0; _libab_ref_changed(ref); @@ -46,14 +42,18 @@ void libab_ref_weaken(libab_ref* ref) { } void libab_ref_free(libab_ref* ref) { - ref->count->strong -= ref->strong; - ref->count->weak--; - _libab_ref_changed(ref); + if(!ref->null) { + ref->count->strong -= ref->strong; + ref->count->weak--; + _libab_ref_changed(ref); + } } void libab_ref_copy(const libab_ref* ref, libab_ref* into) { - ref->count->strong++; - ref->count->weak++; + if(!ref->null) { + ref->count->strong++; + ref->count->weak++; + } memcpy(into, ref, sizeof(*ref)); } @@ -61,7 +61,7 @@ void libab_ref_data_free(void* data) { free(data); } void* libab_ref_get(const libab_ref* ref) { void* to_return = NULL; - if (ref->count->strong > 0) { + if (!ref->null && ref->count->strong > 0) { to_return = ref->data; } return to_return;