From 01a76c7d703650df7f39d21c704f5b7c4f41ca14 Mon Sep 17 00:00:00 2001 From: David Robillard Date: Thu, 25 Feb 2021 20:08:20 -0500 Subject: Add numeric node construction and access API --- src/node.c | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) (limited to 'src/node.c') diff --git a/src/node.c b/src/node.c index db183fc0..f071fc97 100644 --- a/src/node.c +++ b/src/node.c @@ -276,6 +276,68 @@ serd_new_curie(const SerdStringView str) return serd_new_simple_node(SERD_CURIE, str); } +ExessVariant +serd_node_get_value_as(const SerdNode* const node, + const ExessDatatype value_type) +{ + const SerdNode* const datatype_node = serd_node_datatype(node); + + const ExessDatatype node_type = + datatype_node ? exess_datatype_from_uri(serd_node_string(datatype_node)) + : EXESS_NOTHING; + + if (!node_type) { + // No datatype, assume it matches and try reading the value directly + ExessVariant v = exess_make_nothing(EXESS_SUCCESS); + const ExessResult r = + exess_read_variant(&v, value_type, serd_node_string(node)); + + return r.status ? exess_make_nothing(r.status) : v; + } + + // Read the value from the node + ExessVariant v = exess_make_nothing(EXESS_SUCCESS); + const ExessResult r = + exess_read_variant(&v, node_type, serd_node_string(node)); + + // Coerce value to the desired type if possible + return r.status ? exess_make_nothing(r.status) + : exess_coerce(v, value_type, EXESS_REDUCE_PRECISION); +} + +bool +serd_get_boolean(const SerdNode* const node) +{ + const ExessVariant value = serd_node_get_value_as(node, EXESS_BOOLEAN); + + return (value.datatype == EXESS_BOOLEAN) ? *exess_get_boolean(&value) : false; +} + +double +serd_get_double(const SerdNode* const node) +{ + const ExessVariant value = serd_node_get_value_as(node, EXESS_DOUBLE); + + return (value.datatype == EXESS_DOUBLE) ? *exess_get_double(&value) + : (double)NAN; +} + +float +serd_get_float(const SerdNode* const node) +{ + const ExessVariant value = serd_node_get_value_as(node, EXESS_FLOAT); + + return (value.datatype == EXESS_FLOAT) ? *exess_get_float(&value) : NAN; +} + +int64_t +serd_get_integer(const SerdNode* const node) +{ + const ExessVariant value = serd_node_get_value_as(node, EXESS_LONG); + + return (value.datatype == EXESS_LONG) ? *exess_get_long(&value) : 0; +} + SerdNode* serd_node_copy(const SerdNode* node) { @@ -585,7 +647,7 @@ serd_new_decimal(const double d, const SerdNode* const datatype) } SerdNode* -serd_new_integer(int64_t i, const SerdNode* datatype) +serd_new_integer(const int64_t i, const SerdNode* datatype) { const ExessVariant variant = exess_make_long(i); const size_t len = exess_write_variant(variant, 0, NULL).count; -- cgit v1.2.1