From 240a3ac4806c07b1ed2c59394d2cf08d9708a810 Mon Sep 17 00:00:00 2001 From: Kelvin Sherlock Date: Sat, 20 Dec 2014 12:20:18 -0500 Subject: [PATCH] add tool_return pair for returning error or value. --- macos/errors.h | 14 +++++ macos/tool_return.h | 137 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 macos/tool_return.h diff --git a/macos/errors.h b/macos/errors.h index f24845f..ff3f0f1 100644 --- a/macos/errors.h +++ b/macos/errors.h @@ -577,6 +577,20 @@ namespace MacOS { { return std::error_condition(static_cast(e), macos_system_category()); } + + inline void throw_macos_error(int e) + { + throw std::system_error(e, macos_system_category()); + } + inline void throw_macos_error(int e, const char *what) + { + throw std::system_error(e, macos_system_category(), what); + } + inline void throw_macos_error(int e, const std::string &what) + { + throw std::system_error(e, macos_system_category(), what); + } + } namespace std { diff --git a/macos/tool_return.h b/macos/tool_return.h new file mode 100644 index 0000000..52b9ce9 --- /dev/null +++ b/macos/tool_return.h @@ -0,0 +1,137 @@ +#ifndef __tool_return__ +#define __tool_return__ + +#include "errors.h" +#include + +namespace MacOS { + + namespace internal { + + class tool_return_base + { + protected: + macos_error _error; + + tool_return_base() : _error(static_cast(0)) + {} + + tool_return_base(macos_error error) : _error(error) + {} + + public: + + macos_error error() const + { + return _error; + } + + + template + void throw_macos_error(Args&&... args) const + { + if (_error) MacOS::throw_macos_error(_error, std::forward(args)...); + + } + + }; + } // namespace + + template + class tool_return : public internal::tool_return_base + { + private: + T _value; + + tool_return() = delete; + + operator T() const + { + return _value; + } + + public: + + tool_return(T value) : _value(value) + {} + + tool_return(macos_error error) : tool_return_base(error) + {} + + + tool_return &operator=(T value) + { + _value = value; + _error = 0; + return *this; + } + + tool_return &operator=(macos_error error) + { + _value = T(); + _error = error; + return *this; + } + + + constexpr const T* operator->() const + { + return &_value; + } + + + constexpr const T& operator *() const + { + return _value; + } + + + T value() const + { + return _value; + } + + template + T value_or(U&& u) const + { + if (_error) return u; + return _value; + } + + template + T value_or_throw(Args&&... args) const + { + if (_error) throw_macos_error(std::forward(args)...); + + return _value; + } + + + + + + }; + + template<> + class tool_return : public internal::tool_return_base + { + public: + + tool_return() + {} + + tool_return(macos_error error) : tool_return_base(error) + {} + + tool_return &operator=(macos_error error) + { + _error = error; + return *this; + } + + + }; + + +} // namespace IIgs +#endif