From d6c3858418c4c00adb18d927135f73ed5a54564a Mon Sep 17 00:00:00 2001 From: Lexi Winter Date: Sun, 22 Jun 2025 16:56:39 +0100 Subject: nihil.ucl: improve type safety --- nihil.ucl/object_cast.ccm | 81 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 nihil.ucl/object_cast.ccm (limited to 'nihil.ucl/object_cast.ccm') diff --git a/nihil.ucl/object_cast.ccm b/nihil.ucl/object_cast.ccm new file mode 100644 index 0000000..7291960 --- /dev/null +++ b/nihil.ucl/object_cast.ccm @@ -0,0 +1,81 @@ +/* + * This source code is released into the public domain. + */ + +module; + +#include + +#include + +export module nihil.ucl:object_cast; + +import :type; +import :object; +import :array; + +namespace nihil::ucl { + +/* + * Ensure a UCL object is convertible to another type. Throws type_mismatch + * if not. + */ + +// Implementation for basic types. +template +struct convert_check +{ + auto check(::ucl_object_t const *from) -> void + { + auto from_type = static_cast(::ucl_object_type(from)); + auto to_type = To::ucl_type; + + // Converting from anything to object is permitted. + if (to_type == object_type::object) + return; + + // Converting between two equal types is permitted. + if (from_type == to_type) + return; + + // Otherwise, this is an error. + throw type_mismatch(to_type, from_type); + } +}; + +// Implementation for array. +template +struct convert_check> +{ + auto check(::ucl_object_t const *from) -> void + { + using To = array; + auto from_type = static_cast(::ucl_object_type(from)); + auto to_type = To::ucl_type; + + // If the source type is not an array, this is an error. + if (from_type != object_type::array) + throw type_mismatch(to_type, from_type); + + for (std::size_t i = 0, size = ::ucl_array_size(from); + i < size; ++i) { + auto const *arr_obj = ::ucl_array_find_index(from, i); + convert_check{}.check(arr_obj); + } + } +}; + +/* + * Convert a UCL object to another type. + */ +export template +auto object_cast(object const &from) -> To +{ + convert_check{}.check(from.get_ucl_object()); + + auto const *uobj = from.get_ucl_object(); + auto *refptr = ::ucl_object_ref(uobj); + return To(refptr); +} + +} // namespace nihil::ucl -- cgit v1.2.3