diff --git a/3rdParty/tl/expected.hpp b/3rdParty/tl/expected.hpp deleted file mode 100644 index 209a44ecf..000000000 --- a/3rdParty/tl/expected.hpp +++ /dev/null @@ -1,2444 +0,0 @@ -/// -// expected - An implementation of std::expected with extensions -// Written in 2017 by Sy Brand (tartanllama@gmail.com, @TartanLlama) -// -// Documentation available at http://tl.tartanllama.xyz/ -// -// To the extent possible under law, the author(s) have dedicated all -// copyright and related and neighboring rights to this software to the -// public domain worldwide. This software is distributed without any warranty. -// -// You should have received a copy of the CC0 Public Domain Dedication -// along with this software. If not, see -// . -/// - -#ifndef TL_EXPECTED_HPP -#define TL_EXPECTED_HPP - -#define TL_EXPECTED_VERSION_MAJOR 1 -#define TL_EXPECTED_VERSION_MINOR 1 -#define TL_EXPECTED_VERSION_PATCH 0 - -#include -#include -#include -#include - -#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) -#define TL_EXPECTED_EXCEPTIONS_ENABLED -#endif - -#if (defined(_MSC_VER) && _MSC_VER == 1900) -#define TL_EXPECTED_MSVC2015 -#define TL_EXPECTED_MSVC2015_CONSTEXPR -#else -#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr -#endif - -#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC49 -#endif - -#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC54 -#endif - -#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC55 -#endif - -#if !defined(TL_ASSERT) -// can't have assert in constexpr in C++11 and GCC 4.9 has a compiler bug -#if (__cplusplus > 201103L) && !defined(TL_EXPECTED_GCC49) -#include -#define TL_ASSERT(x) assert(x) -#else -#define TL_ASSERT(x) -#endif -#endif - -#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ - !defined(__clang__)) -// GCC < 5 doesn't support overloading on const&& for member functions - -#define TL_EXPECTED_NO_CONSTRR -// GCC < 5 doesn't support some standard C++11 type traits -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - std::has_trivial_copy_constructor -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::has_trivial_copy_assign - -// This one will be different for GCC 5.7 if it's ever supported -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible - -// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks -// std::vector for non-copyable types -#elif (defined(__GNUC__) && __GNUC__ < 8 && !defined(__clang__)) -#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX -#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX -namespace tl { -namespace detail { -template -struct is_trivially_copy_constructible - : std::is_trivially_copy_constructible {}; -#ifdef _GLIBCXX_VECTOR -template -struct is_trivially_copy_constructible> : std::false_type {}; -#endif -} // namespace detail -} // namespace tl -#endif - -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - tl::detail::is_trivially_copy_constructible -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::is_trivially_copy_assignable -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible -#else -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - std::is_trivially_copy_constructible -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::is_trivially_copy_assignable -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible -#endif - -#if __cplusplus > 201103L -#define TL_EXPECTED_CXX14 -#endif - -#ifdef TL_EXPECTED_GCC49 -#define TL_EXPECTED_GCC49_CONSTEXPR -#else -#define TL_EXPECTED_GCC49_CONSTEXPR constexpr -#endif - -#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \ - defined(TL_EXPECTED_GCC49)) -#define TL_EXPECTED_11_CONSTEXPR -#else -#define TL_EXPECTED_11_CONSTEXPR constexpr -#endif - -namespace tl { -template class expected; - -#ifndef TL_MONOSTATE_INPLACE_MUTEX -#define TL_MONOSTATE_INPLACE_MUTEX -class monostate {}; - -struct in_place_t { - explicit in_place_t() = default; -}; -static constexpr in_place_t in_place{}; -#endif - -template class unexpected { -public: - static_assert(!std::is_same::value, "E must not be void"); - - unexpected() = delete; - constexpr explicit unexpected(const E &e) : m_val(e) {} - - constexpr explicit unexpected(E &&e) : m_val(std::move(e)) {} - - template ::value>::type * = nullptr> - constexpr explicit unexpected(Args &&...args) - : m_val(std::forward(args)...) {} - template < - class U, class... Args, - typename std::enable_if &, Args &&...>::value>::type * = nullptr> - constexpr explicit unexpected(std::initializer_list l, Args &&...args) - : m_val(l, std::forward(args)...) {} - - constexpr const E &value() const & { return m_val; } - TL_EXPECTED_11_CONSTEXPR E &value() & { return m_val; } - TL_EXPECTED_11_CONSTEXPR E &&value() && { return std::move(m_val); } - constexpr const E &&value() const && { return std::move(m_val); } - -private: - E m_val; -}; - -#ifdef __cpp_deduction_guides -template unexpected(E) -> unexpected; -#endif - -template -constexpr bool operator==(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() == rhs.value(); -} -template -constexpr bool operator!=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() != rhs.value(); -} -template -constexpr bool operator<(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() < rhs.value(); -} -template -constexpr bool operator<=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() <= rhs.value(); -} -template -constexpr bool operator>(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() > rhs.value(); -} -template -constexpr bool operator>=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() >= rhs.value(); -} - -template -unexpected::type> make_unexpected(E &&e) { - return unexpected::type>(std::forward(e)); -} - -struct unexpect_t { - unexpect_t() = default; -}; -static constexpr unexpect_t unexpect{}; - -namespace detail { -template -[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E &&e) { -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - throw std::forward(e); -#else - (void)e; -#ifdef _MSC_VER - __assume(0); -#else - __builtin_unreachable(); -#endif -#endif -} - -#ifndef TL_TRAITS_MUTEX -#define TL_TRAITS_MUTEX -// C++14-style aliases for brevity -template using remove_const_t = typename std::remove_const::type; -template -using remove_reference_t = typename std::remove_reference::type; -template using decay_t = typename std::decay::type; -template -using enable_if_t = typename std::enable_if::type; -template -using conditional_t = typename std::conditional::type; - -// std::conjunction from C++17 -template struct conjunction : std::true_type {}; -template struct conjunction : B {}; -template -struct conjunction - : std::conditional, B>::type {}; - -#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L -#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND -#endif - -// In C++11 mode, there's an issue in libc++'s std::mem_fn -// which results in a hard-error when using it in a noexcept expression -// in some cases. This is a check to workaround the common failing case. -#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND -template -struct is_pointer_to_non_const_member_func : std::false_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; - -template struct is_const_or_const_ref : std::false_type {}; -template struct is_const_or_const_ref : std::true_type {}; -template struct is_const_or_const_ref : std::true_type {}; -#endif - -// std::invoke from C++17 -// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround -template < - typename Fn, typename... Args, -#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND - typename = enable_if_t::value && - is_const_or_const_ref::value)>, -#endif - typename = enable_if_t>::value>, int = 0> -constexpr auto invoke(Fn &&f, Args &&...args) noexcept( - noexcept(std::mem_fn(f)(std::forward(args)...))) - -> decltype(std::mem_fn(f)(std::forward(args)...)) { - return std::mem_fn(f)(std::forward(args)...); -} - -template >::value>> -constexpr auto invoke(Fn &&f, Args &&...args) noexcept( - noexcept(std::forward(f)(std::forward(args)...))) - -> decltype(std::forward(f)(std::forward(args)...)) { - return std::forward(f)(std::forward(args)...); -} - -// std::invoke_result from C++17 -template struct invoke_result_impl; - -template -struct invoke_result_impl< - F, - decltype(detail::invoke(std::declval(), std::declval()...), void()), - Us...> { - using type = - decltype(detail::invoke(std::declval(), std::declval()...)); -}; - -template -using invoke_result = invoke_result_impl; - -template -using invoke_result_t = typename invoke_result::type; - -#if defined(_MSC_VER) && _MSC_VER <= 1900 -// TODO make a version which works with MSVC 2015 -template struct is_swappable : std::true_type {}; - -template struct is_nothrow_swappable : std::true_type {}; -#else -// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept -namespace swap_adl_tests { -// if swap ADL finds this then it would call std::swap otherwise (same -// signature) -struct tag {}; - -template tag swap(T &, T &); -template tag swap(T (&a)[N], T (&b)[N]); - -// helper functions to test if an unqualified swap is possible, and if it -// becomes std::swap -template std::false_type can_swap(...) noexcept(false); -template (), std::declval()))> -std::true_type can_swap(int) noexcept(noexcept(swap(std::declval(), - std::declval()))); - -template std::false_type uses_std(...); -template -std::is_same(), std::declval())), tag> -uses_std(int); - -template -struct is_std_swap_noexcept - : std::integral_constant::value && - std::is_nothrow_move_assignable::value> {}; - -template -struct is_std_swap_noexcept : is_std_swap_noexcept {}; - -template -struct is_adl_swap_noexcept - : std::integral_constant(0))> {}; -} // namespace swap_adl_tests - -template -struct is_swappable - : std::integral_constant< - bool, - decltype(detail::swap_adl_tests::can_swap(0))::value && - (!decltype(detail::swap_adl_tests::uses_std(0))::value || - (std::is_move_assignable::value && - std::is_move_constructible::value))> {}; - -template -struct is_swappable - : std::integral_constant< - bool, - decltype(detail::swap_adl_tests::can_swap(0))::value && - (!decltype(detail::swap_adl_tests::uses_std( - 0))::value || - is_swappable::value)> {}; - -template -struct is_nothrow_swappable - : std::integral_constant< - bool, - is_swappable::value && - ((decltype(detail::swap_adl_tests::uses_std(0))::value && - detail::swap_adl_tests::is_std_swap_noexcept::value) || - (!decltype(detail::swap_adl_tests::uses_std(0))::value && - detail::swap_adl_tests::is_adl_swap_noexcept::value))> {}; -#endif -#endif - -// Trait for checking if a type is a tl::expected -template struct is_expected_impl : std::false_type {}; -template -struct is_expected_impl> : std::true_type {}; -template using is_expected = is_expected_impl>; - -template -using expected_enable_forward_value = detail::enable_if_t< - std::is_constructible::value && - !std::is_same, in_place_t>::value && - !std::is_same, detail::decay_t>::value && - !std::is_same, detail::decay_t>::value>; - -template -using expected_enable_from_other = detail::enable_if_t< - std::is_constructible::value && - std::is_constructible::value && - !std::is_constructible &>::value && - !std::is_constructible &&>::value && - !std::is_constructible &>::value && - !std::is_constructible &&>::value && - !std::is_convertible &, T>::value && - !std::is_convertible &&, T>::value && - !std::is_convertible &, T>::value && - !std::is_convertible &&, T>::value>; - -template -using is_void_or = conditional_t::value, std::true_type, U>; - -template -using is_copy_constructible_or_void = - is_void_or>; - -template -using is_move_constructible_or_void = - is_void_or>; - -template -using is_copy_assignable_or_void = is_void_or>; - -template -using is_move_assignable_or_void = is_void_or>; - -} // namespace detail - -namespace detail { -struct no_init_t {}; -static constexpr no_init_t no_init{}; - -// Implements the storage of the values, and ensures that the destructor is -// trivial if it can be. -// -// This specialization is for where neither `T` or `E` is trivially -// destructible, so the destructors must be called on destruction of the -// `expected` -template ::value, - bool = std::is_trivially_destructible::value> -struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (m_has_val) { - m_val.~T(); - } else { - m_unexpect.~unexpected(); - } - } - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// This specialization is for when both `T` and `E` are trivially-destructible, -// so the destructor of the `expected` can be trivial. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() = default; - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// T is trivial, E is not. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t) - : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (!m_has_val) { - m_unexpect.~unexpected(); - } - } - - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// E is trivial, T is not. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (m_has_val) { - m_val.~T(); - } - } - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// `T` is `void`, `E` is trivially-destructible -template struct expected_storage_base { -#if __GNUC__ <= 5 -// no constexpr for GCC 4/5 bug -#else - TL_EXPECTED_MSVC2015_CONSTEXPR -#endif - expected_storage_base() : m_has_val(true) {} - - constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {} - - constexpr expected_storage_base(in_place_t) : m_has_val(true) {} - - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() = default; - struct dummy {}; - union { - unexpected m_unexpect; - dummy m_val; - }; - bool m_has_val; -}; - -// `T` is `void`, `E` is not trivially-destructible -template struct expected_storage_base { - constexpr expected_storage_base() : m_dummy(), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {} - - constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {} - - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (!m_has_val) { - m_unexpect.~unexpected(); - } - } - - union { - unexpected m_unexpect; - char m_dummy; - }; - bool m_has_val; -}; - -// This base class provides some handy member functions which can be used in -// further derived classes -template -struct expected_operations_base : expected_storage_base { - using expected_storage_base::expected_storage_base; - - template void construct(Args &&...args) noexcept { - new (std::addressof(this->m_val)) T(std::forward(args)...); - this->m_has_val = true; - } - - template void construct_with(Rhs &&rhs) noexcept { - new (std::addressof(this->m_val)) T(std::forward(rhs).get()); - this->m_has_val = true; - } - - template void construct_error(Args &&...args) noexcept { - new (std::addressof(this->m_unexpect)) - unexpected(std::forward(args)...); - this->m_has_val = false; - } - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - - // These assign overloads ensure that the most efficient assignment - // implementation is used while maintaining the strong exception guarantee. - // The problematic case is where rhs has a value, but *this does not. - // - // This overload handles the case where we can just copy-construct `T` - // directly into place without throwing. - template ::value> - * = nullptr> - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(rhs.get()); - } else { - assign_common(rhs); - } - } - - // This overload handles the case where we can attempt to create a copy of - // `T`, then no-throw move it into place if the copy was successful. - template ::value && - std::is_nothrow_move_constructible::value> - * = nullptr> - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - T tmp = rhs.get(); - geterr().~unexpected(); - construct(std::move(tmp)); - } else { - assign_common(rhs); - } - } - - // This overload is the worst-case, where we have to move-construct the - // unexpected value into temporary storage, then try to copy the T into place. - // If the construction succeeds, then everything is fine, but if it throws, - // then we move the old unexpected value back into place before rethrowing the - // exception. - template ::value && - !std::is_nothrow_move_constructible::value> - * = nullptr> - void assign(const expected_operations_base &rhs) { - if (!this->m_has_val && rhs.m_has_val) { - auto tmp = std::move(geterr()); - geterr().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - construct(rhs.get()); - } catch (...) { - geterr() = std::move(tmp); - throw; - } -#else - construct(rhs.get()); -#endif - } else { - assign_common(rhs); - } - } - - // These overloads do the same as above, but for rvalues - template ::value> - * = nullptr> - void assign(expected_operations_base &&rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(std::move(rhs).get()); - } else { - assign_common(std::move(rhs)); - } - } - - template ::value> - * = nullptr> - void assign(expected_operations_base &&rhs) { - if (!this->m_has_val && rhs.m_has_val) { - auto tmp = std::move(geterr()); - geterr().~unexpected(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - construct(std::move(rhs).get()); - } catch (...) { - geterr() = std::move(tmp); - throw; - } -#else - construct(std::move(rhs).get()); -#endif - } else { - assign_common(std::move(rhs)); - } - } - -#else - - // If exceptions are disabled then we can just copy-construct - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(rhs.get()); - } else { - assign_common(rhs); - } - } - - void assign(expected_operations_base &&rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(std::move(rhs).get()); - } else { - assign_common(std::move(rhs)); - } - } - -#endif - - // The common part of move/copy assigning - template void assign_common(Rhs &&rhs) { - if (this->m_has_val) { - if (rhs.m_has_val) { - get() = std::forward(rhs).get(); - } else { - destroy_val(); - construct_error(std::forward(rhs).geterr()); - } - } else { - if (!rhs.m_has_val) { - geterr() = std::forward(rhs).geterr(); - } - } - } - - bool has_value() const { return this->m_has_val; } - - TL_EXPECTED_11_CONSTEXPR T &get() & { return this->m_val; } - constexpr const T &get() const & { return this->m_val; } - TL_EXPECTED_11_CONSTEXPR T &&get() && { return std::move(this->m_val); } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const T &&get() const && { return std::move(this->m_val); } -#endif - - TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { - return this->m_unexpect; - } - constexpr const unexpected &geterr() const & { return this->m_unexpect; } - TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { - return std::move(this->m_unexpect); - } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const unexpected &&geterr() const && { - return std::move(this->m_unexpect); - } -#endif - - TL_EXPECTED_11_CONSTEXPR void destroy_val() { get().~T(); } -}; - -// This base class provides some handy member functions which can be used in -// further derived classes -template -struct expected_operations_base : expected_storage_base { - using expected_storage_base::expected_storage_base; - - template void construct() noexcept { this->m_has_val = true; } - - // This function doesn't use its argument, but needs it so that code in - // levels above this can work independently of whether T is void - template void construct_with(Rhs &&) noexcept { - this->m_has_val = true; - } - - template void construct_error(Args &&...args) noexcept { - new (std::addressof(this->m_unexpect)) - unexpected(std::forward(args)...); - this->m_has_val = false; - } - - template void assign(Rhs &&rhs) noexcept { - if (!this->m_has_val) { - if (rhs.m_has_val) { - geterr().~unexpected(); - construct(); - } else { - geterr() = std::forward(rhs).geterr(); - } - } else { - if (!rhs.m_has_val) { - construct_error(std::forward(rhs).geterr()); - } - } - } - - bool has_value() const { return this->m_has_val; } - - TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { - return this->m_unexpect; - } - constexpr const unexpected &geterr() const & { return this->m_unexpect; } - TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { - return std::move(this->m_unexpect); - } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const unexpected &&geterr() const && { - return std::move(this->m_unexpect); - } -#endif - - TL_EXPECTED_11_CONSTEXPR void destroy_val() { - // no-op - } -}; - -// This class manages conditionally having a trivial copy constructor -// This specialization is for when T and E are trivially copy constructible -template :: - value &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value> -struct expected_copy_base : expected_operations_base { - using expected_operations_base::expected_operations_base; -}; - -// This specialization is for when T or E are not trivially copy constructible -template -struct expected_copy_base : expected_operations_base { - using expected_operations_base::expected_operations_base; - - expected_copy_base() = default; - expected_copy_base(const expected_copy_base &rhs) - : expected_operations_base(no_init) { - if (rhs.has_value()) { - this->construct_with(rhs); - } else { - this->construct_error(rhs.geterr()); - } - } - - expected_copy_base(expected_copy_base &&rhs) = default; - expected_copy_base &operator=(const expected_copy_base &rhs) = default; - expected_copy_base &operator=(expected_copy_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial move constructor -// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it -// doesn't implement an analogue to std::is_trivially_move_constructible. We -// have to make do with a non-trivial move constructor even if T is trivially -// move constructible -#ifndef TL_EXPECTED_GCC49 -template >::value - &&std::is_trivially_move_constructible::value> -struct expected_move_base : expected_copy_base { - using expected_copy_base::expected_copy_base; -}; -#else -template struct expected_move_base; -#endif -template -struct expected_move_base : expected_copy_base { - using expected_copy_base::expected_copy_base; - - expected_move_base() = default; - expected_move_base(const expected_move_base &rhs) = default; - - expected_move_base(expected_move_base &&rhs) noexcept( - std::is_nothrow_move_constructible::value) - : expected_copy_base(no_init) { - if (rhs.has_value()) { - this->construct_with(std::move(rhs)); - } else { - this->construct_error(std::move(rhs.geterr())); - } - } - expected_move_base &operator=(const expected_move_base &rhs) = default; - expected_move_base &operator=(expected_move_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial copy assignment operator -template >::value - &&TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value - &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value - &&TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value> -struct expected_copy_assign_base : expected_move_base { - using expected_move_base::expected_move_base; -}; - -template -struct expected_copy_assign_base : expected_move_base { - using expected_move_base::expected_move_base; - - expected_copy_assign_base() = default; - expected_copy_assign_base(const expected_copy_assign_base &rhs) = default; - - expected_copy_assign_base(expected_copy_assign_base &&rhs) = default; - expected_copy_assign_base &operator=(const expected_copy_assign_base &rhs) { - this->assign(rhs); - return *this; - } - expected_copy_assign_base & - operator=(expected_copy_assign_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial move assignment operator -// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it -// doesn't implement an analogue to std::is_trivially_move_assignable. We have -// to make do with a non-trivial move assignment operator even if T is trivially -// move assignable -#ifndef TL_EXPECTED_GCC49 -template , - std::is_trivially_move_constructible, - std::is_trivially_move_assignable>>:: - value &&std::is_trivially_destructible::value - &&std::is_trivially_move_constructible::value - &&std::is_trivially_move_assignable::value> -struct expected_move_assign_base : expected_copy_assign_base { - using expected_copy_assign_base::expected_copy_assign_base; -}; -#else -template struct expected_move_assign_base; -#endif - -template -struct expected_move_assign_base - : expected_copy_assign_base { - using expected_copy_assign_base::expected_copy_assign_base; - - expected_move_assign_base() = default; - expected_move_assign_base(const expected_move_assign_base &rhs) = default; - - expected_move_assign_base(expected_move_assign_base &&rhs) = default; - - expected_move_assign_base & - operator=(const expected_move_assign_base &rhs) = default; - - expected_move_assign_base & - operator=(expected_move_assign_base &&rhs) noexcept( - std::is_nothrow_move_constructible::value - &&std::is_nothrow_move_assignable::value) { - this->assign(std::move(rhs)); - return *this; - } -}; - -// expected_delete_ctor_base will conditionally delete copy and move -// constructors depending on whether T is copy/move constructible -template ::value && - std::is_copy_constructible::value), - bool EnableMove = (is_move_constructible_or_void::value && - std::is_move_constructible::value)> -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -// expected_delete_assign_base will conditionally delete copy and move -// constructors depending on whether T and E are copy/move constructible + -// assignable -template ::value && - std::is_copy_constructible::value && - is_copy_assignable_or_void::value && - std::is_copy_assignable::value), - bool EnableMove = (is_move_constructible_or_void::value && - std::is_move_constructible::value && - is_move_assignable_or_void::value && - std::is_move_assignable::value)> -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = default; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = default; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = default; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = delete; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = delete; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = default; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = delete; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = delete; -}; - -// This is needed to be able to construct the expected_default_ctor_base which -// follows, while still conditionally deleting the default constructor. -struct default_constructor_tag { - explicit constexpr default_constructor_tag() = default; -}; - -// expected_default_ctor_base will ensure that expected has a deleted default -// consturctor if T is not default constructible. -// This specialization is for when T is default constructible -template ::value || std::is_void::value> -struct expected_default_ctor_base { - constexpr expected_default_ctor_base() noexcept = default; - constexpr expected_default_ctor_base( - expected_default_ctor_base const &) noexcept = default; - constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = - default; - expected_default_ctor_base & - operator=(expected_default_ctor_base const &) noexcept = default; - expected_default_ctor_base & - operator=(expected_default_ctor_base &&) noexcept = default; - - constexpr explicit expected_default_ctor_base(default_constructor_tag) {} -}; - -// This specialization is for when T is not default constructible -template struct expected_default_ctor_base { - constexpr expected_default_ctor_base() noexcept = delete; - constexpr expected_default_ctor_base( - expected_default_ctor_base const &) noexcept = default; - constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = - default; - expected_default_ctor_base & - operator=(expected_default_ctor_base const &) noexcept = default; - expected_default_ctor_base & - operator=(expected_default_ctor_base &&) noexcept = default; - - constexpr explicit expected_default_ctor_base(default_constructor_tag) {} -}; -} // namespace detail - -template class bad_expected_access : public std::exception { -public: - explicit bad_expected_access(E e) : m_val(std::move(e)) {} - - virtual const char *what() const noexcept override { - return "Bad expected access"; - } - - const E &error() const & { return m_val; } - E &error() & { return m_val; } - const E &&error() const && { return std::move(m_val); } - E &&error() && { return std::move(m_val); } - -private: - E m_val; -}; - -/// An `expected` object is an object that contains the storage for -/// another object and manages the lifetime of this contained object `T`. -/// Alternatively it could contain the storage for another unexpected object -/// `E`. The contained object may not be initialized after the expected object -/// has been initialized, and may not be destroyed before the expected object -/// has been destroyed. The initialization state of the contained object is -/// tracked by the expected object. -template -class expected : private detail::expected_move_assign_base, - private detail::expected_delete_ctor_base, - private detail::expected_delete_assign_base, - private detail::expected_default_ctor_base { - static_assert(!std::is_reference::value, "T must not be a reference"); - static_assert(!std::is_same::type>::value, - "T must not be in_place_t"); - static_assert(!std::is_same::type>::value, - "T must not be unexpect_t"); - static_assert( - !std::is_same>::type>::value, - "T must not be unexpected"); - static_assert(!std::is_reference::value, "E must not be a reference"); - - T *valptr() { return std::addressof(this->m_val); } - const T *valptr() const { return std::addressof(this->m_val); } - unexpected *errptr() { return std::addressof(this->m_unexpect); } - const unexpected *errptr() const { - return std::addressof(this->m_unexpect); - } - - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &val() { - return this->m_val; - } - TL_EXPECTED_11_CONSTEXPR unexpected &err() { return this->m_unexpect; } - - template ::value> * = nullptr> - constexpr const U &val() const { - return this->m_val; - } - constexpr const unexpected &err() const { return this->m_unexpect; } - - using impl_base = detail::expected_move_assign_base; - using ctor_base = detail::expected_default_ctor_base; - -public: - typedef T value_type; - typedef E error_type; - typedef unexpected unexpected_type; - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) & { - return and_then_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) && { - return and_then_impl(std::move(*this), std::forward(f)); - } - template constexpr auto and_then(F &&f) const & { - return and_then_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template constexpr auto and_then(F &&f) const && { - return and_then_impl(std::move(*this), std::forward(f)); - } -#endif - -#else - template - TL_EXPECTED_11_CONSTEXPR auto - and_then(F &&f) & -> decltype(and_then_impl(std::declval(), - std::forward(f))) { - return and_then_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR auto - and_then(F &&f) && -> decltype(and_then_impl(std::declval(), - std::forward(f))) { - return and_then_impl(std::move(*this), std::forward(f)); - } - template - constexpr auto and_then(F &&f) const & -> decltype(and_then_impl( - std::declval(), std::forward(f))) { - return and_then_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr auto and_then(F &&f) const && -> decltype(and_then_impl( - std::declval(), std::forward(f))) { - return and_then_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template constexpr auto map(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - template constexpr auto map(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( - std::declval(), std::declval())) - map(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template constexpr auto transform(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - template constexpr auto transform(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( - std::declval(), std::declval())) - transform(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template constexpr auto map_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - template constexpr auto map_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#endif -#endif -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template constexpr auto transform_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - template constexpr auto transform_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) & { - return or_else_impl(*this, std::forward(f)); - } - - template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) && { - return or_else_impl(std::move(*this), std::forward(f)); - } - - template expected constexpr or_else(F &&f) const & { - return or_else_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template expected constexpr or_else(F &&f) const && { - return or_else_impl(std::move(*this), std::forward(f)); - } -#endif - constexpr expected() = default; - constexpr expected(const expected &rhs) = default; - constexpr expected(expected &&rhs) = default; - expected &operator=(const expected &rhs) = default; - expected &operator=(expected &&rhs) = default; - - template ::value> * = - nullptr> - constexpr expected(in_place_t, Args &&...args) - : impl_base(in_place, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected(in_place_t, std::initializer_list il, Args &&...args) - : impl_base(in_place, il, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value> * = - nullptr, - detail::enable_if_t::value> * = - nullptr> - explicit constexpr expected(const unexpected &e) - : impl_base(unexpect, e.value()), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr> - constexpr expected(unexpected const &e) - : impl_base(unexpect, e.value()), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t::value> * = nullptr> - explicit constexpr expected(unexpected &&e) noexcept( - std::is_nothrow_constructible::value) - : impl_base(unexpect, std::move(e.value())), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t::value> * = nullptr> - constexpr expected(unexpected &&e) noexcept( - std::is_nothrow_constructible::value) - : impl_base(unexpect, std::move(e.value())), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value> * = - nullptr> - constexpr explicit expected(unexpect_t, Args &&...args) - : impl_base(unexpect, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected(unexpect_t, std::initializer_list il, - Args &&...args) - : impl_base(unexpect, il, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value && - std::is_convertible::value)> * = - nullptr, - detail::expected_enable_from_other - * = nullptr> - explicit TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(*rhs); - } else { - this->construct_error(rhs.error()); - } - } - - template ::value && - std::is_convertible::value)> * = - nullptr, - detail::expected_enable_from_other - * = nullptr> - TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(*rhs); - } else { - this->construct_error(rhs.error()); - } - } - - template < - class U, class G, - detail::enable_if_t::value && - std::is_convertible::value)> * = nullptr, - detail::expected_enable_from_other * = nullptr> - explicit TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(std::move(*rhs)); - } else { - this->construct_error(std::move(rhs.error())); - } - } - - template < - class U, class G, - detail::enable_if_t<(std::is_convertible::value && - std::is_convertible::value)> * = nullptr, - detail::expected_enable_from_other * = nullptr> - TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(std::move(*rhs)); - } else { - this->construct_error(std::move(rhs.error())); - } - } - - template < - class U = T, - detail::enable_if_t::value> * = nullptr, - detail::expected_enable_forward_value * = nullptr> - explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) - : expected(in_place, std::forward(v)) {} - - template < - class U = T, - detail::enable_if_t::value> * = nullptr, - detail::expected_enable_forward_value * = nullptr> - TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) - : expected(in_place, std::forward(v)) {} - - template < - class U = T, class G = T, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t< - (!std::is_same, detail::decay_t>::value && - !detail::conjunction, - std::is_same>>::value && - std::is_constructible::value && - std::is_assignable::value && - std::is_nothrow_move_constructible::value)> * = nullptr> - expected &operator=(U &&v) { - if (has_value()) { - val() = std::forward(v); - } else { - err().~unexpected(); - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; - } - - return *this; - } - - template < - class U = T, class G = T, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t< - (!std::is_same, detail::decay_t>::value && - !detail::conjunction, - std::is_same>>::value && - std::is_constructible::value && - std::is_assignable::value && - std::is_nothrow_move_constructible::value)> * = nullptr> - expected &operator=(U &&v) { - if (has_value()) { - val() = std::forward(v); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; -#endif - } - - return *this; - } - - template ::value && - std::is_assignable::value> * = nullptr> - expected &operator=(const unexpected &rhs) { - if (!has_value()) { - err() = rhs; - } else { - this->destroy_val(); - ::new (errptr()) unexpected(rhs); - this->m_has_val = false; - } - - return *this; - } - - template ::value && - std::is_move_assignable::value> * = nullptr> - expected &operator=(unexpected &&rhs) noexcept { - if (!has_value()) { - err() = std::move(rhs); - } else { - this->destroy_val(); - ::new (errptr()) unexpected(std::move(rhs)); - this->m_has_val = false; - } - - return *this; - } - - template ::value> * = nullptr> - void emplace(Args &&...args) { - if (has_value()) { - val().~T(); - } else { - err().~unexpected(); - this->m_has_val = true; - } - ::new (valptr()) T(std::forward(args)...); - } - - template ::value> * = nullptr> - void emplace(Args &&...args) { - if (has_value()) { - val().~T(); - ::new (valptr()) T(std::forward(args)...); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(std::forward(args)...); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(std::forward(args)...); - this->m_has_val = true; -#endif - } - } - - template &, Args &&...>::value> * = nullptr> - void emplace(std::initializer_list il, Args &&...args) { - if (has_value()) { - T t(il, std::forward(args)...); - val() = std::move(t); - } else { - err().~unexpected(); - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; - } - } - - template &, Args &&...>::value> * = nullptr> - void emplace(std::initializer_list il, Args &&...args) { - if (has_value()) { - T t(il, std::forward(args)...); - val() = std::move(t); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; -#endif - } - } - -private: - using t_is_void = std::true_type; - using t_is_not_void = std::false_type; - using t_is_nothrow_move_constructible = std::true_type; - using move_constructing_t_can_throw = std::false_type; - using e_is_nothrow_move_constructible = std::true_type; - using move_constructing_e_can_throw = std::false_type; - - void swap_where_both_have_value(expected & /*rhs*/, t_is_void) noexcept { - // swapping void is a no-op - } - - void swap_where_both_have_value(expected &rhs, t_is_not_void) { - using std::swap; - swap(val(), rhs.val()); - } - - void swap_where_only_one_has_value(expected &rhs, t_is_void) noexcept( - std::is_nothrow_move_constructible::value) { - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - std::swap(this->m_has_val, rhs.m_has_val); - } - - void swap_where_only_one_has_value(expected &rhs, t_is_not_void) { - swap_where_only_one_has_value_and_t_is_not_void( - rhs, typename std::is_nothrow_move_constructible::type{}, - typename std::is_nothrow_move_constructible::type{}); - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, t_is_nothrow_move_constructible, - e_is_nothrow_move_constructible) noexcept { - auto temp = std::move(val()); - val().~T(); - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, t_is_nothrow_move_constructible, - move_constructing_e_can_throw) { - auto temp = std::move(val()); - val().~T(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } catch (...) { - val() = std::move(temp); - throw; - } -#else - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); -#endif - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, move_constructing_t_can_throw, - e_is_nothrow_move_constructible) { - auto temp = std::move(rhs.err()); - rhs.err().~unexpected_type(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (rhs.valptr()) T(std::move(val())); - val().~T(); - ::new (errptr()) unexpected_type(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } catch (...) { - rhs.err() = std::move(temp); - throw; - } -#else - ::new (rhs.valptr()) T(std::move(val())); - val().~T(); - ::new (errptr()) unexpected_type(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); -#endif - } - -public: - template - detail::enable_if_t::value && - detail::is_swappable::value && - (std::is_nothrow_move_constructible::value || - std::is_nothrow_move_constructible::value)> - swap(expected &rhs) noexcept( - std::is_nothrow_move_constructible::value - &&detail::is_nothrow_swappable::value - &&std::is_nothrow_move_constructible::value - &&detail::is_nothrow_swappable::value) { - if (has_value() && rhs.has_value()) { - swap_where_both_have_value(rhs, typename std::is_void::type{}); - } else if (!has_value() && rhs.has_value()) { - rhs.swap(*this); - } else if (has_value()) { - swap_where_only_one_has_value(rhs, typename std::is_void::type{}); - } else { - using std::swap; - swap(err(), rhs.err()); - } - } - - constexpr const T *operator->() const { - TL_ASSERT(has_value()); - return valptr(); - } - TL_EXPECTED_11_CONSTEXPR T *operator->() { - TL_ASSERT(has_value()); - return valptr(); - } - - template ::value> * = nullptr> - constexpr const U &operator*() const & { - TL_ASSERT(has_value()); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &operator*() & { - TL_ASSERT(has_value()); - return val(); - } - template ::value> * = nullptr> - constexpr const U &&operator*() const && { - TL_ASSERT(has_value()); - return std::move(val()); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &&operator*() && { - TL_ASSERT(has_value()); - return std::move(val()); - } - - constexpr bool has_value() const noexcept { return this->m_has_val; } - constexpr explicit operator bool() const noexcept { return this->m_has_val; } - - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR const U &value() const & { - if (!has_value()) - detail::throw_exception(bad_expected_access(err().value())); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &value() & { - if (!has_value()) - detail::throw_exception(bad_expected_access(err().value())); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR const U &&value() const && { - if (!has_value()) - detail::throw_exception(bad_expected_access(std::move(err()).value())); - return std::move(val()); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &&value() && { - if (!has_value()) - detail::throw_exception(bad_expected_access(std::move(err()).value())); - return std::move(val()); - } - - constexpr const E &error() const & { - TL_ASSERT(!has_value()); - return err().value(); - } - TL_EXPECTED_11_CONSTEXPR E &error() & { - TL_ASSERT(!has_value()); - return err().value(); - } - constexpr const E &&error() const && { - TL_ASSERT(!has_value()); - return std::move(err().value()); - } - TL_EXPECTED_11_CONSTEXPR E &&error() && { - TL_ASSERT(!has_value()); - return std::move(err().value()); - } - - template constexpr T value_or(U &&v) const & { - static_assert(std::is_copy_constructible::value && - std::is_convertible::value, - "T must be copy-constructible and convertible to from U&&"); - return bool(*this) ? **this : static_cast(std::forward(v)); - } - template TL_EXPECTED_11_CONSTEXPR T value_or(U &&v) && { - static_assert(std::is_move_constructible::value && - std::is_convertible::value, - "T must be move-constructible and convertible to from U&&"); - return bool(*this) ? std::move(**this) : static_cast(std::forward(v)); - } -}; - -namespace detail { -template using exp_t = typename detail::decay_t::value_type; -template using err_t = typename detail::decay_t::error_type; -template using ret_t = expected>; - -#ifdef TL_EXPECTED_CXX14 -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval()))> -constexpr auto and_then_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() - ? detail::invoke(std::forward(f), *std::forward(exp)) - : Ret(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval()))> -constexpr auto and_then_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() ? detail::invoke(std::forward(f)) - : Ret(unexpect, std::forward(exp).error()); -} -#else -template struct TC; -template (), - *std::declval())), - detail::enable_if_t>::value> * = nullptr> -auto and_then_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() - ? detail::invoke(std::forward(f), *std::forward(exp)) - : Ret(unexpect, std::forward(exp).error()); -} - -template ())), - detail::enable_if_t>::value> * = nullptr> -constexpr auto and_then_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() ? detail::invoke(std::forward(f)) - : Ret(unexpect, std::forward(exp).error()); -} -#endif - -#ifdef TL_EXPECTED_CXX14 -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> -constexpr auto expected_map_impl(Exp &&exp, F &&f) { - using result = ret_t>; - return exp.has_value() ? result(detail::invoke(std::forward(f), - *std::forward(exp))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> -auto expected_map_impl(Exp &&exp, F &&f) { - using result = expected>; - if (exp.has_value()) { - detail::invoke(std::forward(f), *std::forward(exp)); - return result(); - } - - return result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> -constexpr auto expected_map_impl(Exp &&exp, F &&f) { - using result = ret_t>; - return exp.has_value() ? result(detail::invoke(std::forward(f))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> -auto expected_map_impl(Exp &&exp, F &&f) { - using result = expected>; - if (exp.has_value()) { - detail::invoke(std::forward(f)); - return result(); - } - - return result(unexpect, std::forward(exp).error()); -} -#else -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> - -constexpr auto expected_map_impl(Exp &&exp, F &&f) - -> ret_t> { - using result = ret_t>; - - return exp.has_value() ? result(detail::invoke(std::forward(f), - *std::forward(exp))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> - -auto expected_map_impl(Exp &&exp, F &&f) -> expected> { - if (exp.has_value()) { - detail::invoke(std::forward(f), *std::forward(exp)); - return {}; - } - - return unexpected>(std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> - -constexpr auto expected_map_impl(Exp &&exp, F &&f) - -> ret_t> { - using result = ret_t>; - - return exp.has_value() ? result(detail::invoke(std::forward(f))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> - -auto expected_map_impl(Exp &&exp, F &&f) -> expected> { - if (exp.has_value()) { - detail::invoke(std::forward(f)); - return {}; - } - - return unexpected>(std::forward(exp).error()); -} -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, detail::decay_t>; - return exp.has_value() - ? result(*std::forward(exp)) - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, monostate>; - if (exp.has_value()) { - return result(*std::forward(exp)); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, detail::decay_t>; - return exp.has_value() - ? result() - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, monostate>; - if (exp.has_value()) { - return result(); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -#else -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) - -> expected, detail::decay_t> { - using result = expected, detail::decay_t>; - - return exp.has_value() - ? result(*std::forward(exp)) - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { - using result = expected, monostate>; - if (exp.has_value()) { - return result(*std::forward(exp)); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) - -> expected, detail::decay_t> { - using result = expected, detail::decay_t>; - - return exp.has_value() - ? result() - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { - using result = expected, monostate>; - if (exp.has_value()) { - return result(); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -#endif - -#ifdef TL_EXPECTED_CXX14 -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto or_else_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - return exp.has_value() ? std::forward(exp) - : detail::invoke(std::forward(f), - std::forward(exp).error()); -} - -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -detail::decay_t or_else_impl(Exp &&exp, F &&f) { - return exp.has_value() ? std::forward(exp) - : (detail::invoke(std::forward(f), - std::forward(exp).error()), - std::forward(exp)); -} -#else -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto or_else_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - return exp.has_value() ? std::forward(exp) - : detail::invoke(std::forward(f), - std::forward(exp).error()); -} - -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -detail::decay_t or_else_impl(Exp &&exp, F &&f) { - return exp.has_value() ? std::forward(exp) - : (detail::invoke(std::forward(f), - std::forward(exp).error()), - std::forward(exp)); -} -#endif -} // namespace detail - -template -constexpr bool operator==(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? false - : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs); -} -template -constexpr bool operator!=(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? true - : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs); -} -template -constexpr bool operator==(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? false - : (!lhs.has_value() ? lhs.error() == rhs.error() : true); -} -template -constexpr bool operator!=(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? true - : (!lhs.has_value() ? lhs.error() == rhs.error() : false); -} - -template -constexpr bool operator==(const expected &x, const U &v) { - return x.has_value() ? *x == v : false; -} -template -constexpr bool operator==(const U &v, const expected &x) { - return x.has_value() ? *x == v : false; -} -template -constexpr bool operator!=(const expected &x, const U &v) { - return x.has_value() ? *x != v : true; -} -template -constexpr bool operator!=(const U &v, const expected &x) { - return x.has_value() ? *x != v : true; -} - -template -constexpr bool operator==(const expected &x, const unexpected &e) { - return x.has_value() ? false : x.error() == e.value(); -} -template -constexpr bool operator==(const unexpected &e, const expected &x) { - return x.has_value() ? false : x.error() == e.value(); -} -template -constexpr bool operator!=(const expected &x, const unexpected &e) { - return x.has_value() ? true : x.error() != e.value(); -} -template -constexpr bool operator!=(const unexpected &e, const expected &x) { - return x.has_value() ? true : x.error() != e.value(); -} - -template ::value || - std::is_move_constructible::value) && - detail::is_swappable::value && - std::is_move_constructible::value && - detail::is_swappable::value> * = nullptr> -void swap(expected &lhs, - expected &rhs) noexcept(noexcept(lhs.swap(rhs))) { - lhs.swap(rhs); -} -} // namespace tl - -#endif diff --git a/Source/capture.cpp b/Source/capture.cpp index 3904f901c..f36f02bef 100644 --- a/Source/capture.cpp +++ b/Source/capture.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #ifdef USE_SDL3 #include @@ -19,8 +20,6 @@ #include "utils/sdl_compat.h" #endif -#include - #define DEVILUTIONX_SCREENSHOT_FORMAT_PCX 0 #define DEVILUTIONX_SCREENSHOT_FORMAT_PNG 1 @@ -102,7 +101,7 @@ void CaptureScreen() system_palette = origSystemPalette; SystemPaletteUpdated(); - const tl::expected result = + const std::expected result = #if DEVILUTIONX_SCREENSHOT_FORMAT == DEVILUTIONX_SCREENSHOT_FORMAT_PCX WriteSurfaceToFilePcx(GlobalBackBuffer(), outStream); #elif DEVILUTIONX_SCREENSHOT_FORMAT == DEVILUTIONX_SCREENSHOT_FORMAT_PNG diff --git a/Source/control/control.hpp b/Source/control/control.hpp index d5827c5c3..b1e720607 100644 --- a/Source/control/control.hpp +++ b/Source/control/control.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -18,8 +19,6 @@ #endif #endif -#include - #include "DiabloUI/text_input.hpp" #include "DiabloUI/ui_flags.hpp" #include "engine/displacement.hpp" @@ -94,7 +93,7 @@ void AddInfoBoxString(std::string &&str, bool floatingBox = false); void DrawPanelBox(const Surface &out, SDL_Rect srcRect, Point targetPosition); Point GetPanelPosition(UiPanels panel, Point offset = { 0, 0 }); -tl::expected InitMainPanel(); +std::expected InitMainPanel(); void DrawMainPanel(const Surface &out); /** diff --git a/Source/control/control_panel.cpp b/Source/control/control_panel.cpp index 07e6523e1..a4a15f714 100644 --- a/Source/control/control_panel.cpp +++ b/Source/control/control_panel.cpp @@ -353,7 +353,7 @@ void DrawPanelBox(const Surface &out, SDL_Rect srcRect, Point targetPosition) out.BlitFrom(*BottomBuffer, srcRect, targetPosition); } -tl::expected InitMainPanel() +std::expected InitMainPanel() { if (!HeadlessMode) { BottomBuffer.emplace(GetMainPanel().size.width, (GetMainPanel().size.height + PanelPaddingHeight) * (IsChatAvailable() ? 2 : 1)); diff --git a/Source/data/file.cpp b/Source/data/file.cpp index 733fcad43..b5845d50c 100644 --- a/Source/data/file.cpp +++ b/Source/data/file.cpp @@ -3,10 +3,10 @@ #include #include #include +#include #include #include -#include #include #include "engine/assets.hpp" @@ -14,27 +14,27 @@ #include "utils/language.h" namespace devilution { -tl::expected DataFile::load(std::string_view path) +std::expected DataFile::load(std::string_view path) { AssetRef ref = FindAsset(path); if (!ref.ok()) - return tl::unexpected { Error::NotFound }; + return std::unexpected { Error::NotFound }; const size_t size = ref.size(); // TODO: It should be possible to stream the data file contents instead of copying the whole thing into memory std::unique_ptr data { new char[size] }; { AssetHandle handle = OpenIntegralAsset(std::move(ref)); if (!handle.ok()) - return tl::unexpected { Error::OpenFailed }; + return std::unexpected { Error::OpenFailed }; if (size > 0 && !handle.read(data.get(), size)) - return tl::unexpected { Error::BadRead }; + return std::unexpected { Error::BadRead }; } return DataFile { std::move(data), size }; } DataFile DataFile::loadOrDie(std::string_view path) { - tl::expected dataFileResult = DataFile::load(path); + std::expected dataFileResult = DataFile::load(path); if (!dataFileResult.has_value()) { DataFile::reportFatalError(dataFileResult.error(), path); } @@ -92,7 +92,7 @@ void DataFile::reportFatalFieldError(DataFileField::Error code, std::string_view } } -tl::expected DataFile::parseHeader(ColumnDefinition *begin, ColumnDefinition *end, tl::function_ref(std::string_view)> mapper) +std::expected DataFile::parseHeader(ColumnDefinition *begin, ColumnDefinition *end, tl::function_ref(std::string_view)> mapper) { std::bitset::max()> seenColumns; unsigned lastColumn = 0; @@ -129,23 +129,23 @@ tl::expected DataFile::parseHeader(ColumnDefinition *begi // Incrementing the iterator causes it to read to the end of the record in case we broke early (maybe there were extra columns) ++firstRecord; if (firstRecord == this->end()) { - return tl::unexpected { Error::NoContent }; + return std::unexpected { Error::NoContent }; } body_ = firstRecord.data(); if (begin != end) { - return tl::unexpected { Error::NotEnoughColumns }; + return std::unexpected { Error::NotEnoughColumns }; } return {}; } -tl::expected DataFile::skipHeader() +std::expected DataFile::skipHeader() { RecordIterator it { data(), data() + size(), false }; ++it; if (it == this->end()) { - return tl::unexpected { Error::NoContent }; + return std::unexpected { Error::NoContent }; } body_ = it.data(); return {}; @@ -153,7 +153,7 @@ tl::expected DataFile::skipHeader() void DataFile::skipHeaderOrDie(std::string_view path) { - if (tl::expected result = skipHeader(); !result.has_value()) { + if (std::expected result = skipHeader(); !result.has_value()) { DataFile::reportFatalError(result.error(), path); } } diff --git a/Source/data/file.hpp b/Source/data/file.hpp index 4bbad2689..d74459f80 100644 --- a/Source/data/file.hpp +++ b/Source/data/file.hpp @@ -1,11 +1,11 @@ #pragma once #include +#include #include #include #include -#include #include #include "iterators.hpp" @@ -74,7 +74,7 @@ public: * @return an object containing an owned pointer to an in-memory copy of the file * or an error code describing the reason for failure. */ - static tl::expected load(std::string_view path); + static std::expected load(std::string_view path); static DataFile loadOrDie(std::string_view path); @@ -95,7 +95,7 @@ public: * @param mapper Function that maps from a string_view to a unique numeric identifier for the column * @return If the file ends after the header or not enough columns were defined this function returns an error code describing the failure. */ - [[nodiscard]] tl::expected parseHeader(ColumnDefinition *begin, ColumnDefinition *end, tl::function_ref(std::string_view)> mapper); + [[nodiscard]] std::expected parseHeader(ColumnDefinition *begin, ColumnDefinition *end, tl::function_ref(std::string_view)> mapper); /** * @brief Templated version of parseHeader(uint8_t) to allow using directly with enum definitions of columns @@ -106,12 +106,12 @@ public: * @return A void success result or an error code as described above */ template - [[nodiscard]] tl::expected parseHeader(ColumnDefinition *begin, ColumnDefinition *end, std::function(std::string_view)> typedMapper) + [[nodiscard]] std::expected parseHeader(ColumnDefinition *begin, ColumnDefinition *end, std::function(std::string_view)> typedMapper) { return parseHeader(begin, end, [typedMapper](std::string_view label) { return typedMapper(label).transform([](T value) { return static_cast(value); }); }); } - [[nodiscard]] tl::expected skipHeader(); + [[nodiscard]] std::expected skipHeader(); void skipHeaderOrDie(std::string_view path); diff --git a/Source/data/iterators.hpp b/Source/data/iterators.hpp index ccaab1c5d..b40d1d1c1 100644 --- a/Source/data/iterators.hpp +++ b/Source/data/iterators.hpp @@ -1,11 +1,10 @@ #pragma once #include +#include #include #include -#include - #include "parser.hpp" #include "utils/parse_int.hpp" #include "utils/str_cat.hpp" @@ -26,29 +25,29 @@ public: InvalidValue }; - static tl::expected mapError(std::errc ec) + static std::expected mapError(std::errc ec) { if (ec == std::errc()) return {}; switch (ec) { case std::errc::result_out_of_range: - return tl::unexpected { Error::OutOfRange }; + return std::unexpected { Error::OutOfRange }; case std::errc::invalid_argument: - return tl::unexpected { Error::NotANumber }; + return std::unexpected { Error::NotANumber }; default: - return tl::unexpected { Error::InvalidValue }; + return std::unexpected { Error::InvalidValue }; } } - static tl::expected mapError(ParseIntError ec) + static std::expected mapError(ParseIntError ec) { switch (ec) { case ParseIntError::OutOfRange: - return tl::unexpected { Error::OutOfRange }; + return std::unexpected { Error::OutOfRange }; case ParseIntError::ParseError: - return tl::unexpected { Error::NotANumber }; + return std::unexpected { Error::NotANumber }; default: - return tl::unexpected { Error::InvalidValue }; + return std::unexpected { Error::InvalidValue }; } } @@ -95,7 +94,7 @@ public: * @return an error code corresponding to the from_chars result if parsing failed */ template - [[nodiscard]] tl::expected parseInt(T &destination) + [[nodiscard]] std::expected parseInt(T &destination) { std::from_chars_result result {}; if (state_->status == GetFieldResult::Status::ReadyToRead) { @@ -114,7 +113,7 @@ public: return mapError(result.ec); } - [[nodiscard]] tl::expected parseBool(bool &destination) + [[nodiscard]] std::expected parseBool(bool &destination) { const std::string_view str = value(); if (str == "true") { @@ -125,16 +124,16 @@ public: destination = false; return {}; } - return tl::make_unexpected(DataFileField::Error::InvalidValue); + return std::unexpected(DataFileField::Error::InvalidValue); } template - [[nodiscard]] tl::expected parseIntArray(T *destination, size_t n) + [[nodiscard]] std::expected parseIntArray(T *destination, size_t n) { size_t i = 0; for (const std::string_view part : SplitByChar(value(), ',')) { if (i == n) - return tl::make_unexpected(Error::InvalidValue); + return std::unexpected(Error::InvalidValue); const std::from_chars_result result = std::from_chars(part.data(), part.data() + part.size(), destination[i]); if (result.ec != std::errc()) @@ -142,41 +141,41 @@ public: ++i; } if (i != n) - return tl::make_unexpected(Error::InvalidValue); + return std::unexpected(Error::InvalidValue); return {}; } template - [[nodiscard]] tl::expected parseIntArray(T (&destination)[N]) + [[nodiscard]] std::expected parseIntArray(T (&destination)[N]) { return parseIntArray(destination, N); } template - [[nodiscard]] tl::expected parseIntArray(std::array &destination) + [[nodiscard]] std::expected parseIntArray(std::array &destination) { return parseIntArray(destination.data(), N); } template - [[nodiscard]] tl::expected parseEnumArray(T *destination, size_t n, std::optional fillMissing, ParseFn &&parseFn) + [[nodiscard]] std::expected parseEnumArray(T *destination, size_t n, std::optional fillMissing, ParseFn &&parseFn) { size_t i = 0; const std::string_view str = value(); if (!str.empty()) { for (const std::string_view part : SplitByChar(str, ',')) { if (i == n) - return tl::make_unexpected(StrCat("Too many values, max: ", n)); + return std::unexpected(StrCat("Too many values, max: ", n)); auto result = parseFn(part); if (!result.has_value()) { - return tl::make_unexpected(std::move(result).error()); + return std::unexpected(std::move(result).error()); } destination[i++] = *result; } } if (i != n) { if (!fillMissing.has_value()) { - return tl::make_unexpected(StrCat("Too few values, expected ", n, " got ", i)); + return std::unexpected(StrCat("Too few values, expected ", n, " got ", i)); } while (i < n) { destination[i++] = *fillMissing; @@ -186,19 +185,19 @@ public: } template - [[nodiscard]] tl::expected parseEnumArray(T (&destination)[N], std::optional fillMissing, ParseFn &&parseFn) + [[nodiscard]] std::expected parseEnumArray(T (&destination)[N], std::optional fillMissing, ParseFn &&parseFn) { return parseEnumArray(destination, N, std::move(fillMissing), std::forward(parseFn)); } template - [[nodiscard]] tl::expected parseIntArray(std::array &destination, std::optional fillMissing, ParseFn &&parseFn) + [[nodiscard]] std::expected parseIntArray(std::array &destination, std::optional fillMissing, ParseFn &&parseFn) { return parseEnumArray(destination.data(), N, std::move(fillMissing), std::forward(parseFn)); } template - [[nodiscard]] tl::expected parseEnumList(T &destination, ParseFn &&parseFn) + [[nodiscard]] std::expected parseEnumList(T &destination, ParseFn &&parseFn) { destination = {}; const std::string_view str = value(); @@ -207,17 +206,17 @@ public: for (const std::string_view part : SplitByChar(str, ',')) { auto result = parseFn(part); if (!result.has_value()) - return tl::make_unexpected(std::move(result).error()); + return std::unexpected(std::move(result).error()); destination |= result.value(); } return {}; } template - [[nodiscard]] tl::expected asInt() + [[nodiscard]] std::expected asInt() { T value = 0; - return parseInt(value).map([value]() { return value; }); + return parseInt(value).transform([value]() { return value; }); } /** @@ -231,7 +230,7 @@ public: * @return an error code equivalent to what you'd get from from_chars if parsing failed */ template - [[nodiscard]] tl::expected parseFixed6(T &destination) + [[nodiscard]] std::expected parseFixed6(T &destination) { ParseIntResult parseResult; if (state_->status == GetFieldResult::Status::ReadyToRead) { @@ -255,10 +254,10 @@ public: } template - [[nodiscard]] tl::expected asFixed6() + [[nodiscard]] std::expected asFixed6() { T value = 0; - return parseFixed6(value).map([value]() { return value; }); + return parseFixed6(value).transform([value]() { return value; }); } /** diff --git a/Source/data/record_reader.hpp b/Source/data/record_reader.hpp index df3795401..8eb073a43 100644 --- a/Source/data/record_reader.hpp +++ b/Source/data/record_reader.hpp @@ -1,10 +1,10 @@ #pragma once #include +#include #include #include -#include #include #include "data/file.hpp" @@ -86,7 +86,7 @@ public: void read(std::string_view name, T &out, F &&parseFn) { DataFileField field = nextField(); - tl::expected result = parseFn(field.value()); + std::expected result = parseFn(field.value()); failOnError(result, name, field, DataFileField::Error::InvalidValue); out = *std::move(result); } @@ -116,7 +116,7 @@ public: private: template - void failOnError(const tl::expected &result, std::string_view name, const DataFileField &field) + void failOnError(const std::expected &result, std::string_view name, const DataFileField &field) { if (!result.has_value()) { DataFile::reportFatalFieldError(result.error(), filename_, name, field); @@ -124,7 +124,7 @@ private: } template - void failOnError(const tl::expected &result, std::string_view name, const DataFileField &field, DataFileField::Error error) + void failOnError(const std::expected &result, std::string_view name, const DataFileField &field, DataFileField::Error error) { if (!result.has_value()) { DataFile::reportFatalFieldError(error, filename_, name, field, result.error()); diff --git a/Source/data/value_reader.hpp b/Source/data/value_reader.hpp index 6859db307..ace220c47 100644 --- a/Source/data/value_reader.hpp +++ b/Source/data/value_reader.hpp @@ -1,10 +1,10 @@ #pragma once #include +#include #include #include -#include #include #include "data/file.hpp" @@ -25,7 +25,7 @@ public: void readValue(std::string_view expectedKey, T &outValue, F &&readFn) { DataFileField valueField = getValueField(expectedKey); - if (const tl::expected result = readFn(valueField, outValue); + if (const std::expected result = readFn(valueField, outValue); !result.has_value()) { DataFile::reportFatalFieldError(result.error(), filename_, "Value", valueField); } @@ -35,10 +35,10 @@ public: template void read(std::string_view expectedKey, T &outValue, F &&parseFn) { - readValue(expectedKey, outValue, [&parseFn](DataFileField &valueField, T &outValue) -> tl::expected { + readValue(expectedKey, outValue, [&parseFn](DataFileField &valueField, T &outValue) -> std::expected { const auto result = parseFn(valueField.value()); if (!result.has_value()) { - return tl::make_unexpected(devilution::DataFileField::Error::InvalidValue); + return std::unexpected(devilution::DataFileField::Error::InvalidValue); } outValue = result.value(); @@ -49,10 +49,10 @@ public: template void readEnumList(std::string_view expectedKey, T &outValue, F &&parseFn) { - readValue(expectedKey, outValue, [&parseFn](DataFileField &valueField, T &outValue) -> tl::expected { + readValue(expectedKey, outValue, [&parseFn](DataFileField &valueField, T &outValue) -> std::expected { const auto result = valueField.parseEnumList(outValue, std::forward(parseFn)); if (!result.has_value()) { - return tl::make_unexpected(devilution::DataFileField::Error::InvalidValue); + return std::unexpected(devilution::DataFileField::Error::InvalidValue); } return {}; @@ -81,15 +81,15 @@ public: { readValue(expectedKey, outValue, [](DataFileField &valueField, std::string &outValue) { outValue = valueField.value(); - return tl::expected {}; + return std::expected {}; }); } void readChar(std::string_view expectedKey, char &outValue) { - readValue(expectedKey, outValue, [](DataFileField &valueField, char &outValue) -> tl::expected { + readValue(expectedKey, outValue, [](DataFileField &valueField, char &outValue) -> std::expected { if (valueField.value().size() != 1) { - return tl::make_unexpected(devilution::DataFileField::Error::InvalidValue); + return std::unexpected(devilution::DataFileField::Error::InvalidValue); } outValue = valueField.value().at(0); diff --git a/Source/diablo.cpp b/Source/diablo.cpp index a22cb49a0..11d264ed7 100644 --- a/Source/diablo.cpp +++ b/Source/diablo.cpp @@ -1360,12 +1360,12 @@ void DiabloDeinit() SDL_Quit(); } -tl::expected LoadLvlGFX() +std::expected LoadLvlGFX() { assert(pDungeonCels == nullptr); constexpr int SpecialCelWidth = 64; - const auto loadAll = [](const char *cel, const char *til, const char *special) -> tl::expected { + const auto loadAll = [](const char *cel, const char *til, const char *special) -> std::expected { ASSIGN_OR_RETURN(pDungeonCels, LoadFileInMemWithStatus(cel)); ASSIGN_OR_RETURN(pMegaTiles, LoadFileInMemWithStatus(til)); ASSIGN_OR_RETURN(pSpecialCels, LoadCelWithStatus(special, SpecialCelWidth)); @@ -1420,11 +1420,11 @@ tl::expected LoadLvlGFX() "nlevels\\l5data\\l5.til", "nlevels\\l5data\\l5s"); default: - return tl::make_unexpected("LoadLvlGFX"); + return std::unexpected("LoadLvlGFX"); } } -tl::expected LoadAllGFX() +std::expected LoadAllGFX() { IncProgress(); #if !defined(USE_SDL1) && !defined(__vita__) @@ -3136,7 +3136,7 @@ void LoadGameLevelStash() gbIsHellfireSaveGame = isHellfireSaveGame; } -tl::expected LoadGameLevelDungeon(bool firstflag, lvl_entry lvldir, const Player &myPlayer) +std::expected LoadGameLevelDungeon(bool firstflag, lvl_entry lvldir, const Player &myPlayer) { if (firstflag || lvldir == ENTRY_LOAD || !myPlayer._pLvlVisited[currlevel] || gbIsMultiplayer) { HoldThemeRooms(); @@ -3232,7 +3232,7 @@ void LoadGameLevelSetVisited() } } -tl::expected LoadGameLevelTown(bool firstflag, lvl_entry lvldir, const Player &myPlayer) +std::expected LoadGameLevelTown(bool firstflag, lvl_entry lvldir, const Player &myPlayer) { for (int i = 0; i < MAXDUNX; i++) { // NOLINT(modernize-loop-convert) for (int j = 0; j < MAXDUNY; j++) { @@ -3261,7 +3261,7 @@ tl::expected LoadGameLevelTown(bool firstflag, lvl_entry lvld return {}; } -tl::expected LoadGameLevelSetLevel(bool firstflag, lvl_entry lvldir, const Player &myPlayer) +std::expected LoadGameLevelSetLevel(bool firstflag, lvl_entry lvldir, const Player &myPlayer) { LoadSetMap(); IncProgress(); @@ -3313,7 +3313,7 @@ tl::expected LoadGameLevelSetLevel(bool firstflag, lvl_entry return {}; } -tl::expected LoadGameLevelStandardLevel(bool firstflag, lvl_entry lvldir, const Player &myPlayer) +std::expected LoadGameLevelStandardLevel(bool firstflag, lvl_entry lvldir, const Player &myPlayer) { CreateLevel(lvldir); @@ -3396,7 +3396,7 @@ void LoadGameLevelCalculateCursor() CheckCursMove(); } -tl::expected LoadGameLevel(bool firstflag, lvl_entry lvldir) +std::expected LoadGameLevel(bool firstflag, lvl_entry lvldir) { const _music_id neededTrack = GetLevelMusic(leveltype); diff --git a/Source/diablo.h b/Source/diablo.h index 30777619e..24de6384d 100644 --- a/Source/diablo.h +++ b/Source/diablo.h @@ -106,7 +106,7 @@ void diablo_focus_pause(); void diablo_focus_unpause(); bool PressEscKey(); void DisableInputEventHandler(const SDL_Event &event, uint16_t modState); -tl::expected LoadGameLevel(bool firstflag, lvl_entry lvldir); +std::expected LoadGameLevel(bool firstflag, lvl_entry lvldir); bool IsDiabloAlive(bool playSFX); void PrintScreen(SDL_Keycode vkey); diff --git a/Source/dvlnet/base.cpp b/Source/dvlnet/base.cpp index 14eb4fcb2..ba118d707 100644 --- a/Source/dvlnet/base.cpp +++ b/Source/dvlnet/base.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #ifdef USE_SDL3 @@ -11,8 +12,6 @@ #include #endif -#include - #include "player.h" namespace devilution { @@ -20,7 +19,7 @@ namespace net { void base::process_network_packets() { - tl::expected result = poll(); + std::expected result = poll(); if (!result.has_value()) { LogVerbose("Error polling network: {}", result.error().what()); } @@ -61,7 +60,7 @@ void base::DisconnectNet(plr_t plr) { } -tl::expected base::SendEchoRequest(plr_t player) +std::expected base::SendEchoRequest(plr_t player) { if (plr_self == PLR_BROADCAST) return {}; @@ -69,29 +68,29 @@ tl::expected base::SendEchoRequest(plr_t player) return {}; const timestamp_t now = SDL_GetTicks(); - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(plr_self, player, now); if (!pkt.has_value()) { - return tl::make_unexpected(pkt.error()); + return std::unexpected(pkt.error()); } return send(**pkt); } -tl::expected base::HandleAccept(packet &pkt) +std::expected base::HandleAccept(packet &pkt) { if (plr_self != PLR_BROADCAST) { return {}; // already have player id } if (pkt.Cookie() == cookie_self) { - tl::expected newPlayerPkt = pkt.NewPlayer(); + std::expected newPlayerPkt = pkt.NewPlayer(); if (!newPlayerPkt.has_value()) - return tl::make_unexpected(newPlayerPkt.error()); + return std::unexpected(newPlayerPkt.error()); plr_self = *std::move(newPlayerPkt); Connect(plr_self); } - tl::expected infoPkt = pkt.Info(); + std::expected infoPkt = pkt.Info(); if (!infoPkt.has_value()) - return tl::make_unexpected(infoPkt.error()); + return std::unexpected(infoPkt.error()); const buffer_t &info = **infoPkt; if (game_init_info != info) { if (info.size() != sizeof(GameData)) { @@ -109,14 +108,14 @@ tl::expected base::HandleAccept(packet &pkt) return {}; } -tl::expected base::HandleConnect(packet &pkt) +std::expected base::HandleConnect(packet &pkt) { return pkt.NewPlayer().transform([this](plr_t &&newPlayer) { Connect(newPlayer); }); } -tl::expected base::HandleTurn(packet &pkt) +std::expected base::HandleTurn(packet &pkt) { const plr_t src = pkt.Source(); PlayerState &playerState = playerStateTable_[src]; @@ -127,17 +126,17 @@ tl::expected base::HandleTurn(packet &pkt) }); } -tl::expected base::HandleDisconnect(packet &pkt) +std::expected base::HandleDisconnect(packet &pkt) { - tl::expected newPlayer = pkt.NewPlayer(); + std::expected newPlayer = pkt.NewPlayer(); if (!newPlayer.has_value()) - return tl::make_unexpected(newPlayer.error()); + return std::unexpected(newPlayer.error()); if (*newPlayer == plr_self) - return tl::make_unexpected("We were dropped by the owner?"); + return std::unexpected("We were dropped by the owner?"); if (IsConnected(*newPlayer)) { - tl::expected leaveinfo = pkt.LeaveInfo(); + std::expected leaveinfo = pkt.LeaveInfo(); if (!leaveinfo.has_value()) - return tl::make_unexpected(leaveinfo.error()); + return std::unexpected(leaveinfo.error()); _SNETEVENT ev; ev.eventid = EVENT_TYPE_PLAYER_LEAVE_GAME; ev.playerid = *newPlayer; @@ -153,7 +152,7 @@ tl::expected base::HandleDisconnect(packet &pkt) return {}; } -tl::expected base::HandleEchoRequest(packet &pkt) +std::expected base::HandleEchoRequest(packet &pkt) { // If we have already left the game, // there is no need to respond to echoes @@ -168,7 +167,7 @@ tl::expected base::HandleEchoRequest(packet &pkt) }); } -tl::expected base::HandleEchoReply(packet &pkt) +std::expected base::HandleEchoReply(packet &pkt) { const uint32_t now = SDL_GetTicks(); plr_t src = pkt.Source(); @@ -189,7 +188,7 @@ void base::ClearMsg(plr_t plr) message_queue.end()); } -tl::expected base::Connect(plr_t player) +std::expected base::Connect(plr_t player) { PlayerState &playerState = playerStateTable_[player]; const bool wasConnected = playerState.isConnected; @@ -206,10 +205,10 @@ bool base::IsConnected(plr_t player) const return playerState.isConnected; } -tl::expected base::RecvLocal(packet &pkt) +std::expected base::RecvLocal(packet &pkt) { if (pkt.Source() < MAX_PLRS) { - if (tl::expected result = Connect(pkt.Source()); + if (std::expected result = Connect(pkt.Source()); !result.has_value()) { return result; } @@ -271,13 +270,13 @@ bool base::SNetSendMessage(uint8_t playerId, void *data, size_t size) else dest = playerId; if (dest != plr_self) { - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(plr_self, dest, message); if (!pkt.has_value()) { LogError("make_packet: {}", pkt.error().what()); return false; } - tl::expected result = send(**pkt); + std::expected result = send(**pkt); if (!result.has_value()) { LogError("send: {}", result.error().what()); return false; @@ -384,23 +383,23 @@ bool base::SNetSendTurn(char *data, size_t size) return true; } -tl::expected base::SendTurnIfReady(turn_t turn) +std::expected base::SendTurnIfReady(turn_t turn) { if (awaitingSequenceNumber_) awaitingSequenceNumber_ = !IsGameHost(); if (!awaitingSequenceNumber_) { - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(plr_self, PLR_BROADCAST, turn); if (!pkt.has_value()) { - return tl::make_unexpected(pkt.error()); + return std::unexpected(pkt.error()); } return send(**pkt); } return {}; } -tl::expected base::SendFirstTurnIfReady(plr_t player) +std::expected base::SendFirstTurnIfReady(plr_t player) { if (awaitingSequenceNumber_) return {}; @@ -411,12 +410,12 @@ tl::expected base::SendFirstTurnIfReady(plr_t player) return {}; for (const turn_t turn : turnQueue) { - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(plr_self, player, turn); if (!pkt.has_value()) { - return tl::make_unexpected(pkt.error()); + return std::unexpected(pkt.error()); } - tl::expected result = send(**pkt); + std::expected result = send(**pkt); if (!result.has_value()) { return result; } @@ -424,7 +423,7 @@ tl::expected base::SendFirstTurnIfReady(plr_t player) return {}; } -tl::expected base::MakeReady(seq_t sequenceNumber) +std::expected base::MakeReady(seq_t sequenceNumber) { if (!awaitingSequenceNumber_) return {}; @@ -438,7 +437,7 @@ tl::expected base::MakeReady(seq_t sequenceNumber) for (turn_t &turn : turnQueue) { turn.SequenceNumber = next_turn; next_turn++; - if (tl::expected result = SendTurnIfReady(turn); + if (std::expected result = SendTurnIfReady(turn); !result.has_value()) { return result; } @@ -482,14 +481,14 @@ bool base::SNetRegisterEventHandler(event_type evtype, SEVTHANDLER func) bool base::SNetLeaveGame(net::leaveinfo_t type) { - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet( plr_self, PLR_BROADCAST, plr_self, type); if (!pkt.has_value()) { LogError("make_packet: {}", pkt.error().what()); return false; } - tl::expected result = send(**pkt); + std::expected result = send(**pkt); if (!result.has_value()) { LogError("send: {}", result.error().what()); return false; @@ -501,7 +500,7 @@ bool base::SNetLeaveGame(net::leaveinfo_t type) bool base::SNetDropPlayer(int playerid, net::leaveinfo_t flags) { const auto plr = static_cast(playerid); - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet( plr_self, PLR_BROADCAST, @@ -514,12 +513,12 @@ bool base::SNetDropPlayer(int playerid, net::leaveinfo_t flags) // Disconnect at the network layer first so we // don't send players their own disconnect packet DisconnectNet(plr); - tl::expected sendResult = send(**pkt); + std::expected sendResult = send(**pkt); if (!sendResult.has_value()) { LogError("send: {}", sendResult.error().what()); return false; } - tl::expected receiveResult = RecvLocal(**pkt); + std::expected receiveResult = RecvLocal(**pkt); if (!receiveResult.has_value()) { LogError("SNetDropPlayer: {}", receiveResult.error().what()); return false; diff --git a/Source/dvlnet/base.h b/Source/dvlnet/base.h index 46b0ccea4..67e024939 100644 --- a/Source/dvlnet/base.h +++ b/Source/dvlnet/base.h @@ -30,8 +30,8 @@ public: bool SNetGetOwnerTurnsWaiting(uint32_t *turns) override; bool SNetGetTurnsInTransit(uint32_t *turns) override; - virtual tl::expected poll() = 0; - virtual tl::expected send(packet &pkt) = 0; + virtual std::expected poll() = 0; + virtual std::expected send(packet &pkt) = 0; virtual void DisconnectNet(plr_t plr); void process_network_packets() override; @@ -81,10 +81,10 @@ protected: std::unique_ptr pktfty; - tl::expected Connect(plr_t player); - tl::expected RecvLocal(packet &pkt); + std::expected Connect(plr_t player); + std::expected RecvLocal(packet &pkt); void RunEventHandler(_SNETEVENT &ev); - tl::expected SendEchoRequest(plr_t player); + std::expected SendEchoRequest(plr_t player); [[nodiscard]] bool IsConnected(plr_t player) const; virtual bool IsGameHost() = 0; @@ -96,17 +96,17 @@ private: plr_t GetOwner(); bool AllTurnsArrived(); - tl::expected MakeReady(seq_t sequenceNumber); - tl::expected SendTurnIfReady(turn_t turn); - tl::expected SendFirstTurnIfReady(plr_t player); + std::expected MakeReady(seq_t sequenceNumber); + std::expected SendTurnIfReady(turn_t turn); + std::expected SendFirstTurnIfReady(plr_t player); void ClearMsg(plr_t plr); - tl::expected HandleAccept(packet &pkt); - tl::expected HandleConnect(packet &pkt); - tl::expected HandleTurn(packet &pkt); - tl::expected HandleDisconnect(packet &pkt); - tl::expected HandleEchoRequest(packet &pkt); - tl::expected HandleEchoReply(packet &pkt); + std::expected HandleAccept(packet &pkt); + std::expected HandleConnect(packet &pkt); + std::expected HandleTurn(packet &pkt); + std::expected HandleDisconnect(packet &pkt); + std::expected HandleEchoRequest(packet &pkt); + std::expected HandleEchoReply(packet &pkt); }; } // namespace net diff --git a/Source/dvlnet/base_protocol.h b/Source/dvlnet/base_protocol.h index 3967186a4..ab4c6abbb 100644 --- a/Source/dvlnet/base_protocol.h +++ b/Source/dvlnet/base_protocol.h @@ -27,8 +27,8 @@ class base_protocol : public base { public: int create(std::string_view addrstr) override; int join(std::string_view addrstr) override; - tl::expected poll() override; - tl::expected send(packet &pkt) override; + std::expected poll() override; + std::expected send(packet &pkt) override; void DisconnectNet(plr_t plr) override; bool SNetLeaveGame(net::leaveinfo_t type) override; @@ -66,18 +66,18 @@ private: bool isGameHost_; plr_t get_master(); - tl::expected InitiateHandshake(plr_t player); - tl::expected SendTo(plr_t player, packet &pkt); + std::expected InitiateHandshake(plr_t player); + std::expected SendTo(plr_t player, packet &pkt); void DrainSendQueue(plr_t player); void recv(); - tl::expected handle_join_request(packet &pkt, endpoint_t sender); - tl::expected recv_decrypted(packet &pkt, endpoint_t sender); - tl::expected recv_ingame(packet &pkt, endpoint_t sender); + std::expected handle_join_request(packet &pkt, endpoint_t sender); + std::expected recv_decrypted(packet &pkt, endpoint_t sender); + std::expected recv_ingame(packet &pkt, endpoint_t sender); bool is_recognized(endpoint_t sender); - tl::expected wait_network(); - tl::expected wait_firstpeer(); - tl::expected wait_join(); + std::expected wait_network(); + std::expected wait_firstpeer(); + std::expected wait_join(); }; template @@ -91,18 +91,18 @@ plr_t base_protocol

