From f7a161c69030ea18f352dd5fd37cf1ae4ea4d040 Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Fri, 11 Dec 2020 16:02:18 +0100 Subject: [PATCH] Adds new result class to show a functions success or failure. --- src/Result.hpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/Result.hpp diff --git a/src/Result.hpp b/src/Result.hpp new file mode 100644 index 0000000..cad2b62 --- /dev/null +++ b/src/Result.hpp @@ -0,0 +1,58 @@ +#ifndef ARBUTILS_RESULT_HPP +#define ARBUTILS_RESULT_HPP + +namespace ArbUt { + /// @brief Whether the result was okay, or was an error + enum class ResultStatus : uint8_t { Ok, Error }; + + /// @brief Simple data class to return a functions success or failure. + /// @tparam T The potential return value of the function. + template class Result { + public: + /// @brief Return a success, along with the success value. + /// @param value The value to return. + /// @return The result class + inline static const Result& Ok(T value) { return Result(ResultStatus::Ok, value); } + /// @brief Return an error, along with an error message. + /// @param message The error message to return + /// @return The result class + inline static const Result& Error(const std::string& message) { return Result(message); } + + /// @brief Returns whether or not the function succeeded, + /// @return Whether or not the function succeeded. + [[nodiscard]] inline ResultStatus GetStatus() const noexcept { return _resultStatus; } + + /// @brief The value of the result if it was successful. + /// @return The value of the result if it was successful. + inline const T& GetValue() const noexcept { + Assert(_resultStatus == ResultStatus::Ok); + return _resultValue; + } + + /// @brief The value of the result if it was successful. + /// @return The value of the result if it was successful. + inline T& GetValue() noexcept { + Assert(_resultStatus == ResultStatus::Ok); + return _resultValue; + } + + /// @brief Returns the error message if it errored. + /// @return The error message if it errored. + [[nodiscard]] inline const std::string& GetErrorMessage() const noexcept { + Assert(_resultStatus == ResultStatus::Error); + return _errorMessage; + } + + private: + Result(ResultStatus result, const T& value) : _resultStatus(result), _resultValue(value) {} + explicit Result(const std::string& error) : _resultStatus(ResultStatus::Error), _errorMessage(error) {} + + ResultStatus _resultStatus; + union { + T _resultValue; + std::string _errorMessage{}; + }; + }; +} + +#endif // ARBUTILS_RESULT_HPP