From 735e8715a80f2d872ebd3ac8546ae77993459c8d Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Tue, 24 Apr 2018 15:22:17 -0700 Subject: [PATCH] Add a function to create a value reference wrapper. --- include/util.h | 8 ++++++++ src/util.c | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/include/util.h b/include/util.h index 036c925..d1af2ac 100644 --- a/include/util.h +++ b/include/util.h @@ -72,5 +72,13 @@ libab_result libab_instantiate_basetype(libab_basetype* to_instantiate, * @return the result of the instantiation. */ libab_result libab_create_table(libab_ref* into, libab_ref* parent); +/** + * Allocates a new reference counted value with the given type and data. + * @param into the reference to store the allocated data into. + * @param data the type-specific data this value holds. + * @param type the type to give the value. + * @return the result of necessary allocations. + */ +libab_result libab_create_value(libab_ref* into, void* data, libab_ref* type); #endif diff --git a/src/util.c b/src/util.c index 062902e..2b24bca 100644 --- a/src/util.c +++ b/src/util.c @@ -1,4 +1,5 @@ #include "util.h" +#include "value.h" #include #include @@ -148,3 +149,28 @@ libab_result libab_create_table(libab_ref* into, libab_ref* parent) { } return result; } + +void _free_value(void* value) { + libab_value_free(value); + free(value); +} + +libab_result libab_create_value(libab_ref* into, void* data, libab_ref* type) { + libab_value* value; + libab_result result = LIBAB_SUCCESS; + if((value = malloc(sizeof(*value)))) { + libab_value_init(value, data, type); + result = libab_ref_new(into, value, _free_value); + + if(result != LIBAB_SUCCESS) { + _free_value(value); + } + } else { + result = LIBAB_MALLOC; + } + + if(result != LIBAB_SUCCESS) { + libab_ref_null(into); + } + return result; +}