::get_master() } template -tl::expected base_protocol

::wait_network() +std::expected base_protocol

::wait_network() { // wait for ZeroTier for 5 seconds for (auto i = 0; i < 500; ++i) { - tl::expected status = proto.network_online(); + std::expected status = proto.network_online(); if (!status.has_value()) - return tl::make_unexpected(std::move(status).error()); + return std::unexpected(std::move(status).error()); if (*status) return {}; SDL_Delay(10); } - return tl::make_unexpected("Timeout waiting for ZeroTier network initialization"); + return std::unexpected("Timeout waiting for ZeroTier network initialization"); } template @@ -114,7 +114,7 @@ void base_protocol

::DisconnectNet(plr_t plr) } template -tl::expected base_protocol

::wait_firstpeer() +std::expected base_protocol

::wait_firstpeer() { firstpeer = {}; // wait for peer for 5 seconds @@ -129,21 +129,21 @@ tl::expected base_protocol

::wait_firstpeer() SDL_Delay(10); } if (!firstpeer) - return tl::make_unexpected("Timeout waiting for response from game host"); + return std::unexpected("Timeout waiting for response from game host"); return {}; } template bool base_protocol

::send_info_request() { - tl::expected status = proto.peers_ready(); + std::expected status = proto.peers_ready(); if (!status.has_value()) { LogError("peers_ready: {}", status.error().what()); return false; } if (!*status) return false; - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(PLR_BROADCAST, PLR_MASTER); if (!pkt.has_value()) { LogError("make_packet: {}", pkt.error().what()); @@ -154,15 +154,15 @@ bool base_protocol

::send_info_request() } template -tl::expected base_protocol

::wait_join() +std::expected base_protocol

::wait_join() { cookie_self = packet_out::GenerateCookie(); - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet(PLR_BROADCAST, PLR_MASTER, cookie_self, game_init_info); if (!pkt.has_value()) { - return tl::make_unexpected(pkt.error()); + return std::unexpected(pkt.error()); } - tl::expected result = proto.send(firstpeer, (*pkt)->Data()); + std::expected result = proto.send(firstpeer, (*pkt)->Data()); if (!result.has_value()) { return result; } @@ -172,7 +172,7 @@ tl::expected base_protocol

::wait_join() return {}; // join successful SDL_Delay(10); } - return tl::make_unexpected("Timeout waiting to join game"); + return std::unexpected("Timeout waiting to join game"); } template @@ -181,14 +181,14 @@ int base_protocol

::create(std::string_view addrstr) gamename = addrstr; isGameHost_ = true; - tl::expected isReady = wait_network(); + std::expected isReady = wait_network(); if (!isReady.has_value()) { const std::string_view message = isReady.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); return -1; } plr_self = 0; - if (tl::expected result = Connect(plr_self); + if (std::expected result = Connect(plr_self); !result.has_value()) { const std::string_view message = result.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); @@ -203,19 +203,19 @@ int base_protocol

::join(std::string_view addrstr) gamename = addrstr; isGameHost_ = false; - tl::expected isReady = wait_network(); + std::expected isReady = wait_network(); if (!isReady.has_value()) { const std::string_view message = isReady.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); return -1; } - tl::expected isPeerReady = wait_firstpeer(); + std::expected isPeerReady = wait_firstpeer(); if (!isPeerReady.has_value()) { const std::string_view message = isPeerReady.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); return -1; } - tl::expected isJoined = wait_join(); + std::expected isJoined = wait_join(); if (!isJoined.has_value()) { const std::string_view message = isJoined.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); @@ -231,14 +231,14 @@ bool base_protocol

