From 90aa957ca9b7c217af7569009d1675e0f3ff8e9b Mon Sep 17 00:00:00 2001 From: Lexi Winter Date: Thu, 26 Jun 2025 20:47:45 +0100 Subject: ucl, config: use monadic error handling more --- nihil.ucl/object_cast.ccm | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) (limited to 'nihil.ucl/object_cast.ccm') diff --git a/nihil.ucl/object_cast.ccm b/nihil.ucl/object_cast.ccm index b10ffbc..07588a1 100644 --- a/nihil.ucl/object_cast.ccm +++ b/nihil.ucl/object_cast.ccm @@ -4,12 +4,15 @@ module; +#include #include +#include #include export module nihil.ucl:object_cast; +import nihil; import :type; import :object; import :array; @@ -25,21 +28,22 @@ namespace nihil::ucl { template struct convert_check { - auto check(::ucl_object_t const *from) -> void + [[nodiscard]] auto check(::ucl_object_t const *from) + -> std::expected { 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; + return {}; // Converting between two equal types is permitted. if (from_type == to_type) - return; + return {}; // Otherwise, this is an error. - throw type_mismatch(to_type, from_type); + return std::unexpected(type_mismatch(to_type, from_type)); } }; @@ -47,7 +51,8 @@ struct convert_check template struct convert_check> { - auto check(::ucl_object_t const *from) -> void + [[nodiscard]] auto check(::ucl_object_t const *from) + -> std::expected { using To = array; auto from_type = static_cast(::ucl_object_type(from)); @@ -55,13 +60,17 @@ struct convert_check> // 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); + co_return std::unexpected( + 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); + co_await convert_check{} + .check(arr_obj); } + + co_return {}; } }; @@ -69,12 +78,12 @@ struct convert_check> * Convert a UCL object to another type. */ export template -auto object_cast(object const &from) -> To +auto object_cast(object const &from) -> std::expected { auto uobj = from.get_ucl_object(); - convert_check{}.check(uobj); - return To(nihil::ucl::ref, uobj); + co_await convert_check{}.check(uobj); + co_return To(nihil::ucl::ref, uobj); } } // namespace nihil::ucl -- cgit v1.2.3