82 lines
1.9 KiB
C++
82 lines
1.9 KiB
C++
#ifndef NEER_RESULT_H
|
|
#define NEER_RESULT_H
|
|
//#define Ok(v) (nerr::Result(v))
|
|
//#define Err(e) (nerr::Result(e))
|
|
|
|
namespace nerr
|
|
{
|
|
//template <typename T> class Option;
|
|
|
|
template <typename T, typename E>
|
|
class Result
|
|
{
|
|
|
|
public:
|
|
Result(T obj) : m_result(obj) {};
|
|
Result(E err) { m_error.insert(err); };
|
|
Result(){};
|
|
|
|
inline Result<T,E>& operator=(const T& value) {m_result = value; m_error = None(E); return *this;};
|
|
inline Result<T,E>& operator=(const E& err) {m_error.insert(err); return *this;};
|
|
|
|
inline bool is_ok(){return m_error.is_none();};
|
|
inline bool is_err(){return m_error.is_some();};
|
|
|
|
inline T& unwrap()
|
|
{
|
|
if(is_ok())
|
|
{
|
|
return m_result;
|
|
}
|
|
throw m_error.unwrap();
|
|
}
|
|
|
|
inline T& expect(E e)
|
|
{
|
|
if(is_ok())
|
|
{
|
|
return m_result;
|
|
}
|
|
throw e + m_error.unwrap();
|
|
}
|
|
|
|
template<typename U>
|
|
inline Result<U,E> map(const std::function<U(T)>& fn)
|
|
{
|
|
if(is_ok())
|
|
{
|
|
return fn(m_result);
|
|
}
|
|
return m_error.unwrap();
|
|
}
|
|
|
|
template<typename E1>
|
|
inline Result<T,E1> map_err(const std::function<E1(E)>& fn)
|
|
{
|
|
if(!is_ok())
|
|
{
|
|
return fn(m_error.unwrap());
|
|
}
|
|
return m_result;
|
|
}
|
|
|
|
template<typename U>
|
|
inline U map_or(U defv, const std::function<U(T)>& fn)
|
|
{
|
|
if(is_ok())
|
|
{
|
|
return fn(m_result);
|
|
}
|
|
return defv;
|
|
}
|
|
|
|
Option<E> err() { return m_error; }
|
|
Option<T> ok() { return is_ok()?Option<T>(m_result): Option<T>(); }
|
|
|
|
private:
|
|
T m_result;
|
|
Option<E> m_error;
|
|
};
|
|
}
|
|
|
|
#endif |