::IsGameHost() } template -tl::expected base_protocol

::poll() +std::expected base_protocol

::poll() { recv(); return {}; } template -tl::expected base_protocol

::InitiateHandshake(plr_t player) +std::expected base_protocol

::InitiateHandshake(plr_t player) { Peer &peer = peers[player]; @@ -253,26 +253,26 @@ tl::expected base_protocol

::InitiateHandshake(plr_t player } template -tl::expected base_protocol

::send(packet &pkt) +std::expected base_protocol

::send(packet &pkt) { plr_t destination = pkt.Destination(); if (destination == PLR_BROADCAST) { for (plr_t player = 0; player < Players.size(); player++) { - tl::expected result = SendTo(player, pkt); + std::expected result = SendTo(player, pkt); if (!result.has_value()) LogError("Failed to send packet {} to player {}: {}", static_cast(pkt.Type()), player, result.error().what()); } return {}; } if (destination >= MAX_PLRS) - return tl::make_unexpected("Invalid player ID"); + return std::unexpected("Invalid player ID"); if (destination == plr_self) return {}; return SendTo(destination, pkt); } template -tl::expected base_protocol

::SendTo(plr_t player, packet &pkt) +std::expected base_protocol

::SendTo(plr_t player, packet &pkt) { Peer &peer = peers[player]; if (!peer.endpoint) @@ -294,7 +294,7 @@ void base_protocol

::recv() buffer_t pkt_buf; endpoint_t sender; while (proto.recv(sender, pkt_buf)) { // read until kernel buffer is empty? - tl::expected result + std::expected result = pktfty->make_packet(pkt_buf) .and_then([&](std::unique_ptr &&pkt) { return recv_decrypted(*pkt, sender); @@ -316,7 +316,7 @@ void base_protocol

::recv() } template -tl::expected base_protocol

::handle_join_request(packet &inPkt, endpoint_t sender) +std::expected base_protocol

::handle_join_request(packet &inPkt, endpoint_t sender) { plr_t i; for (i = 0; i < Players.size(); ++i) { @@ -324,7 +324,7 @@ tl::expected base_protocol

::handle_join_request(packet &in if (i != plr_self && !peer.endpoint) { peer.endpoint = sender; peer.sendQueue = std::make_unique>(); - if (tl::expected result = Connect(i); + if (std::expected result = Connect(i); !result.has_value()) { return result; } @@ -340,7 +340,7 @@ tl::expected base_protocol

::handle_join_request(packet &in for (plr_t j = 0; j < Players.size(); ++j) { endpoint_t peer = peers[j].endpoint; if ((j != plr_self) && (j != i) && peer) { - tl::expected result + std::expected result = pktfty->make_packet(PLR_MASTER, PLR_BROADCAST, i, senderinfo) .and_then([&](std::unique_ptr &&pkt) { return proto.send(peer, pkt->Data()); }) .and_then([&]() { return pktfty->make_packet(PLR_MASTER, PLR_BROADCAST, j, peer.serialize()); }) @@ -352,14 +352,14 @@ tl::expected base_protocol

::handle_join_request(packet &in // PT_JOIN_ACCEPT must be sent after all PT_CONNECT packets so the new player does // not resume game logic until after having been notified of all existing players - tl::expected cookie = inPkt.Cookie(); + std::expected cookie = inPkt.Cookie(); if (!cookie.has_value()) - return tl::make_unexpected(cookie.error()); - tl::expected, PacketError> pkt + return std::unexpected(cookie.error()); + std::expected, PacketError> pkt = pktfty->make_packet(plr_self, PLR_BROADCAST, *cookie, i, game_init_info); if (!pkt.has_value()) - return tl::make_unexpected(pkt.error()); - tl::expected result = proto.send(sender, (*pkt)->Data()); + return std::unexpected(pkt.error()); + std::expected result = proto.send(sender, (*pkt)->Data()); if (!result.has_value()) return result; DrainSendQueue(i); @@ -367,13 +367,13 @@ tl::expected base_protocol

::handle_join_request(packet &in } template -tl::expected base_protocol

::recv_decrypted(packet &pkt, endpoint_t sender) +std::expected base_protocol

::recv_decrypted(packet &pkt, endpoint_t sender) { if (pkt.Source() == PLR_BROADCAST && pkt.Destination() == PLR_MASTER && pkt.Type() == PT_INFO_REPLY) { size_t neededSize = sizeof(GameData) + (PlayerNameLength * MAX_PLRS); - const tl::expected pktInfo = pkt.Info(); + const std::expected pktInfo = pkt.Info(); if (!pktInfo.has_value()) - return tl::make_unexpected(pktInfo.error()); + return std::unexpected(pktInfo.error()); const buffer_t &infoBuffer = **pktInfo; if (infoBuffer.size() < neededSize) return {}; @@ -406,11 +406,11 @@ tl::expected base_protocol

::recv_decrypted(packet &pkt, en } template -tl::expected base_protocol

::recv_ingame(packet &pkt, endpoint_t sender) +std::expected base_protocol

::recv_ingame(packet &pkt, endpoint_t sender) { if (pkt.Source() == PLR_BROADCAST && pkt.Destination() == PLR_MASTER) { if (pkt.Type() == PT_JOIN_REQUEST) { - if (tl::expected result = handle_join_request(pkt, sender); + if (std::expected result = handle_join_request(pkt, sender); !result.has_value()) { return result; } @@ -427,10 +427,10 @@ tl::expected base_protocol

::recv_ingame(packet &pkt, endpo } } std::memcpy(buf.data() + game_init_info.size() + (PlayerNameLength * MAX_PLRS), &gamename[0], gamename.size()); - tl::expected, PacketError> reply + std::expected, PacketError> reply = pktfty->make_packet(PLR_BROADCAST, PLR_MASTER, buf); if (!reply.has_value()) { - return tl::make_unexpected(reply.error()); + return std::unexpected(reply.error()); } proto.send_oob(sender, (*reply)->Data()); } @@ -444,19 +444,19 @@ tl::expected base_protocol

::recv_ingame(packet &pkt, endpo } // addrinfo packets - tl::expected newPlayer = pkt.NewPlayer(); + std::expected newPlayer = pkt.NewPlayer(); if (!newPlayer.has_value()) - return tl::make_unexpected(newPlayer.error()); + return std::unexpected(newPlayer.error()); Peer &peer = peers[*newPlayer]; - tl::expected pktInfo = pkt.Info(); + std::expected pktInfo = pkt.Info(); if (!pktInfo.has_value()) - return tl::make_unexpected(pktInfo.error()); - if (tl::expected result = peer.endpoint.unserialize(**pktInfo); + return std::unexpected(pktInfo.error()); + if (std::expected result = peer.endpoint.unserialize(**pktInfo); !result.has_value()) { return result; } peer.sendQueue = std::make_unique>(); - if (tl::expected result = Connect(*newPlayer); + if (std::expected result = Connect(*newPlayer); !result.has_value()) { return result; } @@ -473,7 +473,7 @@ tl::expected base_protocol

::recv_ingame(packet &pkt, endpo if (sender == firstpeer && pkt.Type() == PT_JOIN_ACCEPT) { plr_t src = pkt.Source(); peers[src].endpoint = sender; - if (tl::expected result = Connect(src); + if (std::expected result = Connect(src); !result.has_value()) { return result; } @@ -486,7 +486,7 @@ tl::expected base_protocol

::recv_ingame(packet &pkt, endpo return {}; // packet not for us, drop bool wasBroadcast = plr_self == PLR_BROADCAST; - if (tl::expected result = RecvLocal(pkt); + if (std::expected result = RecvLocal(pkt); !result.has_value()) { return result; } @@ -495,7 +495,7 @@ tl::expected base_protocol

::recv_ingame(packet &pkt, endpo if (wasBroadcast) { // Send a handshake to everyone just after PT_JOIN_ACCEPT for (plr_t player = 0; player < Players.size(); player++) { - if (tl::expected result = InitiateHandshake(player); + if (std::expected result = InitiateHandshake(player); !result.has_value()) { return result; } @@ -517,7 +517,7 @@ void base_protocol

::DrainSendQueue(plr_t player) std::deque &sendQueue = *srcPeer.sendQueue; while (!sendQueue.empty()) { packet &pkt = sendQueue.front(); - tl::expected result = proto.send(srcPeer.endpoint, pkt.Data()); + std::expected result = proto.send(srcPeer.endpoint, pkt.Data()); if (!result.has_value()) LogError("DrainSendQueue failed to send packet: {}", result.error().what()); sendQueue.pop_front(); diff --git a/Source/dvlnet/frame_queue.cpp b/Source/dvlnet/frame_queue.cpp index fcc953596..d453a93d5 100644 --- a/Source/dvlnet/frame_queue.cpp +++ b/Source/dvlnet/frame_queue.cpp @@ -25,10 +25,10 @@ framesize_t frame_queue::Size() const return current_size; } -tl::expected frame_queue::Read(framesize_t s) +std::expected frame_queue::Read(framesize_t s) { if (current_size < s) - return tl::make_unexpected(FrameQueueError()); + return std::unexpected(FrameQueueError()); buffer_t ret; while (s > 0 && s >= buffer_deque.front().size()) { const auto bufferSize = static_cast(buffer_deque.front().size()); @@ -56,17 +56,17 @@ void frame_queue::Write(buffer_t buf) buffer_deque.push_back(std::move(buf)); } -tl::expected frame_queue::PacketReady() +std::expected frame_queue::PacketReady() { if (nextsize == 0) { if (Size() < sizeof(framesize_t)) return false; - tl::expected szbuf = Read(sizeof(framesize_t)); + std::expected szbuf = Read(sizeof(framesize_t)); if (!szbuf.has_value()) - return tl::make_unexpected(szbuf.error()); + return std::unexpected(szbuf.error()); nextsize = LoadLE32(szbuf->data()); if (nextsize == 0) - return tl::make_unexpected(FrameQueueError()); + return std::unexpected(FrameQueueError()); } return Size() >= (nextsize & frame_size_mask); } @@ -77,22 +77,22 @@ uint16_t frame_queue::ReadPacketFlags() return static_cast(nextsize >> 16); } -tl::expected frame_queue::ReadPacket() +std::expected frame_queue::ReadPacket() { const framesize_t packetSize = nextsize & frame_size_mask; if (nextsize == 0 || Size() < packetSize) - return tl::make_unexpected(FrameQueueError()); - tl::expected ret = Read(packetSize); + return std::unexpected(FrameQueueError()); + std::expected ret = Read(packetSize); nextsize = 0; return ret; } -tl::expected frame_queue::MakeFrame(buffer_t packetbuf, uint16_t flags) +std::expected frame_queue::MakeFrame(buffer_t packetbuf, uint16_t flags) { buffer_t ret; const auto size = static_cast(packetbuf.size()); if (size > max_frame_size) - return tl::make_unexpected("Buffer exceeds maximum frame size"); + return std::unexpected("Buffer exceeds maximum frame size"); static_assert(sizeof(size) == 4, "framesize_t is not 4 bytes"); unsigned char sizeBuf[4]; WriteLE32(sizeBuf, size | (static_cast(flags) << 16)); diff --git a/Source/dvlnet/frame_queue.h b/Source/dvlnet/frame_queue.h index 89c6e9c3c..13c59c04b 100644 --- a/Source/dvlnet/frame_queue.h +++ b/Source/dvlnet/frame_queue.h @@ -3,10 +3,9 @@ #include #include #include +#include #include -#include - #include "dvlnet/packet.h" namespace devilution { @@ -26,15 +25,15 @@ private: framesize_t nextsize = 0; framesize_t Size() const; - tl::expected Read(framesize_t s); + std::expected Read(framesize_t s); public: - tl::expected PacketReady(); + std::expected PacketReady(); uint16_t ReadPacketFlags(); - tl::expected ReadPacket(); + std::expected ReadPacket(); void Write(buffer_t buf); - static tl::expected MakeFrame(buffer_t packetbuf, uint16_t flags = 0); + static std::expected MakeFrame(buffer_t packetbuf, uint16_t flags = 0); }; } // namespace net diff --git a/Source/dvlnet/packet.cpp b/Source/dvlnet/packet.cpp index 10b3261d8..6dd2abee7 100644 --- a/Source/dvlnet/packet.cpp +++ b/Source/dvlnet/packet.cpp @@ -2,6 +2,7 @@ #include #include +#include #ifdef PACKET_ENCRYPTION #include @@ -10,8 +11,6 @@ #include #endif -#include - #include "utils/algorithm/container.hpp" #include "utils/str_cat.hpp" @@ -113,11 +112,11 @@ PacketError PacketTypeError(std::initializer_list expectedTypes, st namespace { -tl::expected CheckPacketTypeOneOf(std::initializer_list expectedTypes, std::uint8_t actualType) +std::expected CheckPacketTypeOneOf(std::initializer_list expectedTypes, std::uint8_t actualType) { if (c_none_of(expectedTypes, [actualType](uint8_t type) { return type == actualType; })) { - return tl::make_unexpected(PacketTypeError(expectedTypes, actualType)); + return std::unexpected(PacketTypeError(expectedTypes, actualType)); } return {}; } @@ -150,60 +149,60 @@ plr_t packet::Destination() const return m_dest; } -tl::expected packet::Message() +std::expected packet::Message() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_MESSAGE }, m_type) .transform([this]() { return &m_message; }); } -tl::expected packet::Turn() +std::expected packet::Turn() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_TURN }, m_type) .transform([this]() { return m_turn; }); } -tl::expected packet::Cookie() +std::expected packet::Cookie() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_JOIN_REQUEST, PT_JOIN_ACCEPT }, m_type) .transform([this]() { return m_cookie; }); } -tl::expected packet::NewPlayer() +std::expected packet::NewPlayer() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_JOIN_ACCEPT, PT_CONNECT, PT_DISCONNECT }, m_type) .transform([this]() { return m_newplr; }); } -tl::expected packet::Time() +std::expected packet::Time() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_ECHO_REQUEST, PT_ECHO_REPLY }, m_type) .transform([this]() { return m_time; }); } -tl::expected packet::Info() +std::expected packet::Info() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_JOIN_REQUEST, PT_JOIN_ACCEPT, PT_CONNECT, PT_INFO_REPLY }, m_type) .transform([this]() { return &m_info; }); } -tl::expected packet::LeaveInfo() +std::expected packet::LeaveInfo() { assert(have_decrypted); return CheckPacketTypeOneOf({ PT_DISCONNECT }, m_type) .transform([this]() { return m_leaveinfo; }); } -tl::expected packet_in::Create(buffer_t buf) +std::expected packet_in::Create(buffer_t buf) { assert(!have_encrypted && !have_decrypted); if (buf.size() < sizeof(packet_type) + 2 * sizeof(plr_t)) - return tl::make_unexpected(PacketError()); + return std::unexpected(PacketError()); decrypted_buffer = std::move(buf); have_decrypted = true; @@ -217,7 +216,7 @@ tl::expected packet_in::Create(buffer_t buf) } #ifdef PACKET_ENCRYPTION -tl::expected packet_in::Decrypt(buffer_t buf) +std::expected packet_in::Decrypt(buffer_t buf) { assert(!have_encrypted && !have_decrypted); encrypted_buffer = std::move(buf); @@ -226,7 +225,7 @@ tl::expected packet_in::Decrypt(buffer_t buf) if (encrypted_buffer.size() < crypto_secretbox_NONCEBYTES + crypto_secretbox_MACBYTES + sizeof(packet_type) + 2 * sizeof(plr_t)) - return tl::make_unexpected(PacketError()); + return std::unexpected(PacketError()); auto pktlen = (encrypted_buffer.size() - crypto_secretbox_NONCEBYTES - crypto_secretbox_MACBYTES); @@ -240,7 +239,7 @@ tl::expected packet_in::Decrypt(buffer_t buf) if (status != 0) { auto code = PacketError::ErrorCode::DecryptionFailed; std::string_view message = "Failed to decrypt packet data"; - return tl::make_unexpected(PacketError(code, message)); + return std::unexpected(PacketError(code, message)); } have_decrypted = true; @@ -249,7 +248,7 @@ tl::expected packet_in::Decrypt(buffer_t buf) #endif #ifdef PACKET_ENCRYPTION -tl::expected packet_out::Encrypt() +std::expected packet_out::Encrypt() { assert(have_decrypted); @@ -271,7 +270,7 @@ tl::expected packet_out::Encrypt() if (status != 0) { auto code = PacketError::ErrorCode::EncryptionFailed; std::string_view message = "Failed to encrypt packet data"; - return tl::make_unexpected(PacketError(code, message)); + return std::unexpected(PacketError(code, message)); } have_encrypted = true; diff --git a/Source/dvlnet/packet.h b/Source/dvlnet/packet.h index 2a3bbd7b0..509d2ec92 100644 --- a/Source/dvlnet/packet.h +++ b/Source/dvlnet/packet.h @@ -3,12 +3,11 @@ #include #include #include +#include #include #include #include -#include - #ifdef PACKET_ENCRYPTION #include #endif @@ -175,30 +174,30 @@ public: packet_type Type(); plr_t Source() const; plr_t Destination() const; - tl::expected Message(); - tl::expected Turn(); - tl::expected Cookie(); - tl::expected NewPlayer(); - tl::expected Time(); - tl::expected Info(); - tl::expected LeaveInfo(); + std::expected Message(); + std::expected Turn(); + std::expected Cookie(); + std::expected NewPlayer(); + std::expected Time(); + std::expected Info(); + std::expected LeaveInfo(); }; template class packet_proc : public packet { public: using packet::packet; - tl::expected process_data(); + std::expected process_data(); }; class packet_in : public packet_proc { public: using packet_proc::packet_proc; - tl::expected Create(buffer_t buf); - tl::expected process_element(buffer_t &x); + std::expected Create(buffer_t buf); + std::expected process_element(buffer_t &x); template - tl::expected process_element(T &x); - tl::expected Decrypt(buffer_t buf); + std::expected process_element(T &x); + std::expected Decrypt(buffer_t buf); }; class packet_out : public packet_proc { @@ -208,19 +207,19 @@ public: template void create(Args... args); - tl::expected process_element(buffer_t &x); + std::expected process_element(buffer_t &x); template - tl::expected process_element(const T &x); + std::expected process_element(const T &x); static cookie_t GenerateCookie(); - tl::expected Encrypt(); + std::expected Encrypt(); }; template -tl::expected packet_proc

::process_data() +std::expected packet_proc

::process_data() { P &self = static_cast

(*this); { - tl::expected result + std::expected result = self.process_element(m_type) .and_then([&]() { return self.process_element(m_src); @@ -258,10 +257,10 @@ tl::expected packet_proc

::process_data() case PT_ECHO_REPLY: return self.process_element(m_time); } - return tl::make_unexpected(PacketTypeError(m_type)); + return std::unexpected(PacketTypeError(m_type)); } -inline tl::expected packet_in::process_element(buffer_t &x) +inline std::expected packet_in::process_element(buffer_t &x) { x.insert(x.begin(), decrypted_buffer.begin(), decrypted_buffer.end()); decrypted_buffer.resize(0); @@ -269,12 +268,12 @@ inline tl::expected packet_in::process_element(buffer_t &x) } template -tl::expected packet_in::process_element(T &x) +std::expected packet_in::process_element(T &x) { static_assert(std::is_integral::value || std::is_enum::value, "Unsupported T"); static_assert(sizeof(T) == 4 || sizeof(T) == 2 || sizeof(T) == 1, "Unsupported T"); if (decrypted_buffer.size() < sizeof(T)) { - return tl::make_unexpected(PacketError()); + return std::unexpected(PacketError()); } if (sizeof(T) == 4) { x = static_cast(LoadLE32(decrypted_buffer.data())); @@ -427,14 +426,14 @@ inline void packet_out::create(plr_t s, plr_t d, timestamp_t t) m_time = t; } -inline tl::expected packet_out::process_element(buffer_t &x) +inline std::expected packet_out::process_element(buffer_t &x) { decrypted_buffer.insert(decrypted_buffer.end(), x.begin(), x.end()); return {}; } template -tl::expected packet_out::process_element(const T &x) +std::expected packet_out::process_element(const T &x) { static_assert(std::is_integral::value || std::is_enum::value, "Unsupported T"); static_assert(sizeof(T) == 4 || sizeof(T) == 2 || sizeof(T) == 1, "Unsupported T"); @@ -469,43 +468,43 @@ public: packet_factory(); packet_factory(std::string pw); - tl::expected, PacketError> make_packet(buffer_t buf); + std::expected, PacketError> make_packet(buffer_t buf); template - tl::expected, PacketError> make_packet(Args... args); + std::expected, PacketError> make_packet(Args... args); }; -inline tl::expected, PacketError> packet_factory::make_packet(buffer_t buf) +inline std::expected, PacketError> packet_factory::make_packet(buffer_t buf) { auto ret = std::make_unique(key); #ifndef PACKET_ENCRYPTION - tl::expected isCreated = ret->Create(std::move(buf)); + std::expected isCreated = ret->Create(std::move(buf)); #else - tl::expected isCreated = !secure + std::expected isCreated = !secure ? ret->Create(std::move(buf)) : ret->Decrypt(std::move(buf)); #endif if (!isCreated.has_value()) { - return tl::make_unexpected(isCreated.error()); + return std::unexpected(isCreated.error()); } - if (const tl::expected result = ret->process_data(); !result.has_value()) { - return tl::make_unexpected(result.error()); + if (const std::expected result = ret->process_data(); !result.has_value()) { + return std::unexpected(result.error()); } return ret; } template -tl::expected, PacketError> packet_factory::make_packet(Args... args) +std::expected, PacketError> packet_factory::make_packet(Args... args) { auto ret = std::make_unique(key); ret->create(args...); - if (const tl::expected result = ret->process_data(); !result.has_value()) { - return tl::make_unexpected(result.error()); + if (const std::expected result = ret->process_data(); !result.has_value()) { + return std::unexpected(result.error()); } #ifdef PACKET_ENCRYPTION if (secure) { - tl::expected isEncrypted = ret->Encrypt(); + std::expected isEncrypted = ret->Encrypt(); if (!isEncrypted.has_value()) { - return tl::make_unexpected(isEncrypted.error()); + return std::unexpected(isEncrypted.error()); } } #endif diff --git a/Source/dvlnet/protocol_zt.cpp b/Source/dvlnet/protocol_zt.cpp index 3f3fc1900..0509f5346 100644 --- a/Source/dvlnet/protocol_zt.cpp +++ b/Source/dvlnet/protocol_zt.cpp @@ -92,7 +92,7 @@ void protocol_zt::set_reuseaddr(int fd) lwip_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); } -tl::expected protocol_zt::network_online() +std::expected protocol_zt::network_online() { if (!zerotier_network_ready()) return false; @@ -110,7 +110,7 @@ tl::expected protocol_zt::network_online() if (ret < 0) { std::string_view format = "Error binding to ZeroTier UDP socket: {}"; PacketError error = ProtocolError(format, strerror(errno)); - return tl::make_unexpected(std::move(error)); + return std::unexpected(std::move(error)); } set_nonblock(fd_udp); } @@ -121,13 +121,13 @@ tl::expected protocol_zt::network_online() if (r1 < 0) { std::string_view format = "Error binding to ZeroTier TCP socket: {}"; PacketError error = ProtocolError(format, strerror(errno)); - return tl::make_unexpected(std::move(error)); + return std::unexpected(std::move(error)); } auto r2 = lwip_listen(fd_tcp, 10); if (r2 < 0) { std::string_view format = "Error listening on ZeroTier TCP socket: {}"; PacketError error = ProtocolError(format, strerror(errno)); - return tl::make_unexpected(std::move(error)); + return std::unexpected(std::move(error)); } set_nonblock(fd_tcp); set_nodelay(fd_tcp); @@ -135,17 +135,17 @@ tl::expected protocol_zt::network_online() return true; } -tl::expected protocol_zt::peers_ready() +std::expected protocol_zt::peers_ready() { return network_online() - .map([&](bool isOnline) { return isOnline && zerotier_peers_ready(); }); + .transform([&](bool isOnline) { return isOnline && zerotier_peers_ready(); }); } -tl::expected protocol_zt::send(const endpoint &peer, const buffer_t &data) +std::expected protocol_zt::send(const endpoint &peer, const buffer_t &data) { - tl::expected frame = frame_queue::MakeFrame(data); + std::expected frame = frame_queue::MakeFrame(data); if (!frame.has_value()) - return tl::make_unexpected(frame.error()); + return std::unexpected(frame.error()); peer_list[peer].send_queue.push_back(*frame); return {}; } @@ -168,7 +168,7 @@ bool protocol_zt::send_oob_mc(const buffer_t &data) const return send_oob(mc, data); } -tl::expected protocol_zt::send_queued_peer(const endpoint &peer) +std::expected protocol_zt::send_queued_peer(const endpoint &peer) { peer_state &state = peer_list[peer]; if (state.fd == -1) { @@ -200,7 +200,7 @@ tl::expected protocol_zt::send_queued_peer(const endpoint &pe } else { std::string_view format = "Impossible number of bytes sent: {} available, {} sent"; PacketError error = ProtocolError(format, len, decltype(len)(r)); - return tl::make_unexpected(std::move(error)); + return std::unexpected(std::move(error)); } } return true; @@ -223,7 +223,7 @@ bool protocol_zt::recv_peer(const endpoint &peer) bool protocol_zt::send_queued_all() { for (const auto &[endpoint, _] : peer_list) { - tl::expected result = send_queued_peer(endpoint); + std::expected result = send_queued_peer(endpoint); if (!result.has_value()) { LogError("send_queued_peer: {}", result.error().what()); continue; @@ -302,14 +302,14 @@ bool protocol_zt::recv(endpoint &peer, buffer_t &data) } for (auto &p : peer_list) { - tl::expected ready = p.second.recv_queue.PacketReady(); + std::expected ready = p.second.recv_queue.PacketReady(); if (!ready.has_value()) { LogError("PacketReady: {}", ready.error().what()); continue; } if (!*ready) continue; - tl::expected packet = p.second.recv_queue.ReadPacket(); + std::expected packet = p.second.recv_queue.ReadPacket(); if (!packet.has_value()) { LogError("Failed reading packet data from peer: {}", packet.error().what()); continue; diff --git a/Source/dvlnet/protocol_zt.h b/Source/dvlnet/protocol_zt.h index ed87d400a..245af35a8 100644 --- a/Source/dvlnet/protocol_zt.h +++ b/Source/dvlnet/protocol_zt.h @@ -57,12 +57,12 @@ public: return buffer_t(addr.begin(), addr.end()); } - tl::expected unserialize(const buffer_t &buf) + std::expected unserialize(const buffer_t &buf) { if (buf.size() != 16) { std::string_view format = "Endpoint deserialization expected 16 bytes, got {}"; PacketError error = ProtocolError(format, buf.size()); - return tl::make_unexpected(std::move(error)); + return std::unexpected(std::move(error)); } std::copy(buf.begin(), buf.end(), addr.begin()); return {}; @@ -83,13 +83,13 @@ public: protocol_zt(); ~protocol_zt(); void disconnect(const endpoint &peer); - tl::expected send(const endpoint &peer, const buffer_t &data); + std::expected send(const endpoint &peer, const buffer_t &data); bool send_oob(const endpoint &peer, const buffer_t &data) const; bool send_oob_mc(const buffer_t &data) const; bool recv(endpoint &peer, buffer_t &data); bool get_disconnected(endpoint &peer); - tl::expected network_online(); - tl::expected peers_ready(); + std::expected network_online(); + std::expected peers_ready(); bool is_peer_connected(endpoint &peer); std::optional is_peer_relayed(const endpoint &peer) const; std::optional get_latency_to(const endpoint &peer) const; @@ -119,7 +119,7 @@ private: static void set_nodelay(int fd); static void set_reuseaddr(int fd); - tl::expected send_queued_peer(const endpoint &peer); + std::expected send_queued_peer(const endpoint &peer); bool recv_peer(const endpoint &peer); bool send_queued_all(); bool recv_from_peers(); diff --git a/Source/dvlnet/tcp_client.cpp b/Source/dvlnet/tcp_client.cpp index 5ae6bd286..b8584694d 100644 --- a/Source/dvlnet/tcp_client.cpp +++ b/Source/dvlnet/tcp_client.cpp @@ -1,6 +1,7 @@ #include "dvlnet/tcp_client.h" #include +#include #include #include #include @@ -14,7 +15,6 @@ #endif #include -#include #include #include "options.h" @@ -89,7 +89,7 @@ int tcp_client::join(std::string_view addrstr) StartReceive(); { cookie_self = packet_out::GenerateCookie(); - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty->make_packet( PLR_BROADCAST, PLR_MASTER, cookie_self, game_init_info); if (!pkt.has_value()) { @@ -97,14 +97,14 @@ int tcp_client::join(std::string_view addrstr) SDL_SetError("make_packet: %.*s", static_cast(message.size()), message.data()); return -1; } - tl::expected sendResult = send(**pkt); + std::expected sendResult = send(**pkt); if (!sendResult.has_value()) { const std::string_view message = sendResult.error().what(); SDL_SetError("send: %.*s", static_cast(message.size()), message.data()); return -1; } for (auto i = 0; i < NoSleep; ++i) { - tl::expected pollResult = poll(); + std::expected pollResult = poll(); if (!pollResult.has_value()) { const std::string_view message = pollResult.error().what(); SDL_SetError("%.*s", static_cast(message.size()), message.data()); @@ -129,17 +129,17 @@ bool tcp_client::IsGameHost() return local_server != nullptr; } -tl::expected tcp_client::poll() +std::expected tcp_client::poll() { while (ioc.poll_one() > 0) { if (IsGameHost()) { - tl::expected serverResult = local_server->CheckIoHandlerError(); + std::expected serverResult = local_server->CheckIoHandlerError(); if (!serverResult.has_value()) return serverResult; } if (ioHandlerResult == std::nullopt) continue; - tl::expected packetError = tl::make_unexpected(*ioHandlerResult); + std::expected packetError = std::unexpected(*ioHandlerResult); ioHandlerResult = std::nullopt; return packetError; } @@ -162,7 +162,7 @@ void tcp_client::HandleReceive(const asio::error_code &error, size_t bytesRead) recv_queue.Write(std::move(recv_buffer)); recv_buffer.resize(frame_queue::max_frame_size); while (true) { - tl::expected ready = recv_queue.PacketReady(); + std::expected ready = recv_queue.PacketReady(); if (!ready.has_value()) { RaiseIoHandlerError(ready.error()); return; @@ -173,7 +173,7 @@ void tcp_client::HandleReceive(const asio::error_code &error, size_t bytesRead) HandleTcpErrorCode(); return; } - tl::expected result + std::expected result = recv_queue.ReadPacket() .and_then([this](buffer_t &&pktData) { return pktfty->make_packet(pktData); }) .and_then([this](std::unique_ptr &&pkt) { return RecvLocal(*pkt); }); @@ -200,7 +200,7 @@ void tcp_client::HandleSend(const asio::error_code &error, size_t /*bytesSent*/) void tcp_client::HandleTcpErrorCode() { - tl::expected packet = recv_queue.ReadPacket(); + std::expected packet = recv_queue.ReadPacket(); if (!packet.has_value()) { RaiseIoHandlerError(packet.error()); return; @@ -219,11 +219,11 @@ void tcp_client::HandleTcpErrorCode() RaiseIoHandlerError(fmt::format("Unknown error code received from server: {:#04x}", pktData[0])); } -tl::expected tcp_client::send(packet &pkt) +std::expected tcp_client::send(packet &pkt) { - tl::expected frame = frame_queue::MakeFrame(pkt.Data()); + std::expected frame = frame_queue::MakeFrame(pkt.Data()); if (!frame.has_value()) - return tl::make_unexpected(frame.error()); + return std::unexpected(frame.error()); std::unique_ptr framePtr = std::make_unique(*frame); const asio::mutable_buffer buf = asio::buffer(*framePtr); asio::async_write(sock, buf, [this, frame = std::move(framePtr)](const asio::error_code &error, size_t bytesSent) { diff --git a/Source/dvlnet/tcp_client.h b/Source/dvlnet/tcp_client.h index 4196a7753..eab94a644 100644 --- a/Source/dvlnet/tcp_client.h +++ b/Source/dvlnet/tcp_client.h @@ -30,8 +30,8 @@ public: int create(std::string_view addrstr) override; int join(std::string_view addrstr) override; - tl::expected poll() override; - tl::expected send(packet &pkt) override; + std::expected poll() override; + std::expected send(packet &pkt) override; void DisconnectNet(plr_t plr) override; bool SNetLeaveGame(net::leaveinfo_t type) override; diff --git a/Source/dvlnet/tcp_server.cpp b/Source/dvlnet/tcp_server.cpp index 934421c68..7cfe2b656 100644 --- a/Source/dvlnet/tcp_server.cpp +++ b/Source/dvlnet/tcp_server.cpp @@ -1,12 +1,11 @@ #include "dvlnet/tcp_server.h" #include +#include #include #include #include -#include - #include "dvlnet/base.h" #include "player.h" #include "utils/log.hpp" @@ -78,7 +77,7 @@ void tcp_server::HandleReceive(const scc &con, const asio::error_code &ec, con->recv_queue.Write(std::move(con->recv_buffer)); con->recv_buffer.resize(frame_queue::max_frame_size); while (true) { - tl::expected ready = con->recv_queue.PacketReady(); + std::expected ready = con->recv_queue.PacketReady(); if (!ready.has_value()) { Log("PacketReady: {}", ready.error().what()); DropConnection(con); @@ -86,13 +85,13 @@ void tcp_server::HandleReceive(const scc &con, const asio::error_code &ec, } if (!*ready) break; - tl::expected pktData = con->recv_queue.ReadPacket(); + std::expected pktData = con->recv_queue.ReadPacket(); if (!pktData.has_value()) { Log("ReadPacket: {}", pktData.error().what()); DropConnection(con); return; } - tl::expected, PacketError> pkt = pktfty.make_packet(*pktData); + std::expected, PacketError> pkt = pktfty.make_packet(*pktData); if (!pkt.has_value()) { Log("make_packet: {}", pkt.error().what()); if (pkt.error().code() == PacketError::ErrorCode::DecryptionFailed) @@ -101,7 +100,7 @@ void tcp_server::HandleReceive(const scc &con, const asio::error_code &ec, return; } if (con->plr == PLR_BROADCAST) { - tl::expected result = HandleReceiveNewPlayer(con, **pkt); + std::expected result = HandleReceiveNewPlayer(con, **pkt); if (!result.has_value()) { Log("HandleReceiveNewPlayer: {}", result.error().what()); DropConnection(con); @@ -109,7 +108,7 @@ void tcp_server::HandleReceive(const scc &con, const asio::error_code &ec, } } else { con->timeout = timeout_active; - tl::expected result = HandleReceivePacket(**pkt); + std::expected result = HandleReceivePacket(**pkt); if (!result.has_value()) { Log("Network error: {}", result.error().what()); DropConnection(con); @@ -120,22 +119,22 @@ void tcp_server::HandleReceive(const scc &con, const asio::error_code &ec, StartReceive(con); } -tl::expected tcp_server::HandleReceiveNewPlayer(const scc &con, packet &inPkt) +std::expected tcp_server::HandleReceiveNewPlayer(const scc &con, packet &inPkt) { auto newplr = NextFree(); if (newplr == PLR_BROADCAST) - return tl::make_unexpected(ServerError()); + return std::unexpected(ServerError()); if (Empty()) { - tl::expected pktInfo = inPkt.Info(); + std::expected pktInfo = inPkt.Info(); if (!pktInfo.has_value()) - return tl::make_unexpected(pktInfo.error()); + return std::unexpected(pktInfo.error()); game_init_info = **pktInfo; } for (plr_t player = 0; player < Players.size(); player++) { if (connections[player]) { - tl::expected result + std::expected result = pktfty.make_packet(PLR_MASTER, PLR_BROADCAST, newplr) .and_then([&](std::unique_ptr &&pkt) { return StartSend(connections[player], *pkt); }) .and_then([&]() { return pktfty.make_packet(PLR_MASTER, PLR_BROADCAST, player); }) @@ -145,7 +144,7 @@ tl::expected tcp_server::HandleReceiveNewPlayer(const scc &co } } - tl::expected result + std::expected result = inPkt.Cookie() .and_then([&](cookie_t &&cookie) { return pktfty.make_packet(PLR_MASTER, PLR_BROADCAST, cookie, newplr, game_init_info); }) .and_then([&](std::unique_ptr &&pkt) { return StartSend(con, *pkt); }); @@ -157,47 +156,47 @@ tl::expected tcp_server::HandleReceiveNewPlayer(const scc &co return {}; } -tl::expected tcp_server::HandleReceivePacket(packet &pkt) +std::expected tcp_server::HandleReceivePacket(packet &pkt) { return SendPacket(pkt); } -tl::expected tcp_server::SendPacket(packet &pkt) +std::expected tcp_server::SendPacket(packet &pkt) { if (pkt.Destination() == PLR_BROADCAST) { for (size_t i = 0; i < Players.size(); ++i) { if (i == pkt.Source() || !connections[i]) continue; - tl::expected result = StartSend(connections[i], pkt); + std::expected result = StartSend(connections[i], pkt); if (!result.has_value()) LogError("Failed to send packet {} to player {}: {}", static_cast(pkt.Type()), i, result.error().what()); } return {}; } if (pkt.Destination() >= MAX_PLRS) - return tl::make_unexpected(ServerError()); + return std::unexpected(ServerError()); if (pkt.Destination() == pkt.Source() || !connections[pkt.Destination()]) return {}; return StartSend(connections[pkt.Destination()], pkt); } -tl::expected tcp_server::StartSend(const scc &con, packet &pkt) +std::expected tcp_server::StartSend(const scc &con, packet &pkt) { return StartSend(con, pkt.Data(), 0); } -tl::expected tcp_server::StartSend(const scc &con, PacketError::ErrorCode errorCode) +std::expected tcp_server::StartSend(const scc &con, PacketError::ErrorCode errorCode) { buffer_t pktData; pktData.push_back(static_cast(errorCode)); return StartSend(con, pktData, TcpErrorCodeFlags); } -tl::expected tcp_server::StartSend(const scc &con, buffer_t pktData, uint16_t flags) +std::expected tcp_server::StartSend(const scc &con, buffer_t pktData, uint16_t flags) { - tl::expected frame = frame_queue::MakeFrame(pktData, flags); + std::expected frame = frame_queue::MakeFrame(pktData, flags); if (!frame.has_value()) - return tl::make_unexpected(frame.error()); + return std::unexpected(frame.error()); std::unique_ptr framePtr = std::make_unique(*frame); const asio::mutable_buffer buf = asio::buffer(*framePtr); asio::async_write(con->socket, buf, @@ -279,7 +278,7 @@ void tcp_server::DropConnection(const scc &con) } connections[plr] = nullptr; - tl::expected, PacketError> pkt + std::expected, PacketError> pkt = pktfty.make_packet(PLR_MASTER, PLR_BROADCAST, plr, leaveinfo_t::LEAVE_DROP); if (pkt.has_value()) { @@ -294,11 +293,11 @@ void tcp_server::RaiseIoHandlerError(const PacketError &error) ioHandlerResult.emplace(error); } -tl::expected tcp_server::CheckIoHandlerError() +std::expected tcp_server::CheckIoHandlerError() { if (ioHandlerResult == std::nullopt) return {}; - tl::expected packetError = tl::make_unexpected(*ioHandlerResult); + std::expected packetError = std::unexpected(*ioHandlerResult); ioHandlerResult = std::nullopt; return packetError; } diff --git a/Source/dvlnet/tcp_server.h b/Source/dvlnet/tcp_server.h index 5d33ddc60..71f397391 100644 --- a/Source/dvlnet/tcp_server.h +++ b/Source/dvlnet/tcp_server.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -13,8 +14,6 @@ // the 3DS SDK. #include -#include - #include #include #include @@ -40,7 +39,7 @@ public: tcp_server(asio::io_context &ioc, const std::string &bindaddr, unsigned short port, packet_factory &pktfty); std::string LocalhostSelf(); - tl::expected CheckIoHandlerError(); + std::expected CheckIoHandlerError(); void DisconnectNet(plr_t plr); void Close(); virtual ~tcp_server(); @@ -80,12 +79,12 @@ private: void HandleAccept(const scc &con, const asio::error_code &ec); void StartReceive(const scc &con); void HandleReceive(const scc &con, const asio::error_code &ec, size_t bytesRead); - tl::expected HandleReceiveNewPlayer(const scc &con, packet &pkt); - tl::expected HandleReceivePacket(packet &pkt); - tl::expected SendPacket(packet &pkt); - tl::expected StartSend(const scc &con, packet &pkt); - tl::expected StartSend(const scc &con, PacketError::ErrorCode errorCode); - tl::expected StartSend(const scc &con, buffer_t pktData, uint16_t flags); + std::expected HandleReceiveNewPlayer(const scc &con, packet &pkt); + std::expected HandleReceivePacket(packet &pkt); + std::expected SendPacket(packet &pkt); + std::expected StartSend(const scc &con, packet &pkt); + std::expected StartSend(const scc &con, PacketError::ErrorCode errorCode); + std::expected StartSend(const scc &con, buffer_t pktData, uint16_t flags); void HandleSend(const scc &con, const asio::error_code &ec, size_t bytesSent); void StartTimeout(const scc &con); void HandleTimeout(const scc &con, const asio::error_code &ec); diff --git a/Source/effects.cpp b/Source/effects.cpp index eb4841a39..6252764c9 100644 --- a/Source/effects.cpp +++ b/Source/effects.cpp @@ -6,9 +6,9 @@ #include "effects.h" #include +#include #include -#include #include #include "data/file.hpp" @@ -126,7 +126,7 @@ SfxID RndSFX(SfxID psfx) } } -tl::expected ParseSfxFlag(std::string_view value) +std::expected ParseSfxFlag(std::string_view value) { if (value == "Stream") return sfx_STREAM; if (value == "Misc") return sfx_MISC; @@ -135,7 +135,7 @@ tl::expected ParseSfxFlag(std::string_view value) if (value == "Rogue") return sfx_ROGUE; if (value == "Warrior") return sfx_WARRIOR; if (value == "Sorcerer") return sfx_SORCERER; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } void LoadEffectsData() @@ -329,22 +329,22 @@ int GetSFXLength(SfxID nSFX) return sfx.pSnd->DSB.GetLength(); } -tl::expected ParseHeroSpeech(std::string_view value) +std::expected ParseHeroSpeech(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value."); + return std::unexpected("Unknown enum value."); } -tl::expected ParseSfxId(std::string_view value) +std::expected ParseSfxId(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value."); + return std::unexpected("Unknown enum value."); } } // namespace devilution diff --git a/Source/effects.h b/Source/effects.h index e10743279..a2a3adb1d 100644 --- a/Source/effects.h +++ b/Source/effects.h @@ -6,11 +6,10 @@ #pragma once #include +#include #include #include -#include - #include "engine/sound.h" #include "sound_effect_enums.h" @@ -37,7 +36,7 @@ void ui_sound_init(); void effects_play_sound(SfxID); int GetSFXLength(SfxID nSFX); -tl::expected ParseHeroSpeech(std::string_view value); -tl::expected ParseSfxId(std::string_view value); +std::expected ParseHeroSpeech(std::string_view value); +std::expected ParseSfxId(std::string_view value); } // namespace devilution diff --git a/Source/effects_stubs.cpp b/Source/effects_stubs.cpp index 38702061b..6c750f9b9 100644 --- a/Source/effects_stubs.cpp +++ b/Source/effects_stubs.cpp @@ -1,7 +1,7 @@ // Stubbed implementations of effects for the NOSOUND mode. #include "effects.h" -#include +#include #include #include "engine/random.hpp" @@ -50,22 +50,22 @@ void ui_sound_init() { } void effects_play_sound(SfxID id) { } int GetSFXLength(SfxID nSFX) { return 0; } -tl::expected ParseHeroSpeech(std::string_view value) +std::expected ParseHeroSpeech(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value."); + return std::unexpected("Unknown enum value."); } -tl::expected ParseSfxId(std::string_view value) +std::expected ParseSfxId(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value."); + return std::unexpected("Unknown enum value."); } } // namespace devilution diff --git a/Source/engine/assets.cpp b/Source/engine/assets.cpp index 02cbfa129..2452a7363 100644 --- a/Source/engine/assets.cpp +++ b/Source/engine/assets.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -311,11 +312,11 @@ SDL_IOStream *OpenAssetAsSdlRwOps(std::string_view filename, bool threadsafe) #endif } -tl::expected LoadAsset(std::string_view path) +std::expected LoadAsset(std::string_view path) { AssetRef ref = FindAsset(path); if (!ref.ok()) { - return tl::make_unexpected(StrCat("Asset not found: ", path)); + return std::unexpected(StrCat("Asset not found: ", path)); } const size_t size = ref.size(); @@ -323,21 +324,21 @@ tl::expected LoadAsset(std::string_view path) AssetHandle handle = OpenAsset(std::move(ref)); if (!handle.ok()) { - return tl::make_unexpected(StrCat("Failed to open asset: ", path, "\n", handle.error())); + return std::unexpected(StrCat("Failed to open asset: ", path, "\n", handle.error())); } if (size > 0 && !handle.read(data.get(), size)) { - return tl::make_unexpected(StrCat("Read failed: ", path, "\n", handle.error())); + return std::unexpected(StrCat("Read failed: ", path, "\n", handle.error())); } return AssetData { std::move(data), size }; } -tl::expected LoadIntegralAsset(std::string_view path) +std::expected LoadIntegralAsset(std::string_view path) { AssetRef ref = FindAsset(path); if (!ref.ok()) { - return tl::make_unexpected(StrCat("Asset not found: ", path)); + return std::unexpected(StrCat("Asset not found: ", path)); } const size_t size = ref.size(); @@ -345,11 +346,11 @@ tl::expected LoadIntegralAsset(std::string_view path) AssetHandle handle = OpenIntegralAsset(std::move(ref)); if (!handle.ok()) { - return tl::make_unexpected(StrCat("Failed to open asset: ", path, "\n", handle.error())); + return std::unexpected(StrCat("Failed to open asset: ", path, "\n", handle.error())); } if (size > 0 && !handle.read(data.get(), size)) { - return tl::make_unexpected(StrCat("Read failed: ", path, "\n", handle.error())); + return std::unexpected(StrCat("Read failed: ", path, "\n", handle.error())); } return AssetData { std::move(data), size }; @@ -415,7 +416,7 @@ bool LoadMPQ(std::span paths, std::string_view mpqName, int p mpqAbsPath = StrCat(path, mpqName, ext); if (!FileExists(mpqAbsPath)) continue; - tl::expected archive = MpqArchive::Open(mpqAbsPath.c_str()); + std::expected archive = MpqArchive::Open(mpqAbsPath.c_str()); if (!archive.has_value()) { foundButFailed = true; LogError("Error {}: {}", archive.error(), mpqAbsPath); @@ -607,22 +608,22 @@ void UnloadModArchives() #ifndef UNPACKED_MPQS namespace { -tl::expected ReadPackedModManifestFrom(MpqArchive &archive) +std::expected ReadPackedModManifestFrom(MpqArchive &archive) { constexpr std::string_view ManifestName = "manifest.ini"; if (!archive.HasFile(ManifestName)) - return tl::make_unexpected(0); + return std::unexpected(0); size_t fileSize = 0; int32_t error = 0; std::unique_ptr data = archive.ReadFile(ManifestName, fileSize, error); if (data == nullptr) - return tl::make_unexpected(error); + return std::unexpected(error); return ParseModManifest(std::string_view(reinterpret_cast(data.get()), fileSize)); } -tl::expected ReadPackedModManifest(std::span paths, std::string_view modname) +std::expected ReadPackedModManifest(std::span paths, std::string_view modname) { const std::string mpqName = StrCat("mods" DIRECTORY_SEPARATOR_STR, modname); std::string mpqAbsPath; @@ -630,12 +631,12 @@ tl::expected ReadPackedModManifest(std::span archive = MpqArchive::Open(mpqAbsPath.c_str()); + std::expected archive = MpqArchive::Open(mpqAbsPath.c_str()); if (!archive.has_value()) - return tl::make_unexpected(0); + return std::unexpected(0); return ReadPackedModManifestFrom(*archive); } - return tl::make_unexpected(0); + return std::unexpected(0); } // Reads the mod's `manifest.ini` from its own archive (registered at `priority`) and @@ -647,7 +648,7 @@ void ReadLoadedModManifest(ModIdentifier &mod, int priority) if (it == MpqArchives.end()) return; MpqArchive &archive = it->second; - tl::expected manifest = ReadPackedModManifestFrom(archive); + std::expected manifest = ReadPackedModManifestFrom(archive); if (manifest.has_value()) mod.manifest = std::move(*manifest); else if (manifest.error() != 0) @@ -659,7 +660,7 @@ void ReadLoadedModManifest(ModIdentifier &mod, int priority) // the mod has no packed archive, no manifest, or an unreadable one. std::vector ReadPackedModRequiredMods(std::span paths, std::string_view modname) { - tl::expected manifest = ReadPackedModManifest(paths, modname); + std::expected manifest = ReadPackedModManifest(paths, modname); if (!manifest.has_value()) return {}; return std::move(manifest->requiredMods); @@ -693,7 +694,7 @@ ModManifest ReadModManifestByName(std::string_view name) #ifndef UNPACKED_MPQS // Packed mod archive. - tl::expected manifest = ReadPackedModManifest(searchPaths, name); + std::expected manifest = ReadPackedModManifest(searchPaths, name); if (manifest.has_value()) return std::move(*manifest); #endif diff --git a/Source/engine/assets.hpp b/Source/engine/assets.hpp index 0094b1745..8bb275191 100644 --- a/Source/engine/assets.hpp +++ b/Source/engine/assets.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -17,8 +18,6 @@ #include #endif -#include - #include #include "appfat.h" @@ -298,8 +297,8 @@ struct AssetData { } }; -tl::expected LoadAsset(std::string_view path); -tl::expected LoadIntegralAsset(std::string_view path); +std::expected LoadAsset(std::string_view path); +std::expected LoadIntegralAsset(std::string_view path); #ifdef UNPACKED_MPQS using MpqArchiveT = std::string; diff --git a/Source/engine/load_cel.cpp b/Source/engine/load_cel.cpp index 5adc1a365..c497ab16f 100644 --- a/Source/engine/load_cel.cpp +++ b/Source/engine/load_cel.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -9,8 +10,6 @@ #include #endif -#include - #include "appfat.h" #include "mpq/mpq_common.hpp" #include "utils/status_macros.hpp" @@ -25,7 +24,7 @@ namespace devilution { -tl::expected LoadCelListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths) +std::expected LoadCelListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths) { char path[MaxMpqPathSize]; *BufCopy(path, pszName, DEVILUTIONX_CEL_EXT) = '\0'; @@ -43,7 +42,7 @@ tl::expected LoadCelListOrSheetWithStatu OwnedClxSpriteListOrSheet LoadCelListOrSheet(const char *pszName, PointerOrValue widthOrWidths) { - tl::expected result = LoadCelListOrSheetWithStatus(pszName, widthOrWidths); + std::expected result = LoadCelListOrSheetWithStatus(pszName, widthOrWidths); if (DVL_PREDICT_FALSE(!result.has_value())) app_fatal(result.error()); return std::move(result).value(); } diff --git a/Source/engine/load_cel.hpp b/Source/engine/load_cel.hpp index 501556281..58917fb5e 100644 --- a/Source/engine/load_cel.hpp +++ b/Source/engine/load_cel.hpp @@ -1,10 +1,9 @@ #pragma once #include +#include #include -#include - #include "engine/clx_sprite.hpp" #include "utils/pointer_value_union.hpp" #include "utils/status_macros.hpp" @@ -17,7 +16,7 @@ namespace devilution { -tl::expected LoadCelListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths); +std::expected LoadCelListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths); OwnedClxSpriteListOrSheet LoadCelListOrSheet(const char *pszName, PointerOrValue widthOrWidths); @@ -28,13 +27,13 @@ inline OwnedClxSpriteList LoadCel(const char *pszName, uint16_t width) inline OptionalOwnedClxSpriteList LoadOptionalCel(const char *pszName, uint16_t width) { - tl::expected result = LoadCelListOrSheetWithStatus(pszName, PointerOrValue { width }); + std::expected result = LoadCelListOrSheetWithStatus(pszName, PointerOrValue { width }); if (!result.has_value()) return std::nullopt; return (*std::move(result)).list(); } -inline tl::expected LoadCelWithStatus(const char *pszName, uint16_t width) +inline std::expected LoadCelWithStatus(const char *pszName, uint16_t width) { ASSIGN_OR_RETURN(OwnedClxSpriteListOrSheet result, LoadCelListOrSheetWithStatus(pszName, PointerOrValue { width })); return std::move(result).list(); @@ -47,13 +46,13 @@ inline OwnedClxSpriteList LoadCel(const char *pszName, const uint16_t *widths) inline OptionalOwnedClxSpriteList LoadOptionalCel(const char *pszName, const uint16_t *widths) { - tl::expected result = LoadCelListOrSheetWithStatus(pszName, PointerOrValue { widths }); + std::expected result = LoadCelListOrSheetWithStatus(pszName, PointerOrValue { widths }); if (!result.has_value()) return std::nullopt; return (*std::move(result)).list(); } -inline tl::expected LoadCelWithStatus(const char *pszName, const uint16_t *widths) +inline std::expected LoadCelWithStatus(const char *pszName, const uint16_t *widths) { ASSIGN_OR_RETURN(OwnedClxSpriteListOrSheet result, LoadCelListOrSheetWithStatus(pszName, PointerOrValue { widths })); return std::move(result).list(); diff --git a/Source/engine/load_cl2.cpp b/Source/engine/load_cl2.cpp index 499c51731..a13c5f593 100644 --- a/Source/engine/load_cl2.cpp +++ b/Source/engine/load_cl2.cpp @@ -1,11 +1,10 @@ #include "engine/load_cl2.hpp" #include +#include #include #include -#include - #include "mpq/mpq_common.hpp" #include "utils/status_macros.hpp" #include "utils/str_cat.hpp" @@ -19,7 +18,7 @@ namespace devilution { -tl::expected LoadCl2ListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths) +std::expected LoadCl2ListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths) { char path[MaxMpqPathSize]; *BufCopy(path, pszName, DEVILUTIONX_CL2_EXT) = '\0'; @@ -34,7 +33,7 @@ tl::expected LoadCl2ListOrSheetWithStatu OwnedClxSpriteListOrSheet LoadCl2ListOrSheet(const char *pszName, PointerOrValue widthOrWidths) { - tl::expected result = LoadCl2ListOrSheetWithStatus(pszName, widthOrWidths); + std::expected result = LoadCl2ListOrSheetWithStatus(pszName, widthOrWidths); if (!result.has_value()) app_fatal(result.error()); return std::move(result).value(); } diff --git a/Source/engine/load_cl2.hpp b/Source/engine/load_cl2.hpp index 46d46bca3..2fe076488 100644 --- a/Source/engine/load_cl2.hpp +++ b/Source/engine/load_cl2.hpp @@ -3,9 +3,9 @@ #include #include #include +#include #include -#include #include #include "appfat.h" @@ -29,11 +29,11 @@ namespace devilution { -tl::expected LoadCl2ListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths); +std::expected LoadCl2ListOrSheetWithStatus(const char *pszName, PointerOrValue widthOrWidths); OwnedClxSpriteListOrSheet LoadCl2ListOrSheet(const char *pszName, PointerOrValue widthOrWidths); template -tl::expected LoadMultipleCl2Sheet(tl::function_ref filenames, size_t count, uint16_t width) +std::expected LoadMultipleCl2Sheet(tl::function_ref filenames, size_t count, uint16_t width) { StaticVector, MaxCount> paths; StaticVector files; @@ -76,7 +76,7 @@ tl::expected LoadMultipleCl2Sheet(tl::function #endif } -inline tl::expected LoadCl2WithStatus(const char *pszName, uint16_t width) +inline std::expected LoadCl2WithStatus(const char *pszName, uint16_t width) { ASSIGN_OR_RETURN(OwnedClxSpriteListOrSheet result, LoadCl2ListOrSheetWithStatus(pszName, PointerOrValue { width })); return std::move(result).list(); diff --git a/Source/engine/load_clx.cpp b/Source/engine/load_clx.cpp index 1db52a0fb..f0c71bf96 100644 --- a/Source/engine/load_clx.cpp +++ b/Source/engine/load_clx.cpp @@ -2,8 +2,7 @@ #include #include - -#include +#include #include "appfat.h" #include "engine/assets.hpp" @@ -26,17 +25,17 @@ OptionalOwnedClxSpriteListOrSheet LoadOptionalClxListOrSheet(const char *path) return OwnedClxSpriteListOrSheet::FromBuffer(std::move(data), size); } -tl::expected LoadClxListOrSheetWithStatus(const char *path) +std::expected LoadClxListOrSheetWithStatus(const char *path) { size_t size; - tl::expected, std::string> data = LoadFileInMemWithStatus(path, &size); - if (!data.has_value()) return tl::make_unexpected(std::move(data).error()); + std::expected, std::string> data = LoadFileInMemWithStatus(path, &size); + if (!data.has_value()) return std::unexpected(std::move(data).error()); return OwnedClxSpriteListOrSheet::FromBuffer(std::move(data).value(), size); } OwnedClxSpriteListOrSheet LoadClxListOrSheet(const char *path) { - tl::expected result = LoadClxListOrSheetWithStatus(path); + std::expected result = LoadClxListOrSheetWithStatus(path); if (!result.has_value()) app_fatal(result.error()); return std::move(result).value(); } diff --git a/Source/engine/load_clx.hpp b/Source/engine/load_clx.hpp index 5a74037cc..437b15011 100644 --- a/Source/engine/load_clx.hpp +++ b/Source/engine/load_clx.hpp @@ -1,9 +1,8 @@ #pragma once +#include #include -#include - #include "clx_sprite.hpp" #include "utils/status_macros.hpp" @@ -11,14 +10,14 @@ namespace devilution { OwnedClxSpriteListOrSheet LoadClxListOrSheet(const char *path); -tl::expected LoadClxListOrSheetWithStatus(const char *path); +std::expected LoadClxListOrSheetWithStatus(const char *path); inline OwnedClxSpriteList LoadClx(const char *path) { return LoadClxListOrSheet(path).list(); } -inline tl::expected LoadClxWithStatus(const char *path) +inline std::expected LoadClxWithStatus(const char *path) { ASSIGN_OR_RETURN(OwnedClxSpriteListOrSheet result, LoadClxListOrSheetWithStatus(path)); return std::move(result).list(); diff --git a/Source/engine/load_file.hpp b/Source/engine/load_file.hpp index 88490a187..0226db659 100644 --- a/Source/engine/load_file.hpp +++ b/Source/engine/load_file.hpp @@ -4,10 +4,9 @@ #include #include #include +#include #include -#include - #include "appfat.h" #include "engine/assets.hpp" #include "mpq/mpq_common.hpp" @@ -17,35 +16,35 @@ namespace devilution { template -tl::expected LoadFileInMemWithStatus(const char *path, T *data) +std::expected LoadFileInMemWithStatus(const char *path, T *data) { size_t size; AssetHandle handle = OpenAsset(path, size); if (!handle.ok()) { - return tl::make_unexpected(FailedToOpenFileErrorMessage(path, handle.error())); + return std::unexpected(FailedToOpenFileErrorMessage(path, handle.error())); } if ((size % sizeof(T)) != 0) { - return tl::make_unexpected(StrCat("File size does not align with type\n", path)); + return std::unexpected(StrCat("File size does not align with type\n", path)); } if (!handle.read(data, size)) { - return tl::make_unexpected("handle.read failed"); + return std::unexpected("handle.read failed"); } return {}; } template -tl::expected LoadIntegralFileInMemWithStatus(const char *path, T *data) +std::expected LoadIntegralFileInMemWithStatus(const char *path, T *data) { size_t size; AssetHandle handle = OpenIntegralAsset(path, size); if (!handle.ok()) { - return tl::make_unexpected(FailedToOpenFileErrorMessage(path, handle.error())); + return std::unexpected(FailedToOpenFileErrorMessage(path, handle.error())); } if ((size % sizeof(T)) != 0) { - return tl::make_unexpected(StrCat("File size does not align with type\n", path)); + return std::unexpected(StrCat("File size does not align with type\n", path)); } if (!handle.read(data, size)) { - return tl::make_unexpected("handle.read failed"); + return std::unexpected("handle.read failed"); } return {}; } @@ -53,19 +52,19 @@ tl::expected LoadIntegralFileInMemWithStatus(const char *path template void LoadFileInMem(const char *path, T *data) { - const tl::expected result = LoadFileInMemWithStatus(path, data); + const std::expected result = LoadFileInMemWithStatus(path, data); if (!result.has_value()) app_fatal(result.error()); } template -tl::expected LoadFileInMemWithStatus(const char *path, T *data, std::size_t count) +std::expected LoadFileInMemWithStatus(const char *path, T *data, std::size_t count) { AssetHandle handle = OpenAsset(path); if (!handle.ok()) { - return tl::make_unexpected(FailedToOpenFileErrorMessage(path, handle.error())); + return std::unexpected(FailedToOpenFileErrorMessage(path, handle.error())); } if (!handle.read(data, count * sizeof(T))) { - return tl::make_unexpected("handle.read failed"); + return std::unexpected("handle.read failed"); } return {}; } @@ -73,7 +72,7 @@ tl::expected LoadFileInMemWithStatus(const char *path, T *dat template void LoadFileInMem(const char *path, T *data, std::size_t count) { - tl::expected result = LoadFileInMemWithStatus(path, data, count); + std::expected result = LoadFileInMemWithStatus(path, data, count); if (!result.has_value()) app_fatal(result.error()); } @@ -85,7 +84,7 @@ bool LoadOptionalFileInMem(const char *path, T *data, std::size_t count) } template -tl::expected LoadFileInMemWithStatus(const char *path, std::array &data) +std::expected LoadFileInMemWithStatus(const char *path, std::array &data) { return LoadFileInMemWithStatus(path, data.data(), N); } @@ -97,15 +96,15 @@ void LoadFileInMem(const char *path, std::array &data) } template -tl::expected, std::string> LoadFileInMemWithStatus(const char *path, std::size_t *numRead = nullptr) +std::expected, std::string> LoadFileInMemWithStatus(const char *path, std::size_t *numRead = nullptr) { size_t size; AssetHandle handle = OpenAsset(path, size); if (!handle.ok()) { - return tl::make_unexpected(FailedToOpenFileErrorMessage(path, handle.error())); + return std::unexpected(FailedToOpenFileErrorMessage(path, handle.error())); } if ((size % sizeof(T)) != 0) { - return tl::make_unexpected(StrCat("File size does not align with type\n", path)); + return std::unexpected(StrCat("File size does not align with type\n", path)); } if (numRead != nullptr) @@ -113,7 +112,7 @@ tl::expected, std::string> LoadFileInMemWithStatus(const ch std::unique_ptr buf { new T[size / sizeof(T)] }; if (!handle.read(buf.get(), size)) { - return tl::make_unexpected("handle.read failed"); + return std::unexpected("handle.read failed"); } return { std::move(buf) }; } @@ -127,7 +126,7 @@ tl::expected, std::string> LoadFileInMemWithStatus(const ch template std::unique_ptr LoadFileInMem(const char *path, std::size_t *numRead = nullptr) { - tl::expected, std::string> result = LoadFileInMemWithStatus(path, numRead); + std::expected, std::string> result = LoadFileInMemWithStatus(path, numRead); if (!result.has_value()) app_fatal(result.error()); return std::move(result).value(); } diff --git a/Source/engine/sound.cpp b/Source/engine/sound.cpp index ddeb43bc6..56a8adce9 100644 --- a/Source/engine/sound.cpp +++ b/Source/engine/sound.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -23,7 +24,6 @@ #include #include #endif -#include #include "appfat.h" #include "engine/assets.hpp" @@ -64,7 +64,7 @@ std::string GetMp3Path(const char *path) return mp3Path; } -tl::expected LoadAudioFile(const char *path, bool stream, SoundSample &result) +std::expected LoadAudioFile(const char *path, bool stream, SoundSample &result) { bool isMp3 = true; std::string foundPath = GetMp3Path(path); @@ -75,7 +75,7 @@ tl::expected LoadAudioFile(const char *path, bool stream, Sou isMp3 = false; } if (!ref.ok()) { - return tl::make_unexpected(StrCat("Audio file not found\n", path, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); + return std::unexpected(StrCat("Audio file not found\n", path, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); } #ifdef STREAM_ALL_AUDIO_MIN_FILE_SIZE @@ -92,7 +92,7 @@ tl::expected LoadAudioFile(const char *path, bool stream, Sou if (stream) { if (result.SetChunkStream(foundPath, isMp3, /*logErrors=*/true) != 0) { - return tl::make_unexpected(StrCat("Failed to load audio file\n", foundPath, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); + return std::unexpected(StrCat("Failed to load audio file\n", foundPath, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); } } else { #if !defined(STREAM_ALL_AUDIO_MIN_FILE_SIZE) || STREAM_ALL_AUDIO_MIN_FILE_SIZE == 0 @@ -100,15 +100,15 @@ tl::expected LoadAudioFile(const char *path, bool stream, Sou #endif AssetHandle handle = OpenAsset(std::move(ref)); if (!handle.ok()) { - return tl::make_unexpected(StrCat("Failed to load audio file\n", foundPath, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); + return std::unexpected(StrCat("Failed to load audio file\n", foundPath, "\n", SDL_GetError(), "\n" __FILE__ ":", __LINE__)); } auto waveFile = MakeArraySharedPtr(size); if (!handle.read(waveFile.get(), size)) { - return tl::make_unexpected(StrCat("Failed to read file\n", foundPath, ": ", SDL_GetError(), __FILE__ ":", __LINE__)); + return std::unexpected(StrCat("Failed to read file\n", foundPath, ": ", SDL_GetError(), __FILE__ ":", __LINE__)); } const int error = result.SetChunk(waveFile, size, isMp3); if (error != 0) { - return tl::make_unexpected(SDL_GetError()); + return std::unexpected(SDL_GetError()); } } return {}; @@ -224,7 +224,7 @@ void snd_play_snd(TSnd *pSnd, int lVolume, int lPan, int userVolume) pSnd->start_tc = tc; } -tl::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream) +std::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream) { auto snd = std::make_unique(); snd->start_tc = SDL_GetTicks() - 80 - 1; @@ -236,7 +236,7 @@ tl::expected, std::string> SoundFileLoadWithStatus(const c std::unique_ptr sound_file_load(const char *path, bool stream) { - tl::expected, std::string> result = SoundFileLoadWithStatus(path, stream); + std::expected, std::string> result = SoundFileLoadWithStatus(path, stream); if (!result.has_value()) app_fatal(result.error()); return std::move(result).value(); } diff --git a/Source/engine/sound.h b/Source/engine/sound.h index 6167c3929..ce4aea1ad 100644 --- a/Source/engine/sound.h +++ b/Source/engine/sound.h @@ -6,12 +6,11 @@ #pragma once #include +#include #include #include #include -#include - #include "levels/gendung.h" #include "utils/attributes.h" @@ -69,7 +68,7 @@ extern _music_id sgnMusicTrack; void ClearDuplicateSounds(); void snd_play_snd(TSnd *pSnd, int lVolume, int lPan, int userVolume); std::unique_ptr sound_file_load(const char *path, bool stream = false); -tl::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream = false); +std::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream = false); void snd_init(); void snd_deinit(); _music_id GetLevelMusic(dungeon_type dungeonType); diff --git a/Source/engine/sound_stubs.cpp b/Source/engine/sound_stubs.cpp index 3fcefd04c..587ba2ebc 100644 --- a/Source/engine/sound_stubs.cpp +++ b/Source/engine/sound_stubs.cpp @@ -11,7 +11,7 @@ _music_id sgnMusicTrack = NUM_MUSIC; void ClearDuplicateSounds() { } void snd_play_snd(TSnd *pSnd, int lVolume, int lPan, int userVolume) { } std::unique_ptr sound_file_load(const char *path, bool stream) { return nullptr; } -tl::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream) { return nullptr; } +std::expected, std::string> SoundFileLoadWithStatus(const char *path, bool stream) { return nullptr; } TSnd::~TSnd() { } void snd_init() { } void snd_deinit() { } diff --git a/Source/gamemenu.cpp b/Source/gamemenu.cpp index f1f997c75..d99690700 100644 --- a/Source/gamemenu.cpp +++ b/Source/gamemenu.cpp @@ -309,7 +309,7 @@ void gamemenu_load_game(bool /*bActivate*/) DeactivateVirtualGamepad(); FreeVirtualGamepadTextures(); #endif - if (tl::expected result = LoadGame(false); !result.has_value()) { + if (std::expected result = LoadGame(false); !result.has_value()) { app_fatal(result.error()); } #if !defined(USE_SDL1) && !defined(__vita__) diff --git a/Source/interfac.cpp b/Source/interfac.cpp index 5fe61d4bb..32d958cba 100644 --- a/Source/interfac.cpp +++ b/Source/interfac.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include #include @@ -20,8 +21,6 @@ #include #endif -#include - #include "control/control.hpp" #include "controls/input.h" #include "engine/clx_sprite.hpp" @@ -317,7 +316,7 @@ void DoLoad(interface_mode uMsg) IncProgress(); Player &myPlayer = *MyPlayer; - tl::expected loadResult; + std::expected loadResult; switch (uMsg) { case WM_DIABLOADGAME: IncProgress(2); @@ -464,7 +463,7 @@ void DoLoad(interface_mode uMsg) if (loadResult.has_value()) IncProgress(); break; default: - loadResult = tl::make_unexpected("Unknown progress mode"); + loadResult = std::unexpected("Unknown progress mode"); break; } diff --git a/Source/levels/gendung.cpp b/Source/levels/gendung.cpp index cf66a0440..fd3091168 100644 --- a/Source/levels/gendung.cpp +++ b/Source/levels/gendung.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,7 +10,6 @@ #include #include -#include #include #include "engine/clx_sprite.hpp" @@ -439,7 +439,7 @@ void CreateDungeon(uint32_t rseed, lvl_entry entry) Make_SetPC(SetPiece); } -tl::expected LoadLevelSOLData() +std::expected LoadLevelSOLData() { switch (leveltype) { case DTYPE_TOWN: @@ -501,7 +501,7 @@ tl::expected LoadLevelSOLData() SOLData[142] = TileProperties::None; // Tile is incorrectly marked as being solid break; default: - return tl::make_unexpected("LoadLevelSOLData"); + return std::unexpected("LoadLevelSOLData"); } return {}; } @@ -833,7 +833,7 @@ void FloodTransparencyValues(uint8_t floorID) } } -tl::expected ParseDungeonType(std::string_view value) +std::expected ParseDungeonType(std::string_view value) { if (value.empty()) return DTYPE_NONE; if (value == "DTYPE_TOWN") return DTYPE_TOWN; @@ -843,16 +843,16 @@ tl::expected ParseDungeonType(std::string_view value) if (value == "DTYPE_HELL") return DTYPE_HELL; if (value == "DTYPE_NEST") return DTYPE_NEST; if (value == "DTYPE_CRYPT") return DTYPE_CRYPT; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected<_setlevels, std::string> ParseSetLevel(std::string_view value) +std::expected<_setlevels, std::string> ParseSetLevel(std::string_view value) { const std::optional<_setlevels> enumValueOpt = magic_enum::enum_cast<_setlevels>(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } } // namespace devilution diff --git a/Source/levels/gendung.h b/Source/levels/gendung.h index 090c14fa3..dbd1ac696 100644 --- a/Source/levels/gendung.h +++ b/Source/levels/gendung.h @@ -7,13 +7,12 @@ #include #include +#include #include #include #include #include -#include - #include "engine/clx_sprite.hpp" #include "engine/point.hpp" #include "engine/rectangle.hpp" @@ -58,8 +57,8 @@ inline bool IsArenaLevel(_setlevels setLevel) } } -tl::expected ParseDungeonType(std::string_view value); -tl::expected<_setlevels, std::string> ParseSetLevel(std::string_view value); +std::expected ParseDungeonType(std::string_view value); +std::expected<_setlevels, std::string> ParseSetLevel(std::string_view value); enum class DungeonFlag : uint8_t { // clang-format off @@ -298,7 +297,7 @@ struct Miniset { return HasAnyOf(SOLData[dPiece[coords.x][coords.y]], property); } -tl::expected LoadLevelSOLData(); +std::expected LoadLevelSOLData(); void SetDungeonMicros(std::unique_ptr &dungeonCels, uint_fast8_t µTileLen); void DRLG_InitTrans(); void DRLG_MRectTrans(WorldTilePosition origin, WorldTilePosition extent); diff --git a/Source/lighting.cpp b/Source/lighting.cpp index a88256b1f..0df043d6d 100644 --- a/Source/lighting.cpp +++ b/Source/lighting.cpp @@ -8,11 +8,10 @@ #include #include #include +#include #include #include -#include - #include "automap.h" #include "engine/displacement.hpp" #include "engine/lighting_defs.hpp" @@ -221,7 +220,7 @@ void DoVision(Point position, uint8_t radius, MapExplorationType doAutomap, bool DoVision(position, radius, markVisibleFn, markTransparentFn, passesLightFn, inBoundsFn); } -tl::expected LoadTrns() +std::expected LoadTrns() { RETURN_IF_ERROR(LoadFileInMemWithStatus("plrgfx\\infra.trn", InfravisionTable)); RETURN_IF_ERROR(LoadFileInMemWithStatus("plrgfx\\stone.trn", StoneTable)); diff --git a/Source/lighting.h b/Source/lighting.h index 625d3537f..81b924687 100644 --- a/Source/lighting.h +++ b/Source/lighting.h @@ -7,8 +7,7 @@ #include #include - -#include +#include #include "automap.h" #include "engine/displacement.hpp" @@ -57,7 +56,7 @@ void DoUnLight(Point position, uint8_t radius); void DoLighting(Point position, uint8_t radius, DisplacementOf offset); void DoUnVision(Point position, uint8_t radius); void DoVision(Point position, uint8_t radius, MapExplorationType doAutomap, bool visible); -tl::expected LoadTrns(); +std::expected LoadTrns(); void MakeLightTable(); #ifdef _DEBUG void ToggleLighting(); diff --git a/Source/loadsave.cpp b/Source/loadsave.cpp index b95ad6249..149939ed3 100644 --- a/Source/loadsave.cpp +++ b/Source/loadsave.cpp @@ -9,11 +9,11 @@ #include #include #include +#include #include #include #include -#include #include "automap.h" #include "codec.h" @@ -2004,7 +2004,7 @@ void SaveLevel(SaveWriter &saveWriter, LevelConversionData *levelConversionData) myPlayer._pSLvlVisited[setlvlnum] = true; } -tl::expected LoadLevel(LevelConversionData *levelConversionData) +std::expected LoadLevel(LevelConversionData *levelConversionData) { char szName[MaxMpqPathSize]; std::optional archive = OpenSaveArchive(gSaveNumber); @@ -2013,7 +2013,7 @@ tl::expected LoadLevel(LevelConversionData *levelConversionDa GetPermLevelNames(szName); LoadHelper file(std::move(archive), szName); if (!file.IsValid()) - return tl::make_unexpected(std::string(_("Unable to open save file archive"))); + return std::unexpected(std::string(_("Unable to open save file archive"))); if (leveltype != DTYPE_TOWN) { for (int j = 0; j < MAXDUNY; j++) { @@ -2125,7 +2125,7 @@ bool IsStashSizeValid(size_t stashSize, uint32_t pages, uint32_t itemCount) } // namespace -tl::expected ConvertLevels(SaveWriter &saveWriter) +std::expected ConvertLevels(SaveWriter &saveWriter) { // Backup current level state const bool tmpSetlevel = setlevel; @@ -2464,17 +2464,17 @@ void RemoveEmptyInventory(Player &player) } } -tl::expected LoadGame(bool firstflag) +std::expected LoadGame(bool firstflag) { FreeGameMem(); LoadHelper file(OpenSaveArchive(gSaveNumber), "game"); if (!file.IsValid()) { - return tl::make_unexpected(std::string(_("Unable to open save file archive"))); + return std::unexpected(std::string(_("Unable to open save file archive"))); } if (!IsHeaderValid(file.NextLE())) { - return tl::make_unexpected(std::string(_("Invalid save file"))); + return std::unexpected(std::string(_("Invalid save file"))); } if (gbIsHellfireSaveGame) { @@ -2506,7 +2506,7 @@ tl::expected LoadGame(bool firstflag) const int tmpNobjects = file.NextBE(); if (!gbIsHellfire && IsAnyOf(leveltype, DTYPE_NEST, DTYPE_CRYPT)) { - return tl::make_unexpected(std::string(_("Player is on a Hellfire only level"))); + return std::unexpected(std::string(_("Player is on a Hellfire only level"))); } for (uint8_t i = 0; i < giNumberOfLevels; i++) { @@ -2938,7 +2938,7 @@ void SaveLevel(SaveWriter &saveWriter) SaveLevel(saveWriter, nullptr); } -tl::expected LoadLevel() +std::expected LoadLevel() { return LoadLevel(nullptr); } diff --git a/Source/loadsave.h b/Source/loadsave.h index 0d139e143..c05732056 100644 --- a/Source/loadsave.h +++ b/Source/loadsave.h @@ -6,8 +6,7 @@ #pragma once #include - -#include +#include #include "pfile.h" #include "player.h" @@ -36,14 +35,14 @@ void RemoveEmptyInventory(Player &player); * @brief Load game state * @param firstflag Can be set to false if we are simply reloading the current game */ -tl::expected LoadGame(bool firstflag); +std::expected LoadGame(bool firstflag); void SaveHotkeys(SaveWriter &saveWriter, const Player &player); void SaveHeroItems(SaveWriter &saveWriter, Player &player); void SaveGameData(SaveWriter &saveWriter); void SaveGame(); void SaveLevel(SaveWriter &saveWriter); -tl::expected LoadLevel(); -tl::expected ConvertLevels(SaveWriter &saveWriter); +std::expected LoadLevel(); +std::expected ConvertLevels(SaveWriter &saveWriter); void LoadStash(); void SaveStash(SaveWriter &stashWriter); diff --git a/Source/lua/autocomplete.cpp b/Source/lua/autocomplete.cpp index 4ae1f6fbf..54003c073 100644 --- a/Source/lua/autocomplete.cpp +++ b/Source/lua/autocomplete.cpp @@ -42,7 +42,7 @@ struct ValueInfo { sol::protected_function LoadLuaFunctionSignatureGetter(sol::state &lua) { - tl::expected src = LoadAsset("lua_internal\\get_lua_function_signature.lua"); + std::expected src = LoadAsset("lua_internal\\get_lua_function_signature.lua"); if (!src.has_value()) { app_fatal(src.error()); } diff --git a/Source/lua/lua_global.cpp b/Source/lua/lua_global.cpp index a1b1429df..2e555e51f 100644 --- a/Source/lua/lua_global.cpp +++ b/Source/lua/lua_global.cpp @@ -1,13 +1,13 @@ #include "lua/lua_global.hpp" #include +#include #include #include #include #include #include -#include #include #include #include @@ -113,7 +113,7 @@ sol::object LuaLoadScriptFromAssets(std::string_view packageName) return luaState.sol.load(iter->second.as_string_view(), path, sol::load_mode::binary); } - tl::expected assetData = LoadIntegralAsset(path); + std::expected assetData = LoadIntegralAsset(path); if (!assetData.has_value()) { sol::stack::push(luaState.sol.lua_state(), assetData.error()); return sol::stack_object(luaState.sol.lua_state(), -1); diff --git a/Source/lua/lua_global.hpp b/Source/lua/lua_global.hpp index d7812f1a7..b965399a3 100644 --- a/Source/lua/lua_global.hpp +++ b/Source/lua/lua_global.hpp @@ -1,8 +1,8 @@ #pragma once +#include #include -#include #include #include diff --git a/Source/lua/modules/dev/monsters.cpp b/Source/lua/modules/dev/monsters.cpp index b9843bcc0..9185b20b2 100644 --- a/Source/lua/modules/dev/monsters.cpp +++ b/Source/lua/modules/dev/monsters.cpp @@ -59,7 +59,7 @@ std::string DebugCmdSpawnUniqueMonster(std::string name, std::optional if (!found) { if (LevelMonsterTypeCount == MaxLvlMTypes) LevelMonsterTypeCount--; // we are running out of monster types, so override last used monster type - tl::expected idResult = AddMonsterType(uniqueIndex, PLACE_SCATTER); + std::expected idResult = AddMonsterType(uniqueIndex, PLACE_SCATTER); if (!idResult.has_value()) return std::move(idResult).error(); id = idResult.value(); CMonster &monsterType = LevelMonsterTypes[id]; @@ -134,7 +134,7 @@ std::string DebugCmdSpawnMonster(std::string name, std::optional count if (!found) { if (LevelMonsterTypeCount == MaxLvlMTypes) LevelMonsterTypeCount--; // we are running out of monster types, so override last used monster type - tl::expected idResult = AddMonsterType(static_cast<_monster_id>(mtype), PLACE_SCATTER); + std::expected idResult = AddMonsterType(static_cast<_monster_id>(mtype), PLACE_SCATTER); if (!idResult.has_value()) return std::move(idResult).error(); id = idResult.value(); CMonster &monsterType = LevelMonsterTypes[id]; diff --git a/Source/lua/repl.cpp b/Source/lua/repl.cpp index b840d7ab5..f73dd6b71 100644 --- a/Source/lua/repl.cpp +++ b/Source/lua/repl.cpp @@ -2,11 +2,11 @@ #include "lua/repl.hpp" #include +#include #include #include #include -#include #include #include @@ -87,14 +87,14 @@ sol::environment &GetLuaReplEnvironment() return *replEnv; } -tl::expected RunLuaReplLine(std::string_view code) +std::expected RunLuaReplLine(std::string_view code) { const sol::protected_function_result result = TryRunLuaAsExpressionThenStatement(code); if (!result.valid()) { if (result.get_type() == sol::type::string) { - return tl::make_unexpected(result.get()); + return std::unexpected(result.get()); } - return tl::make_unexpected("Unknown Lua error"); + return std::unexpected("Unknown Lua error"); } if (result.get_type() == sol::type::none) { return std::string {}; diff --git a/Source/lua/repl.hpp b/Source/lua/repl.hpp index 8f6ba1204..0eb2a7902 100644 --- a/Source/lua/repl.hpp +++ b/Source/lua/repl.hpp @@ -1,15 +1,15 @@ #pragma once #ifdef _DEBUG +#include #include #include -#include #include namespace devilution { -tl::expected RunLuaReplLine(std::string_view code); +std::expected RunLuaReplLine(std::string_view code); sol::environment &GetLuaReplEnvironment(); diff --git a/Source/mods/mod_identity.cpp b/Source/mods/mod_identity.cpp index ca18ed571..744192955 100644 --- a/Source/mods/mod_identity.cpp +++ b/Source/mods/mod_identity.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -95,7 +96,7 @@ bool HexToModHash(std::string_view hex, std::array &out) ModManifest ParseModManifest(std::string_view manifestIni) { ModManifest manifest; - tl::expected ini = Ini::parse(manifestIni); + std::expected ini = Ini::parse(manifestIni); if (!ini.has_value()) { LogError("Failed to parse mod manifest: {}", ini.error()); return manifest; diff --git a/Source/monster.cpp b/Source/monster.cpp index af9e19c6e..21fce5634 100644 --- a/Source/monster.cpp +++ b/Source/monster.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -30,7 +31,6 @@ #include #endif -#include #include #include @@ -462,7 +462,7 @@ Point GetUniqueMonstPosition(UniqueMonsterType uniqindex) return position; } -tl::expected PlaceUniqueMonst(UniqueMonsterType uniqindex, size_t minionType, int bosspacksize) +std::expected PlaceUniqueMonst(UniqueMonsterType uniqindex, size_t minionType, int bosspacksize) { const auto &uniqueMonsterData = UniqueMonstersData[static_cast(uniqindex)]; const size_t typeIndex = GetMonsterTypeIndex(uniqueMonsterData.mtype); @@ -503,7 +503,7 @@ void ClrAllMonsters() } } -tl::expected PlaceUniqueMonsters() +std::expected PlaceUniqueMonsters() { for (size_t u = 0; u < UniqueMonstersData.size(); ++u) { if (UniqueMonstersData[u].mlevel != currlevel) @@ -530,7 +530,7 @@ tl::expected PlaceUniqueMonsters() return {}; } -tl::expected PlaceQuestMonsters() +std::expected PlaceQuestMonsters() { if (!setlevel) { if (Quests[Q_BUTCHER].IsAvailable()) { @@ -612,7 +612,7 @@ tl::expected PlaceQuestMonsters() return {}; } -tl::expected LoadDiabMonsts() +std::expected LoadDiabMonsts() { { ASSIGN_OR_RETURN(auto dunData, LoadFileInMemWithStatus("levels\\l4data\\diab1.dun")); @@ -3288,7 +3288,7 @@ bool PosOkMovingMissile(Point position) } // namespace -tl::expected AddMonsterType(_monster_id type, placeflag placeflag) +std::expected AddMonsterType(_monster_id type, placeflag placeflag) { const size_t typeIndex = GetMonsterTypeIndex(type); CMonster &monsterType = LevelMonsterTypes[typeIndex]; @@ -3316,7 +3316,7 @@ tl::expected AddMonsterType(_monster_id type, placeflag pla return typeIndex; } -tl::expected InitTRNForUniqueMonster(Monster &monster) +std::expected InitTRNForUniqueMonster(Monster &monster) { char filestr[64]; *BufCopy(filestr, R"(monsters\monsters\)", UniqueMonstersData[static_cast(monster.uniqueType)].mTrnName, ".trn") = '\0'; @@ -3324,7 +3324,7 @@ tl::expected InitTRNForUniqueMonster(Monster &monster) return {}; } -tl::expected PrepareUniqueMonst(Monster &monster, UniqueMonsterType monsterType, size_t minionType, int bosspacksize, const UniqueMonsterData &uniqueMonsterData) +std::expected PrepareUniqueMonst(Monster &monster, UniqueMonsterType monsterType, size_t minionType, int bosspacksize, const UniqueMonsterData &uniqueMonsterData) { monster.uniqueType = monsterType; monster.maxHitPoints = uniqueMonsterData.mmaxhp << 6; @@ -3431,7 +3431,7 @@ void InitLevelMonsters() uniquetrans = 0; } -tl::expected GetLevelMTypes() +std::expected GetLevelMTypes() { RETURN_IF_ERROR(AddMonsterType(MT_GOLEM, PLACE_SPECIAL)); if (currlevel == 16) { @@ -3517,7 +3517,7 @@ tl::expected GetLevelMTypes() return {}; } -tl::expected InitMonsterSND(CMonster &monsterType) +std::expected InitMonsterSND(CMonster &monsterType) { if (!gbSndInited) return {}; @@ -3546,7 +3546,7 @@ tl::expected InitMonsterSND(CMonster &monsterType) return {}; } -tl::expected InitMonsterGFX(CMonster &monsterType, MonsterSpritesData &&spritesData) +std::expected InitMonsterGFX(CMonster &monsterType, MonsterSpritesData &&spritesData) { if (HeadlessMode) return {}; @@ -3620,7 +3620,7 @@ tl::expected InitMonsterGFX(CMonster &monsterType, MonsterSpr return {}; } -tl::expected InitAllMonsterGFX() +std::expected InitAllMonsterGFX() { if (HeadlessMode) return {}; @@ -3685,7 +3685,7 @@ void InitGolems() } } -tl::expected InitMonsters() +std::expected InitMonsters() { if (!gbIsSpawn && !setlevel && currlevel == 16) LoadDiabMonsts(); @@ -3748,7 +3748,7 @@ tl::expected InitMonsters() return InitAllMonsterGFX(); } -tl::expected SetMapMonsters(const uint16_t *dunData, Point startPosition) +std::expected SetMapMonsters(const uint16_t *dunData, Point startPosition) { RETURN_IF_ERROR(AddMonsterType(MT_GOLEM, PLACE_SPECIAL)); if (setlevel) @@ -4392,7 +4392,7 @@ bool LineClearMovingMissile(Point startPoint, Point endPoint) return LineClear(PosOkMovingMissile, startPoint, endPoint); } -tl::expected SyncMonsterAnim(Monster &monster) +std::expected SyncMonsterAnim(Monster &monster) { #ifdef _DEBUG // fix for saves with debug monsters having type originally not on the level diff --git a/Source/monster.h b/Source/monster.h index 2be5890ed..c6ed35b69 100644 --- a/Source/monster.h +++ b/Source/monster.h @@ -7,12 +7,12 @@ #include #include +#include #include #include #include -#include #include #include "engine/actor_position.hpp" @@ -496,21 +496,21 @@ extern size_t ActiveMonsterCount; extern int MonsterKillCounts[NUM_MAX_MTYPES]; extern bool sgbSaveSoundOn; -tl::expected PrepareUniqueMonst(Monster &monster, UniqueMonsterType monsterType, size_t miniontype, int bosspacksize, const UniqueMonsterData &uniqueMonsterData); +std::expected PrepareUniqueMonst(Monster &monster, UniqueMonsterType monsterType, size_t miniontype, int bosspacksize, const UniqueMonsterData &uniqueMonsterData); void InitLevelMonsters(); -tl::expected GetLevelMTypes(); -tl::expected AddMonsterType(_monster_id type, placeflag placeflag); -inline tl::expected AddMonsterType(UniqueMonsterType uniqueType, placeflag placeflag) +std::expected GetLevelMTypes(); +std::expected AddMonsterType(_monster_id type, placeflag placeflag); +inline std::expected AddMonsterType(UniqueMonsterType uniqueType, placeflag placeflag) { return AddMonsterType(UniqueMonstersData[static_cast(uniqueType)].mtype, placeflag); } -tl::expected InitMonsterSND(CMonster &monsterType); -tl::expected InitMonsterGFX(CMonster &monsterType, MonsterSpritesData &&spritesData = {}); -tl::expected InitAllMonsterGFX(); +std::expected InitMonsterSND(CMonster &monsterType); +std::expected InitMonsterGFX(CMonster &monsterType, MonsterSpritesData &&spritesData = {}); +std::expected InitAllMonsterGFX(); void WeakenNaKrul(); void InitGolems(); -tl::expected InitMonsters(); -tl::expected SetMapMonsters(const uint16_t *dunData, Point startPosition); +std::expected InitMonsters(); +std::expected SetMapMonsters(const uint16_t *dunData, Point startPosition); Monster *AddMonster(Point position, Direction dir, size_t typeIndex, bool inMap); /** * @brief Spawns a new monsters (dynamically/not on level load). @@ -555,7 +555,7 @@ bool LineClearMissile(Point startPoint, Point endPoint); * @brief Checks for same missile obstructions as CheckMissileCol() for missiles that move along a path between two points */ bool LineClearMovingMissile(Point startPoint, Point endPoint); -tl::expected SyncMonsterAnim(Monster &monster); +std::expected SyncMonsterAnim(Monster &monster); void M_FallenFear(Point position); void PrintMonstHistory(int mt); void PrintUniqueHistory(); diff --git a/Source/mpq/mpq_reader.cpp b/Source/mpq/mpq_reader.cpp index 69221117d..78a59dd87 100644 --- a/Source/mpq/mpq_reader.cpp +++ b/Source/mpq/mpq_reader.cpp @@ -67,22 +67,22 @@ MpqArchive::~MpqArchive() mpqfs_close(archive_); } -tl::expected MpqArchive::Open(const char *path) +std::expected MpqArchive::Open(const char *path) { mpqfs_archive_t *handle = nullptr; const mpqfs_error_code code = mpqfs_open(path, &handle); if (code != MPQFS_OK) { - return tl::make_unexpected(FormatMpqfsError(code)); + return std::unexpected(FormatMpqfsError(code)); } return MpqArchive(path, handle); } -tl::expected MpqArchive::Clone() +std::expected MpqArchive::Clone() { mpqfs_archive_t *clone = nullptr; const mpqfs_error_code code = mpqfs_clone(archive_, &clone); if (code != MPQFS_OK) { - return tl::make_unexpected(FormatMpqfsError(code)); + return std::unexpected(FormatMpqfsError(code)); } return MpqArchive(path_, clone); } diff --git a/Source/mpq/mpq_reader.hpp b/Source/mpq/mpq_reader.hpp index 991b783b6..e1ffe0ee8 100644 --- a/Source/mpq/mpq_reader.hpp +++ b/Source/mpq/mpq_reader.hpp @@ -2,12 +2,11 @@ #include #include +#include #include #include #include -#include - // Forward-declare so that we can avoid exposing mpqfs.h to all consumers. struct mpqfs_archive; typedef struct mpqfs_archive mpqfs_archive_t; @@ -16,8 +15,8 @@ namespace devilution { class MpqArchive { public: - static tl::expected Open(const char *path); - tl::expected Clone(); + static std::expected Open(const char *path); + std::expected Clone(); MpqArchive(MpqArchive &&other) noexcept; MpqArchive &operator=(MpqArchive &&other) noexcept; diff --git a/Source/objects.cpp b/Source/objects.cpp index fcd6b36ea..c520a6a59 100644 --- a/Source/objects.cpp +++ b/Source/objects.cpp @@ -7,11 +7,11 @@ #include #include #include +#include #include #include -#include #include #include @@ -3681,7 +3681,7 @@ bool IsItemBlockingObjectAtPosition(Point position) return false; } -tl::expected LoadLevelObjects(uint16_t filesWidths[65]) +std::expected LoadLevelObjects(uint16_t filesWidths[65]) { if (HeadlessMode) return {}; @@ -3706,7 +3706,7 @@ tl::expected LoadLevelObjects(uint16_t filesWidths[65]) return {}; } -tl::expected InitObjectGFX() +std::expected InitObjectGFX() { uint16_t filesWidths[65] = {}; diff --git a/Source/objects.h b/Source/objects.h index 4dedfdb8f..73cad1893 100644 --- a/Source/objects.h +++ b/Source/objects.h @@ -7,10 +7,9 @@ #include #include +#include #include -#include - #include "cursor.h" #include "engine/clx_sprite.hpp" #include "engine/point.hpp" @@ -329,7 +328,7 @@ inline Object &ObjectAtPosition(Point position) */ bool IsItemBlockingObjectAtPosition(Point position); -tl::expected InitObjectGFX(); +std::expected InitObjectGFX(); void FreeObjectGFX(); void AddL1Objs(int x1, int y1, int x2, int y2); void AddL2Objs(int x1, int y1, int x2, int y2); diff --git a/Source/options.cpp b/Source/options.cpp index acf5f3e72..629093693 100644 --- a/Source/options.cpp +++ b/Source/options.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -26,7 +27,6 @@ #include #endif -#include #include #include @@ -157,7 +157,7 @@ void LoadIni() } std::fclose(file); } - tl::expected result = Ini::parse(std::string_view(buffer.data(), buffer.size())); + std::expected result = Ini::parse(std::string_view(buffer.data(), buffer.size())); if (!result.has_value()) app_fatal(result.error()); ini.emplace(std::move(result).value()); } diff --git a/Source/panels/charpanel.cpp b/Source/panels/charpanel.cpp index 162f3aafe..3ef55f743 100644 --- a/Source/panels/charpanel.cpp +++ b/Source/panels/charpanel.cpp @@ -1,11 +1,11 @@ #include "panels/charpanel.hpp" #include +#include #include #include -#include #include #include @@ -270,7 +270,7 @@ void DrawStatButtons(const Surface &out) } // namespace -tl::expected LoadCharPanel() +std::expected LoadCharPanel() { ASSIGN_OR_RETURN(OptionalOwnedClxSpriteList background, LoadClxWithStatus("data\\charbg.clx")); const OwnedSurface out((*background)[0].width(), (*background)[0].height()); diff --git a/Source/panels/charpanel.hpp b/Source/panels/charpanel.hpp index 947b6e1ef..a5cf1c901 100644 --- a/Source/panels/charpanel.hpp +++ b/Source/panels/charpanel.hpp @@ -1,9 +1,8 @@ #pragma once +#include #include -#include - #include "engine/clx_sprite.hpp" #include "engine/surface.hpp" @@ -12,7 +11,7 @@ namespace devilution { extern OptionalOwnedClxSpriteList pChrButtons; void DrawChr(const Surface &); -tl::expected LoadCharPanel(); +std::expected LoadCharPanel(); void FreeCharPanel(); } // namespace devilution diff --git a/Source/panels/console.cpp b/Source/panels/console.cpp index 818c46e42..1960a6509 100644 --- a/Source/panels/console.cpp +++ b/Source/panels/console.cpp @@ -53,7 +53,7 @@ constexpr std::string_view HelpText = " Up/Down to fill the input from history," " Shift+Up/Down to fill the input from output history," " Ctrl+L to clear history, Esc to close."; -std::optional> ConsolePrelude; +std::optional> ConsolePrelude; bool IsConsoleVisible; char ConsoleInputBuffer[4096]; @@ -639,7 +639,7 @@ void InitConsole() void RunInConsole(std::string_view code) { AddConsoleLine(ConsoleLine { .type = ConsoleLine::Input, .text = StrCat(Prompt, code) }); - tl::expected result = RunLuaReplLine(code); + std::expected result = RunLuaReplLine(code); if (result.has_value()) { if (!result->empty()) { diff --git a/Source/panels/mainpanel.cpp b/Source/panels/mainpanel.cpp index bb1a45b15..18ad4f74d 100644 --- a/Source/panels/mainpanel.cpp +++ b/Source/panels/mainpanel.cpp @@ -1,11 +1,10 @@ #include "panels/mainpanel.hpp" #include +#include #include #include -#include - #include "control/control.hpp" #include "engine/clx_sprite.hpp" #include "engine/load_clx.hpp" @@ -70,7 +69,7 @@ void RenderMainButton(const Surface &out, int buttonId, std::string_view text, i } // namespace -tl::expected LoadMainPanel() +std::expected LoadMainPanel() { std::optional out; constexpr uint16_t NumButtonSprites = 6; diff --git a/Source/panels/mainpanel.hpp b/Source/panels/mainpanel.hpp index a0b788ccd..02ab5da22 100644 --- a/Source/panels/mainpanel.hpp +++ b/Source/panels/mainpanel.hpp @@ -1,9 +1,8 @@ #pragma once +#include #include -#include - #include "engine/clx_sprite.hpp" namespace devilution { @@ -11,7 +10,7 @@ namespace devilution { extern OptionalOwnedClxSpriteList PanelButtonDown; extern OptionalOwnedClxSpriteList TalkButton; -tl::expected LoadMainPanel(); +std::expected LoadMainPanel(); void FreeMainPanel(); } // namespace devilution diff --git a/Source/panels/partypanel.cpp b/Source/panels/partypanel.cpp index de59fad2c..71cb9d604 100644 --- a/Source/panels/partypanel.cpp +++ b/Source/panels/partypanel.cpp @@ -1,6 +1,6 @@ #include "panels/partypanel.hpp" -#include +#include #include #include "automap.h" @@ -135,7 +135,7 @@ bool PartySidePanelOpen = true; bool InspectingFromPartyPanel; int PortraitIdUnderCursor = -1; -tl::expected LoadPartyPanel() +std::expected LoadPartyPanel() { ASSIGN_OR_RETURN(OwnedClxSpriteList frame, LoadCelWithStatus("data\\textslid", FrameSpriteSize)); ASSIGN_OR_RETURN(PlayerTags, LoadClxWithStatus("data\\monstertags.clx")); diff --git a/Source/panels/partypanel.hpp b/Source/panels/partypanel.hpp index d73adf10c..f853e5f10 100644 --- a/Source/panels/partypanel.hpp +++ b/Source/panels/partypanel.hpp @@ -1,9 +1,8 @@ #pragma once +#include #include -#include - #include "engine/clx_sprite.hpp" #include "engine/surface.hpp" @@ -13,7 +12,7 @@ extern bool PartySidePanelOpen; extern bool InspectingFromPartyPanel; extern int PortraitIdUnderCursor; -tl::expected LoadPartyPanel(); +std::expected LoadPartyPanel(); void FreePartyPanel(); void DrawPartyMemberInfoPanel(const Surface &out); bool DidRightClickPartyPortrait(); diff --git a/Source/panels/spell_book.cpp b/Source/panels/spell_book.cpp index 5693963c4..e27c0b5e1 100644 --- a/Source/panels/spell_book.cpp +++ b/Source/panels/spell_book.cpp @@ -1,10 +1,10 @@ #include "panels/spell_book.hpp" #include +#include #include #include -#include #include #include "control/control.hpp" @@ -119,7 +119,7 @@ StringOrView GetSpellPowerText(SpellID spell, int spellLevel) } // namespace -tl::expected InitSpellBook() +std::expected InitSpellBook() { ASSIGN_OR_RETURN(spellBookBackground, LoadCelWithStatus("data\\spellbk", static_cast(SidePanelSize.width))); ASSIGN_OR_RETURN(spellBookButtons, LoadCelWithStatus("data\\spellbkb", SpellBookButtonWidth())); diff --git a/Source/panels/spell_book.hpp b/Source/panels/spell_book.hpp index 9d15381e4..a48ea5cb9 100644 --- a/Source/panels/spell_book.hpp +++ b/Source/panels/spell_book.hpp @@ -1,15 +1,14 @@ #pragma once +#include #include -#include - #include "engine/clx_sprite.hpp" #include "engine/surface.hpp" namespace devilution { -tl::expected InitSpellBook(); +std::expected InitSpellBook(); void FreeSpellBook(); void CheckSBook(); void DrawSpellBook(const Surface &out); diff --git a/Source/panels/spell_icons.cpp b/Source/panels/spell_icons.cpp index 52ad89f2e..b0ad674c8 100644 --- a/Source/panels/spell_icons.cpp +++ b/Source/panels/spell_icons.cpp @@ -84,7 +84,7 @@ const SpellIcon SpellITbl[] = { } // namespace -tl::expected LoadLargeSpellIcons() +std::expected LoadLargeSpellIcons() { #ifdef UNPACKED_MPQS LargeSpellIcons = LoadOptionalClx("data\\spelicon_fg.clx"); @@ -111,7 +111,7 @@ void FreeLargeSpellIcons() LargeSpellIcons = std::nullopt; } -tl::expected LoadSmallSpellIcons() +std::expected LoadSmallSpellIcons() { #ifdef UNPACKED_MPQS ASSIGN_OR_RETURN(SmallSpellIcons, LoadClxWithStatus("data\\spelli2_fg.clx")); diff --git a/Source/panels/spell_icons.hpp b/Source/panels/spell_icons.hpp index db66cfe8f..c9427592e 100644 --- a/Source/panels/spell_icons.hpp +++ b/Source/panels/spell_icons.hpp @@ -1,10 +1,9 @@ #pragma once #include +#include #include -#include - #include "engine/clx_sprite.hpp" #include "engine/point.hpp" #include "engine/surface.hpp" @@ -109,10 +108,10 @@ void DrawSmallSpellIconBorder(const Surface &out, Point position); */ void SetSpellTrans(SpellType t); -tl::expected LoadLargeSpellIcons(); +std::expected LoadLargeSpellIcons(); void FreeLargeSpellIcons(); -tl::expected LoadSmallSpellIcons(); +std::expected LoadSmallSpellIcons(); void FreeSmallSpellIcons(); } // namespace devilution diff --git a/Source/pfile.cpp b/Source/pfile.cpp index b50ccbfbe..ae1a52613 100644 --- a/Source/pfile.cpp +++ b/Source/pfile.cpp @@ -7,12 +7,12 @@ #include #include +#include #include #include #include #include -#include #ifdef USE_SDL3 #include @@ -265,7 +265,7 @@ std::optional CreateSaveReader(std::string &&path) return std::nullopt; return SaveReader(std::move(path)); #else - tl::expected opened = MpqArchive::Open(path.c_str()); + std::expected opened = MpqArchive::Open(path.c_str()); if (!opened.has_value()) return std::nullopt; return std::move(*opened); #endif @@ -809,7 +809,7 @@ void pfile_save_level() SaveLevel(saveWriter); } -tl::expected pfile_convert_levels() +std::expected pfile_convert_levels() { SaveWriter saveWriter = GetSaveWriter(gSaveNumber); return ConvertLevels(saveWriter); diff --git a/Source/pfile.h b/Source/pfile.h index df10fca08..fec90c02c 100644 --- a/Source/pfile.h +++ b/Source/pfile.h @@ -6,10 +6,9 @@ #pragma once #include +#include #include -#include - #include "DiabloUI/diabloui.h" #include "player.h" @@ -125,7 +124,7 @@ bool pfile_ui_save_create(_uiheroinfo *heroinfo); bool pfile_delete_save(_uiheroinfo *heroInfo); void pfile_read_player_from_save(uint32_t saveNum, Player &player); void pfile_save_level(); -tl::expected pfile_convert_levels(); +std::expected pfile_convert_levels(); void pfile_remove_temp_files(); std::unique_ptr pfile_read(const char *pszName, size_t *pdwLen); void pfile_update(bool forceSave); diff --git a/Source/platform/android/android.cpp b/Source/platform/android/android.cpp index a4e477cf0..0f243b40a 100644 --- a/Source/platform/android/android.cpp +++ b/Source/platform/android/android.cpp @@ -8,7 +8,7 @@ namespace { bool AreExtraFontsOutOfDateForMpqPath(const char *mpqPath) { - tl::expected archive = MpqArchive::Open(mpqPath); + std::expected archive = MpqArchive::Open(mpqPath); return archive.has_value() && AreExtraFontsOutOfDate(*archive); } diff --git a/Source/tables/itemdat.cpp b/Source/tables/itemdat.cpp index 7c8eb4c69..699154024 100644 --- a/Source/tables/itemdat.cpp +++ b/Source/tables/itemdat.cpp @@ -41,18 +41,18 @@ std::vector ItemPrefixes; /** Contains the data related to each item suffix. */ std::vector ItemSuffixes; -tl::expected<_item_indexes, std::string> ParseItemId(std::string_view value) +std::expected<_item_indexes, std::string> ParseItemId(std::string_view value) { const std::optional<_item_indexes> enumValueOpt = magic_enum::enum_cast<_item_indexes>(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } namespace { -tl::expected ParseItemClass(std::string_view value) +std::expected ParseItemClass(std::string_view value) { if (value == "None") return ICLASS_NONE; if (value == "Weapon") return ICLASS_WEAPON; @@ -60,10 +60,10 @@ tl::expected ParseItemClass(std::string_view value) if (value == "Misc") return ICLASS_MISC; if (value == "Gold") return ICLASS_GOLD; if (value == "Quest") return ICLASS_QUEST; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseItemEquipType(std::string_view value) +std::expected ParseItemEquipType(std::string_view value) { if (value == "None") return ILOC_NONE; if (value == "One-handed") return ILOC_ONEHAND; @@ -74,10 +74,10 @@ tl::expected ParseItemEquipType(std::string_view v if (value == "Amulet") return ILOC_AMULET; if (value == "Unequippable") return ILOC_UNEQUIPABLE; if (value == "Belt") return ILOC_BELT; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseItemCursorGraphic(std::string_view value) +std::expected ParseItemCursorGraphic(std::string_view value) { if (value == "POTION_OF_FULL_MANA") return ICURS_POTION_OF_FULL_MANA; if (value == "SCROLL_OF") return ICURS_SCROLL_OF; @@ -253,11 +253,11 @@ tl::expected ParseItemCursorGraphic(std::strin // also support providing the item cursor icon frame number directly return ParseInt(value) - .map([](auto numericalValue) { return static_cast(numericalValue); }) - .map_error([](auto) { return std::string("Unknown enum value"); }); + .transform([](auto numericalValue) { return static_cast(numericalValue); }) + .transform_error([](auto) { return std::string("Unknown enum value"); }); } -tl::expected ParseItemType(std::string_view value) +std::expected ParseItemType(std::string_view value) { if (value == "Misc") return ItemType::Misc; if (value == "Sword") return ItemType::Sword; @@ -274,10 +274,10 @@ tl::expected ParseItemType(std::string_view value) if (value == "Ring") return ItemType::Ring; if (value == "Amulet") return ItemType::Amulet; if (value == "None") return ItemType::None; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseUniqueBaseItem(std::string_view value) +std::expected ParseUniqueBaseItem(std::string_view value) { if (value == "NONE") return UITYPE_NONE; if (value == "SHORTBOW") return UITYPE_SHORTBOW; @@ -354,10 +354,10 @@ tl::expected ParseUniqueBaseItem(std::string_view return static_cast(findIt->second); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseOrAddUniqueBaseItem(std::string_view value) +std::expected ParseOrAddUniqueBaseItem(std::string_view value) { const auto parseResult = ParseUniqueBaseItem(value); if (parseResult.has_value()) { @@ -367,7 +367,7 @@ tl::expected ParseOrAddUniqueBaseItem(std::string const size_t newUniqueBaseItemIndex = static_cast(NUM_DEFAULT_UITYPES) + AdditionalUniqueBaseItemStringsToIndices.size(); if (newUniqueBaseItemIndex >= static_cast(NUM_MAX_UITYPES)) { - return tl::make_unexpected(fmt::format("Could not define new unique base item \"{}\", since the maximum number of {} has already been reached.", value, static_cast(NUM_MAX_UITYPES))); + return std::unexpected(fmt::format("Could not define new unique base item \"{}\", since the maximum number of {} has already been reached.", value, static_cast(NUM_MAX_UITYPES))); } const auto newUniqueBaseItem = static_cast(newUniqueBaseItemIndex); @@ -375,7 +375,7 @@ tl::expected ParseOrAddUniqueBaseItem(std::string return newUniqueBaseItem; } -tl::expected ParseItemSpecialEffect(std::string_view value) +std::expected ParseItemSpecialEffect(std::string_view value) { if (value == "RandomStealLife") return ItemSpecialEffect::RandomStealLife; if (value == "RandomArrowVelocity") return ItemSpecialEffect::RandomArrowVelocity; @@ -403,10 +403,10 @@ tl::expected ParseItemSpecialEffect(std::string_ if (value == "HalfTrapDamage") return ItemSpecialEffect::HalfTrapDamage; if (value == "TripleDemonDamage") return ItemSpecialEffect::TripleDemonDamage; if (value == "ZeroResistance") return ItemSpecialEffect::ZeroResistance; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseItemMiscId(std::string_view value) +std::expected ParseItemMiscId(std::string_view value) { if (value == "NONE") return IMISC_NONE; if (value == "USEFIRST") return IMISC_USEFIRST; @@ -454,10 +454,10 @@ tl::expected ParseItemMiscId(std::string_view value) if (value == "AURIC") return IMISC_AURIC; if (value == "NOTE") return IMISC_NOTE; if (value == "ARENAPOT") return IMISC_ARENAPOT; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseItemEffectType(std::string_view value) +std::expected ParseItemEffectType(std::string_view value) { if (value == "TOHIT") return IPL_TOHIT; if (value == "TOHIT_CURSE") return IPL_TOHIT_CURSE; @@ -539,10 +539,10 @@ tl::expected ParseItemEffectType(std::string_view if (value == "ACUNDEAD") return IPL_ACUNDEAD; if (value == "MANATOLIFE") return IPL_MANATOLIFE; if (value == "LIFETOMANA") return IPL_LIFETOMANA; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseAffixItemType(std::string_view value) +std::expected ParseAffixItemType(std::string_view value) { if (value == "Misc") return AffixItemType::Misc; if (value == "Bow") return AffixItemType::Bow; @@ -550,15 +550,15 @@ tl::expected ParseAffixItemType(std::string_view val if (value == "Weapon") return AffixItemType::Weapon; if (value == "Shield") return AffixItemType::Shield; if (value == "Armor") return AffixItemType::Armor; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseAffixAlignment(std::string_view value) +std::expected ParseAffixAlignment(std::string_view value) { if (value == "Any") return GOE_ANY; if (value == "Evil") return GOE_EVIL; if (value == "Good") return GOE_GOOD; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } } // namespace diff --git a/Source/tables/itemdat.h b/Source/tables/itemdat.h index 77b8bcf1d..176a01c10 100644 --- a/Source/tables/itemdat.h +++ b/Source/tables/itemdat.h @@ -6,11 +6,11 @@ #pragma once #include +#include #include #include #include -#include #include #include "tables/objdat.h" @@ -656,7 +656,7 @@ extern std::vector ItemSuffixes; extern DVL_API_FOR_TEST std::vector UniqueItems; extern ankerl::unordered_dense::map UniqueItemMappingIdsToIndices; -tl::expected<_item_indexes, std::string> ParseItemId(std::string_view value); +std::expected<_item_indexes, std::string> ParseItemId(std::string_view value); void LoadItemDatFromFile(DataFile &dataFile, std::string_view filename, int32_t baseMappingId); void LoadUniqueItemDatFromFile(DataFile &dataFile, std::string_view filename, int32_t baseMappingId); void LoadItemData(); diff --git a/Source/tables/misdat.cpp b/Source/tables/misdat.cpp index 620fa1e4c..375e5f5e6 100644 --- a/Source/tables/misdat.cpp +++ b/Source/tables/misdat.cpp @@ -9,14 +9,13 @@ #include #include #include +#include #include #include #include #include #include -#include - #include "data/file.hpp" #include "data/iterators.hpp" #include "data/record_reader.hpp" @@ -57,15 +56,15 @@ size_t ToIndex(std::vector> &all, const std::array ParseMissileGraphicsFlag(std::string_view value) +std::expected ParseMissileGraphicsFlag(std::string_view value) { if (value.empty()) return MissileGraphicsFlags::None; if (value == "MonsterOwned") return MissileGraphicsFlags::MonsterOwned; if (value == "NotAnimated") return MissileGraphicsFlags::NotAnimated; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMissileGraphicID(std::string_view value) +std::expected ParseMissileGraphicID(std::string_view value) { if (value.empty()) return MissileGraphicID::None; if (value == "Arrow") return MissileGraphicID::Arrow; @@ -127,7 +126,7 @@ tl::expected ParseMissileGraphicID(std::string_vi if (value == "BlueFlare2") return MissileGraphicID::BlueFlare2; if (value == "OrangeFlareExplosion") return MissileGraphicID::OrangeFlareExplosion; if (value == "BlueFlareExplosion2") return MissileGraphicID::BlueFlareExplosion2; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } void LoadMissileSpriteData() @@ -166,7 +165,7 @@ void LoadMissileSpriteData() MissileAnimLengths.shrink_to_fit(); } -tl::expected ParseMissileDataFlag(std::string_view value) +std::expected ParseMissileDataFlag(std::string_view value) { if (value == "Physical") return MissileDataFlags::Physical; if (value == "Fire") return MissileDataFlags::Fire; @@ -175,11 +174,11 @@ tl::expected ParseMissileDataFlag(std::string_vie if (value == "Acid") return MissileDataFlags::Acid; if (value == "Arrow") return MissileDataFlags::Arrow; if (value == "Invisible") return MissileDataFlags::Invisible; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } // NOLINTNEXTLINE(readability-function-cognitive-complexity) -tl::expected ParseMissileAddFn(std::string_view value) +std::expected ParseMissileAddFn(std::string_view value) { if (value.empty()) return nullptr; if (value == "AddOpenNest") return AddOpenNest; @@ -255,11 +254,11 @@ tl::expected ParseMissileAddFn(std::string_view if (value == "AddBoneSpirit") return AddBoneSpirit; if (value == "AddRedPortal") return AddRedPortal; if (value == "AddDiabloApocalypse") return AddDiabloApocalypse; - return tl::make_unexpected("Unknown MissileData::AddFn name"); + return std::unexpected("Unknown MissileData::AddFn name"); } // NOLINTNEXTLINE(readability-function-cognitive-complexity) -tl::expected ParseMissileProcessFn(std::string_view value) +std::expected ParseMissileProcessFn(std::string_view value) { if (value.empty()) return nullptr; if (value == "ProcessElementalArrow") return ProcessElementalArrow; @@ -307,12 +306,12 @@ tl::expected ParseMissileProcessFn(std::str if (value == "ProcessBoneSpirit") return ProcessBoneSpirit; if (value == "ProcessResurrectBeam") return ProcessResurrectBeam; if (value == "ProcessRedPortal") return ProcessRedPortal; - return tl::make_unexpected("Unknown MissileData::ProcessFn name"); + return std::unexpected("Unknown MissileData::ProcessFn name"); } // A temporary solution for parsing SfxID until we have a more general one. // NOLINTNEXTLINE(readability-function-cognitive-complexity) -tl::expected ParseCastSound(std::string_view value) +std::expected ParseCastSound(std::string_view value) { if (value.empty()) return SfxID::None; if (value == "BigExplosion") return SfxID::BigExplosion; @@ -345,11 +344,11 @@ tl::expected ParseCastSound(std::string_view value) if (value == "SpellStoneCurse") return SfxID::SpellStoneCurse; if (value == "SpellTeleport") return SfxID::SpellTeleport; if (value == "SpellTrapDisarm") return SfxID::SpellTrapDisarm; - return tl::make_unexpected("Unknown enum value (only a few are supported for now)"); + return std::unexpected("Unknown enum value (only a few are supported for now)"); } // A temporary solution for parsing SfxID until we have a more general one. -tl::expected ParseHitSound(std::string_view value) +std::expected ParseHitSound(std::string_view value) { if (value.empty()) return SfxID::None; if (value == "BigExplosion") return SfxID::BigExplosion; @@ -358,15 +357,15 @@ tl::expected ParseHitSound(std::string_view value) if (value == "SpellFireHit") return SfxID::SpellFireHit; if (value == "SpellLightningHit") return SfxID::SpellLightningHit; if (value == "SpellResurrect") return SfxID::SpellResurrect; - return tl::make_unexpected("Unknown enum value (only a few are supported for now)"); + return std::unexpected("Unknown enum value (only a few are supported for now)"); } -tl::expected ParseMissileMovementDistribution(std::string_view value) +std::expected ParseMissileMovementDistribution(std::string_view value) { if (value.empty()) return MissileMovementDistribution::Disabled; if (value == "Blockable") return MissileMovementDistribution::Blockable; if (value == "Unblockable") return MissileMovementDistribution::Unblockable; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } void LoadMisdat() @@ -408,7 +407,7 @@ uint8_t MissileFileData::animLen(uint8_t dir) const return MissileAnimLengths[animLenIdx][dir]; } -tl::expected MissileFileData::LoadGFX() +std::expected MissileFileData::LoadGFX() { if (sprites) return {}; @@ -451,7 +450,7 @@ const MissileData &GetMissileData(MissileID missileId) return MissilesData[static_cast>(missileId)]; } -tl::expected InitMissileGFX() +std::expected InitMissileGFX() { if (HeadlessMode) return {}; diff --git a/Source/tables/misdat.h b/Source/tables/misdat.h index eb4fb7452..bede6b68d 100644 --- a/Source/tables/misdat.h +++ b/Source/tables/misdat.h @@ -7,11 +7,10 @@ #include #include +#include #include #include -#include - #include "effects.h" #include "engine/clx_sprite.hpp" #include "tables/spelldat.h" @@ -220,7 +219,7 @@ struct MissileFileData { [[nodiscard]] uint8_t animDelay(uint8_t dir) const; [[nodiscard]] uint8_t animLen(uint8_t dir) const; - tl::expected LoadGFX(); + std::expected LoadGFX(); void FreeGFX() { @@ -246,7 +245,7 @@ MissileFileData &GetMissileSpriteData(MissileGraphicID graphicId); void LoadMissileData(); -tl::expected InitMissileGFX(); +std::expected InitMissileGFX(); void FreeMissileGFX(); } // namespace devilution diff --git a/Source/tables/monstdat.cpp b/Source/tables/monstdat.cpp index 1cbada0d4..191f7c816 100644 --- a/Source/tables/monstdat.cpp +++ b/Source/tables/monstdat.cpp @@ -8,13 +8,13 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -223,7 +223,7 @@ namespace { /** Contains the mapping between monster ID strings and indices, used for parsing additional monster data. */ ankerl::unordered_dense::map AdditionalMonsterIdStringsToIndices; -tl::expected<_monster_id, std::string> ParseMonsterId(std::string_view value) +std::expected<_monster_id, std::string> ParseMonsterId(std::string_view value) { const std::optional<_monster_id> enumValueOpt = magic_enum::enum_cast<_monster_id>(value); if (enumValueOpt.has_value()) { @@ -233,27 +233,27 @@ tl::expected<_monster_id, std::string> ParseMonsterId(std::string_view value) if (findIt != AdditionalMonsterIdStringsToIndices.end()) { return static_cast<_monster_id>(findIt->second); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMonsterAvailability(std::string_view value) +std::expected ParseMonsterAvailability(std::string_view value) { if (value == "Always") return MonsterAvailability::Always; if (value == "Never") return MonsterAvailability::Never; if (value == "Retail") return MonsterAvailability::Retail; - return tl::make_unexpected("Expected one of: Always, Never, or Retail"); + return std::unexpected("Expected one of: Always, Never, or Retail"); } -tl::expected ParseAiId(std::string_view value) +std::expected ParseAiId(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMonsterFlag(std::string_view value) +std::expected ParseMonsterFlag(std::string_view value) { if (value == "HIDDEN") return MFLAG_HIDDEN; if (value == "LOCK_ANIMATION") return MFLAG_LOCK_ANIMATION; @@ -267,37 +267,37 @@ tl::expected ParseMonsterFlag(std::string_view value) if (value == "NO_ENEMY") return MFLAG_NO_ENEMY; if (value == "BERSERK") return MFLAG_BERSERK; if (value == "NOLIFESTEAL") return MFLAG_NOLIFESTEAL; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMonsterClass(std::string_view value) +std::expected ParseMonsterClass(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMonsterResistance(std::string_view value) +std::expected ParseMonsterResistance(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseSelectionRegion(std::string_view value) +std::expected ParseSelectionRegion(std::string_view value) { if (value.empty()) return SelectionRegion::None; if (value == "Bottom") return SelectionRegion::Bottom; if (value == "Middle") return SelectionRegion::Middle; if (value == "Top") return SelectionRegion::Top; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMonsterTreasure(std::string_view value) +std::expected ParseMonsterTreasure(std::string_view value) { // TODO: Replace this hack with proper parsing. @@ -305,16 +305,16 @@ tl::expected ParseMonsterTreasure(std::string_view value) if (value == "None") return T_NODROP; if (value == "Uniq(SKCROWN)") return Uniq(UITEM_SKCROWN); if (value == "Uniq(CLEAVER)") return Uniq(UITEM_CLEAVER); - return tl::make_unexpected("Invalid value. NOTE: Parser is incomplete"); + return std::unexpected("Invalid value. NOTE: Parser is incomplete"); } -tl::expected ParseUniqueMonsterPack(std::string_view value) +std::expected ParseUniqueMonsterPack(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } } // namespace diff --git a/Source/tables/objdat.cpp b/Source/tables/objdat.cpp index e1c3c79d8..3b077f6b5 100644 --- a/Source/tables/objdat.cpp +++ b/Source/tables/objdat.cpp @@ -5,12 +5,12 @@ */ #include "tables/objdat.h" +#include #include #include #include #include -#include #include "cursor.h" #include "data/file.hpp" @@ -178,7 +178,7 @@ std::vector ObjMasterLoadList; namespace { -tl::expected ParseTheme(std::string_view value) +std::expected ParseTheme(std::string_view value) { if (value.empty()) return THEME_NONE; if (value == "THEME_BARREL") return THEME_BARREL; @@ -198,10 +198,10 @@ tl::expected ParseTheme(std::string_view value) if (value == "THEME_TEARFOUNTAIN") return THEME_TEARFOUNTAIN; if (value == "THEME_BRNCROSS") return THEME_BRNCROSS; if (value == "THEME_WEAPONRACK") return THEME_WEAPONRACK; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseQuest(std::string_view value) +std::expected ParseQuest(std::string_view value) { if (value.empty()) return Q_INVALID; if (value == "Q_ROCK") return Q_ROCK; @@ -228,10 +228,10 @@ tl::expected ParseQuest(std::string_view value) if (value == "Q_NAKRUL") return Q_NAKRUL; if (value == "Q_CORNSTN") return Q_CORNSTN; if (value == "Q_JERSEY") return Q_JERSEY; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseObjectDataFlags(std::string_view value) +std::expected ParseObjectDataFlags(std::string_view value) { if (value.empty()) return ObjectDataFlags::None; if (value == "Animated") return ObjectDataFlags::Animated; @@ -240,16 +240,16 @@ tl::expected ParseObjectDataFlags(std::string_view if (value == "Light") return ObjectDataFlags::Light; if (value == "Trap") return ObjectDataFlags::Trap; if (value == "Breakable") return ObjectDataFlags::Breakable; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseSelectionRegion(std::string_view value) +std::expected ParseSelectionRegion(std::string_view value) { if (value.empty()) return SelectionRegion::None; if (value == "Bottom") return SelectionRegion::Bottom; if (value == "Middle") return SelectionRegion::Middle; if (value == "Top") return SelectionRegion::Top; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } } // namespace diff --git a/Source/tables/playerdat.cpp b/Source/tables/playerdat.cpp index 2db6d7922..d287287a6 100644 --- a/Source/tables/playerdat.cpp +++ b/Source/tables/playerdat.cpp @@ -11,9 +11,9 @@ #include #include #include +#include #include -#include #include #include @@ -74,7 +74,7 @@ enum class ExperienceColumn { LAST = Experience }; -tl::expected mapExperienceColumnFromName(std::string_view name) +std::expected mapExperienceColumnFromName(std::string_view name) { if (name == "Level") { return ExperienceColumn::Level; @@ -82,7 +82,7 @@ tl::expected mapExperienceColumnFromN if (name == "Experience") { return ExperienceColumn::Experience; } - return tl::unexpected { ColumnDefinition::Error::UnknownColumn }; + return std::unexpected { ColumnDefinition::Error::UnknownColumn }; } void ReloadExperienceData() @@ -156,19 +156,19 @@ void ReloadExperienceData() } } -tl::expected ParsePlayerClassFlag(std::string_view value) +std::expected ParsePlayerClassFlag(std::string_view value) { const std::optional enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } void LoadClassData(std::string_view classPath, ClassAttributes &attributes, PlayerCombatData &combat) { const std::string filename = StrCat("txtdata\\classes\\", classPath, "\\attributes.tsv"); - tl::expected dataFileResult = DataFile::loadOrDie(filename); + std::expected dataFileResult = DataFile::loadOrDie(filename); DataFile &dataFile = dataFileResult.value(); dataFile.skipHeaderOrDie(filename); @@ -200,7 +200,7 @@ void LoadClassData(std::string_view classPath, ClassAttributes &attributes, Play void LoadClassStartingLoadoutData(std::string_view classPath, PlayerStartingLoadoutData &startingLoadoutData) { const std::string filename = StrCat("txtdata\\classes\\", classPath, "\\starting_loadout.tsv"); - tl::expected dataFileResult = DataFile::loadOrDie(filename); + std::expected dataFileResult = DataFile::loadOrDie(filename); DataFile &dataFile = dataFileResult.value(); dataFile.skipHeaderOrDie(filename); @@ -218,7 +218,7 @@ void LoadClassStartingLoadoutData(std::string_view classPath, PlayerStartingLoad void LoadClassSpriteData(std::string_view classPath, PlayerSpriteData &spriteData) { const std::string filename = StrCat("txtdata\\classes\\", classPath, "\\sprites.tsv"); - tl::expected dataFileResult = DataFile::loadOrDie(filename); + std::expected dataFileResult = DataFile::loadOrDie(filename); DataFile &dataFile = dataFileResult.value(); dataFile.skipHeaderOrDie(filename); @@ -242,7 +242,7 @@ void LoadClassSpriteData(std::string_view classPath, PlayerSpriteData &spriteDat void LoadClassAnimData(std::string_view classPath, PlayerAnimData &animData) { const std::string filename = StrCat("txtdata\\classes\\", classPath, "\\animations.tsv"); - tl::expected dataFileResult = DataFile::loadOrDie(filename); + std::expected dataFileResult = DataFile::loadOrDie(filename); DataFile &dataFile = dataFileResult.value(); dataFile.skipHeaderOrDie(filename); @@ -280,7 +280,7 @@ void LoadClassAnimData(std::string_view classPath, PlayerAnimData &animData) void LoadClassSounds(std::string_view classPath, ankerl::unordered_dense::map &sounds) { const std::string filename = StrCat("txtdata\\classes\\", classPath, "\\sounds.tsv"); - tl::expected dataFileResult = DataFile::loadOrDie(filename); + std::expected dataFileResult = DataFile::loadOrDie(filename); DataFile &dataFile = dataFileResult.value(); dataFile.skipHeaderOrDie(filename); diff --git a/Source/tables/spelldat.cpp b/Source/tables/spelldat.cpp index 501ae1561..0b8abc25c 100644 --- a/Source/tables/spelldat.cpp +++ b/Source/tables/spelldat.cpp @@ -5,11 +5,10 @@ */ #include "tables/spelldat.h" +#include #include #include -#include - #include "data/file.hpp" #include "data/iterators.hpp" #include "data/record_reader.hpp" @@ -33,26 +32,26 @@ void AddNullSpell() } // A temporary solution for parsing soundID until we have a more general one. -tl::expected ParseSpellSoundId(std::string_view value) +std::expected ParseSpellSoundId(std::string_view value) { if (value == "CastFire") return SfxID::CastFire; if (value == "CastHealing") return SfxID::CastHealing; if (value == "CastLightning") return SfxID::CastLightning; if (value == "CastSkill") return SfxID::CastSkill; - return tl::make_unexpected("Unknown enum value (only a few are supported for now)"); + return std::unexpected("Unknown enum value (only a few are supported for now)"); } -tl::expected ParseSpellDataFlag(std::string_view value) +std::expected ParseSpellDataFlag(std::string_view value) { if (value == "Fire") return SpellDataFlags::Fire; if (value == "Lightning") return SpellDataFlags::Lightning; if (value == "Magic") return SpellDataFlags::Magic; if (value == "Targeted") return SpellDataFlags::Targeted; if (value == "AllowedInTown") return SpellDataFlags::AllowedInTown; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } -tl::expected ParseMissileId(std::string_view value) +std::expected ParseMissileId(std::string_view value) { if (value == "Arrow") return MissileID::Arrow; if (value == "Firebolt") return MissileID::Firebolt; @@ -162,7 +161,7 @@ tl::expected ParseMissileId(std::string_view value) if (value == "BlueExplosion") return MissileID::BlueExplosion; if (value == "BlueExplosion2") return MissileID::BlueExplosion2; if (value == "OrangeExplosion") return MissileID::OrangeExplosion; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } } // namespace @@ -170,7 +169,7 @@ tl::expected ParseMissileId(std::string_view value) /** Data related to each spell ID. */ std::vector SpellsData; -tl::expected ParseSpellId(std::string_view value) +std::expected ParseSpellId(std::string_view value) { if (value == "Null") return SpellID::Null; if (value == "Firebolt") return SpellID::Firebolt; @@ -224,7 +223,7 @@ tl::expected ParseSpellId(std::string_view value) if (value == "RuneOfNova") return SpellID::RuneOfNova; if (value == "RuneOfImmolation") return SpellID::RuneOfImmolation; if (value == "RuneOfStone") return SpellID::RuneOfStone; - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } void LoadSpellData() diff --git a/Source/tables/spelldat.h b/Source/tables/spelldat.h index bba4f4dcf..336c813f5 100644 --- a/Source/tables/spelldat.h +++ b/Source/tables/spelldat.h @@ -6,13 +6,12 @@ #pragma once #include +#include #include #include #include #include -#include - #include "sound_effect_enums.h" #include "utils/enum_traits.h" @@ -88,7 +87,7 @@ enum class SpellID : int8_t { Invalid = -1, }; -tl::expected ParseSpellId(std::string_view value); +std::expected ParseSpellId(std::string_view value); enum class MagicType : uint8_t { Fire, diff --git a/Source/tables/textdat.cpp b/Source/tables/textdat.cpp index 1fb8ee131..ccc40b28b 100644 --- a/Source/tables/textdat.cpp +++ b/Source/tables/textdat.cpp @@ -25,7 +25,7 @@ std::vector Speeches; /** Contains the mapping between text ID strings and indices, used for parsing additional text data. */ ankerl::unordered_dense::map AdditionalTextIdStringsToIndices; -tl::expected<_speech_id, std::string> ParseSpeechId(std::string_view value) +std::expected<_speech_id, std::string> ParseSpeechId(std::string_view value) { if (value.empty()) { return TEXT_NONE; @@ -41,7 +41,7 @@ tl::expected<_speech_id, std::string> ParseSpeechId(std::string_view value) return static_cast<_speech_id>(findIt->second); } - return tl::make_unexpected("Invalid value."); + return std::unexpected("Invalid value."); } namespace { diff --git a/Source/tables/textdat.h b/Source/tables/textdat.h index 0028870a1..da82b60ba 100644 --- a/Source/tables/textdat.h +++ b/Source/tables/textdat.h @@ -6,9 +6,9 @@ #pragma once #include +#include #include -#include #include #include "sound_effect_enums.h" @@ -435,7 +435,7 @@ struct Speech { extern std::vector Speeches; -tl::expected<_speech_id, std::string> ParseSpeechId(std::string_view value); +std::expected<_speech_id, std::string> ParseSpeechId(std::string_view value); void LoadTextData(); diff --git a/Source/tables/townerdat.cpp b/Source/tables/townerdat.cpp index 9f7ab2c15..5d6e367d0 100644 --- a/Source/tables/townerdat.cpp +++ b/Source/tables/townerdat.cpp @@ -6,12 +6,12 @@ #include "tables/townerdat.hpp" #include +#include #include #include #include #include -#include #include #include "data/file.hpp" @@ -31,13 +31,13 @@ namespace { * @return The parsed enum value, or an error message */ template -tl::expected ParseEnum(std::string_view value) +std::expected ParseEnum(std::string_view value) { const auto enumValueOpt = magic_enum::enum_cast(value); if (enumValueOpt.has_value()) { return enumValueOpt.value(); } - return tl::make_unexpected("Unknown enum value"); + return std::unexpected("Unknown enum value"); } /** diff --git a/Source/utils/ini.cpp b/Source/utils/ini.cpp index a000c4280..ecda31827 100644 --- a/Source/utils/ini.cpp +++ b/Source/utils/ini.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -15,7 +16,6 @@ #include #include -#include #include #include @@ -122,7 +122,7 @@ void Ini::Values::append(const Ini::Value &value) std::get>(rep_).push_back(value); } -tl::expected Ini::parse(std::string_view buffer) +std::expected Ini::parse(std::string_view buffer) { Ini::FileData fileData; ankerl::unordered_dense::map *sectionEntries = nullptr; @@ -160,10 +160,10 @@ tl::expected Ini::parse(std::string_view buffer) ++keyEnd; } if (keyEnd == lineEnd) { - return tl::make_unexpected(fmt::format("line {}: unclosed section name {}", lineNum, std::string_view(keyBegin, keyEnd - keyBegin))); + return std::unexpected(fmt::format("line {}: unclosed section name {}", lineNum, std::string_view(keyBegin, keyEnd - keyBegin))); } if (const char *after = SkipTrailingWhitespace(keyEnd + 1, lineEnd); after != lineEnd) { - return tl::make_unexpected(fmt::format("line {}: content after section [{}]: {}", lineNum, std::string_view(keyBegin, keyEnd - keyBegin), std::string_view(after, lineEnd - after))); + return std::unexpected(fmt::format("line {}: content after section [{}]: {}", lineNum, std::string_view(keyBegin, keyEnd - keyBegin), std::string_view(after, lineEnd - after))); } const std::string_view sectionName = std::string_view(keyBegin, keyEnd - keyBegin); auto it = fileData.sections.find(sectionName); @@ -180,10 +180,10 @@ tl::expected Ini::parse(std::string_view buffer) continue; } - if (sectionEntries == nullptr) return tl::unexpected(fmt::format("line {}: key not in any section", lineNum)); + if (sectionEntries == nullptr) return std::unexpected(fmt::format("line {}: key not in any section", lineNum)); const char *eqPos = static_cast(memchr(keyBegin, '=', lineEnd - keyBegin)); if (eqPos == nullptr) { - return tl::make_unexpected(fmt::format("line {}: key {} has no value", lineNum, std::string_view(keyBegin, lineEnd - keyBegin))); + return std::unexpected(fmt::format("line {}: key {} has no value", lineNum, std::string_view(keyBegin, lineEnd - keyBegin))); } const char *keyEnd = SkipTrailingWhitespace(keyBegin, eqPos); const std::string_view key = std::string_view(keyBegin, keyEnd - keyBegin); diff --git a/Source/utils/ini.hpp b/Source/utils/ini.hpp index 119453de0..1c1605f18 100644 --- a/Source/utils/ini.hpp +++ b/Source/utils/ini.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -11,7 +12,6 @@ #include #include -#include #include "utils/string_view_hash.hpp" @@ -51,7 +51,7 @@ public: friend class Ini; }; - static tl::expected parse(std::string_view buffer); + static std::expected parse(std::string_view buffer); [[nodiscard]] std::string serialize() const; /** @return all the keys associated with this section in the ini */ diff --git a/Source/utils/parse_int.hpp b/Source/utils/parse_int.hpp index 76311b41b..f6e946a32 100644 --- a/Source/utils/parse_int.hpp +++ b/Source/utils/parse_int.hpp @@ -2,11 +2,10 @@ #include #include +#include #include #include -#include - namespace devilution { enum class ParseIntError { @@ -15,7 +14,7 @@ enum class ParseIntError { }; template -using ParseIntResult = tl::expected; +using ParseIntResult = std::expected; template ParseIntResult ParseInt( @@ -28,11 +27,11 @@ ParseIntResult ParseInt( *endOfParse = result.ptr; } if (result.ec == std::errc::invalid_argument) - return tl::unexpected(ParseIntError::ParseError); + return std::unexpected(ParseIntError::ParseError); if (result.ec == std::errc::result_out_of_range || value < min || value > max) - return tl::unexpected(ParseIntError::OutOfRange); + return std::unexpected(ParseIntError::OutOfRange); if (result.ec != std::errc()) - return tl::unexpected(ParseIntError::ParseError); + return std::unexpected(ParseIntError::ParseError); return value; } @@ -53,7 +52,7 @@ ParseIntResult ParseFixed6(std::string_view str, const char **endOfParse = } if (str.empty()) { - return tl::unexpected { ParseIntError::ParseError }; + return std::unexpected { ParseIntError::ParseError }; } constexpr IntT minIntegerValue = std::numeric_limits::min() >> 6; @@ -82,7 +81,7 @@ ParseIntResult ParseFixed6(std::string_view str, const char **endOfParse = if (!haveDigits) { // early return in case we got a string like "-.abc", don't want to set the end pointer in this case - return tl::unexpected { ParseIntError::ParseError }; + return std::unexpected { ParseIntError::ParseError }; } if (endOfParse != nullptr) { @@ -100,7 +99,7 @@ ParseIntResult ParseFixed6(std::string_view str, const char **endOfParse = // rounding could give us a value of 64 for the fraction part (e.g. 0.993 rounds to 1.0) so we need to ensure this doesn't overflow if (fractionPart >= 64 && (integerPart >= maxIntegerValue || (std::is_signed_v && integerPart <= minIntegerValue))) { - return tl::unexpected { ParseIntError::OutOfRange }; + return std::unexpected { ParseIntError::OutOfRange }; } else { IntT fixedValue = integerPart << 6; if (isNegative) { diff --git a/Source/utils/status_macros.hpp b/Source/utils/status_macros.hpp index 2b8766c3b..c1826e205 100644 --- a/Source/utils/status_macros.hpp +++ b/Source/utils/status_macros.hpp @@ -4,7 +4,7 @@ #define RETURN_IF_ERROR(expr) \ if (auto result = expr; DVL_PREDICT_FALSE(!result.has_value())) { \ - return tl::make_unexpected(std::move(result).error()); \ + return std::unexpected(std::move(result).error()); \ } #define STATUS_MACROS_CONCAT_NAME_INNER(x, y) x##y @@ -13,7 +13,7 @@ #define ASSIGN_OR_RETURN_IMPL(result, lhs, rhs) \ auto result = rhs; /* NOLINT(bugprone-macro-parentheses): assignment */ \ if (DVL_PREDICT_FALSE(!result.has_value())) { /* NOLINT(bugprone-macro-parentheses): assignment */ \ - return tl::make_unexpected(std::move(result).error()); \ + return std::unexpected(std::move(result).error()); \ } \ lhs = std::move(result).value(); /* NOLINT(bugprone-macro-parentheses): assignment */ diff --git a/Source/utils/surface_to_pcx.cpp b/Source/utils/surface_to_pcx.cpp index a281b135c..5141d0590 100644 --- a/Source/utils/surface_to_pcx.cpp +++ b/Source/utils/surface_to_pcx.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #ifdef USE_SDL3 @@ -13,8 +14,6 @@ #include #endif -#include - #include "engine/surface.hpp" #include "utils/endian_swap.hpp" #include "utils/pcx.hpp" @@ -23,13 +22,13 @@ namespace devilution { namespace { -tl::expected CheckedFWrite(const void *ptr, size_t size, SDL_IOStream *out) +std::expected CheckedFWrite(const void *ptr, size_t size, SDL_IOStream *out) { if (SDL_WriteIO(out, ptr, size) != size) { const char *errorMessage = SDL_GetError(); if (errorMessage == nullptr) errorMessage = ""; - tl::expected result = tl::make_unexpected(std::string("write failed with: ").append(errorMessage)); + std::expected result = std::unexpected(std::string("write failed with: ").append(errorMessage)); SDL_ClearError(); return result; } @@ -43,7 +42,7 @@ tl::expected CheckedFWrite(const void *ptr, size_t size, SDL_ * @param out File stream to write to * @return True on success */ -tl::expected WritePcxHeader(int16_t width, int16_t height, SDL_IOStream *out) +std::expected WritePcxHeader(int16_t width, int16_t height, SDL_IOStream *out) { PCXHeader buffer; @@ -68,7 +67,7 @@ tl::expected WritePcxHeader(int16_t width, int16_t height, SD * @param out File stream for the PCX file. * @return True if successful, else false */ -tl::expected WritePcxPalette(SDL_Color *palette, SDL_IOStream *out) +std::expected WritePcxPalette(SDL_Color *palette, SDL_IOStream *out) { uint8_t pcxPalette[1 + 256 * 3]; @@ -131,7 +130,7 @@ uint8_t *WritePcxLine(uint8_t *src, uint8_t *dst, int width) * @param out File stream for the PCX file. * @return True if successful, else false */ -tl::expected WritePcxPixels(const Surface &buf, SDL_IOStream *out) +std::expected WritePcxPixels(const Surface &buf, SDL_IOStream *out) { const int width = buf.w(); const std::unique_ptr pBuffer { new uint8_t[static_cast(2 * width)] }; @@ -139,7 +138,7 @@ tl::expected WritePcxPixels(const Surface &buf, SDL_IOStream for (int height = buf.h(); height > 0; height--) { const uint8_t *pBufferEnd = WritePcxLine(pixels, pBuffer.get(), width); pixels += buf.pitch(); - tl::expected result = CheckedFWrite(pBuffer.get(), pBufferEnd - pBuffer.get(), out); + std::expected result = CheckedFWrite(pBuffer.get(), pBufferEnd - pBuffer.get(), out); if (!result.has_value()) return result; } return {}; @@ -147,10 +146,10 @@ tl::expected WritePcxPixels(const Surface &buf, SDL_IOStream } // namespace -tl::expected +std::expected WriteSurfaceToFilePcx(const Surface &buf, SDL_IOStream *outStream) { - tl::expected result = WritePcxHeader(buf.w(), buf.h(), outStream); + std::expected result = WritePcxHeader(buf.w(), buf.h(), outStream); if (!result.has_value()) return result; result = WritePcxPixels(buf, outStream); if (!result.has_value()) return result; diff --git a/Source/utils/surface_to_pcx.hpp b/Source/utils/surface_to_pcx.hpp index 65c71298f..b377842fc 100644 --- a/Source/utils/surface_to_pcx.hpp +++ b/Source/utils/surface_to_pcx.hpp @@ -1,3 +1,4 @@ +#include #include #ifdef USE_SDL3 @@ -8,13 +9,11 @@ #include "utils/sdl_compat.h" #endif -#include - #include "engine/surface.hpp" namespace devilution { -tl::expected +std::expected WriteSurfaceToFilePcx(const Surface &buf, SDL_IOStream *outStream); } // namespace devilution diff --git a/Source/utils/surface_to_png.cpp b/Source/utils/surface_to_png.cpp index ec116a04d..0ad411f11 100644 --- a/Source/utils/surface_to_png.cpp +++ b/Source/utils/surface_to_png.cpp @@ -1,5 +1,6 @@ #include "utils/surface_to_png.hpp" +#include #include #ifdef USE_SDL3 @@ -12,8 +13,6 @@ #include "utils/sdl_compat.h" #endif -#include - #include "engine/surface.hpp" namespace devilution { @@ -22,7 +21,7 @@ namespace devilution { extern "C" int IMG_SavePNG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst); #endif -tl::expected +std::expected WriteSurfaceToFilePng(const Surface &buf, SDL_IOStream *dst) { #ifdef USE_SDL3 @@ -31,7 +30,7 @@ WriteSurfaceToFilePng(const Surface &buf, SDL_IOStream *dst) const bool ok = IMG_SavePNG_RW(buf.surface, dst, /*freedst=*/1) == 0; #endif if (!ok) { - tl::expected result = tl::make_unexpected(std::string(SDL_GetError())); + std::expected result = std::unexpected(std::string(SDL_GetError())); SDL_ClearError(); return result; } diff --git a/Source/utils/surface_to_png.hpp b/Source/utils/surface_to_png.hpp index 14aede4b6..5ec1447b4 100644 --- a/Source/utils/surface_to_png.hpp +++ b/Source/utils/surface_to_png.hpp @@ -1,4 +1,5 @@ #include +#include #include #ifdef USE_SDL3 @@ -8,8 +9,6 @@ #include #endif -#include - #include "engine/surface.hpp" namespace devilution { @@ -19,7 +18,7 @@ namespace devilution { * * Takes ownership of `dst` and closes it when done. */ -tl::expected +std::expected WriteSurfaceToFilePng(const Surface &buf, #ifdef USE_SDL3 SDL_IOStream * diff --git a/test/data_file_test.cpp b/test/data_file_test.cpp index 5062135ac..9e7b4f3dc 100644 --- a/test/data_file_test.cpp +++ b/test/data_file_test.cpp @@ -200,7 +200,7 @@ TEST(DataFileTest, ParseInt) } DataFile &dataFile = result.value(); - auto unused = dataFile.parseHeader(nullptr, nullptr, [](std::string_view) -> tl::expected { return tl::unexpected { ColumnDefinition::Error::UnknownColumn }; }); + auto unused = dataFile.parseHeader(nullptr, nullptr, [](std::string_view) -> std::expected { return std::unexpected { ColumnDefinition::Error::UnknownColumn }; }); EXPECT_TRUE(unused.has_value()) << "Should be able to parse and discard the header from the sample.tsv file"; @@ -334,7 +334,7 @@ TEST(DataFileTest, ParseHeaderThenIterateOverRecords) { "1", "", "3" }, }; - auto parseHeaderResult = dataFile.parseHeader(nullptr, nullptr, [](std::string_view) -> tl::expected { return tl::unexpected { ColumnDefinition::Error::UnknownColumn }; }); + auto parseHeaderResult = dataFile.parseHeader(nullptr, nullptr, [](std::string_view) -> std::expected { return std::unexpected { ColumnDefinition::Error::UnknownColumn }; }); EXPECT_TRUE(parseHeaderResult.has_value()) << "Expected to be able to parse and discard the header record"; unsigned row = 0; diff --git a/test/ini_test.cpp b/test/ini_test.cpp index f35f68770..d1f879de0 100644 --- a/test/ini_test.cpp +++ b/test/ini_test.cpp @@ -32,7 +32,7 @@ std::string ReplaceNewlines(std::string_view s) TEST(IniTest, BasicTest) { - tl::expected result = Ini::parse(R"( + std::expected result = Ini::parse(R"( ; Section A comment [sectionA] key1 = value1 diff --git a/test/text_render_integration_test.cpp b/test/text_render_integration_test.cpp index 6f4cacbe2..42b37d254 100644 --- a/test/text_render_integration_test.cpp +++ b/test/text_render_integration_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -15,7 +16,6 @@ #include #endif -#include #include #include "engine/load_file.hpp" @@ -397,7 +397,7 @@ TEST_P(TextRenderIntegrationTest, RenderAndCompareTest) SDL_IOStream *actual = SDL_IOFromFile(actualPath.c_str(), "wb"); ASSERT_NE(actual, nullptr) << SDL_GetError(); - const tl::expected result = WriteSurfaceToFilePng(out, actual); + const std::expected result = WriteSurfaceToFilePng(out, actual); ASSERT_TRUE(result.has_value()) << result.error(); // We compare pixels rather than PNG file contents because different