The Pedigree Project 0.1
Result.h
1/*
2 * Copyright (c) 2008-2014, Pedigree Developers
3 *
4 * Please see the CONTRIB file in the root of the source tree for a full
5 * list of contributors.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#ifndef KERNEL_UTILITIES_RESULT_H
21#define KERNEL_UTILITIES_RESULT_H
22
23#include "pedigree/kernel/utilities/assert.h"
24#include "pedigree/kernel/utilities/utility.h"
25
35template <class T, class E>
36class Result {
37 public:
38 static Result<T, E> withValue(const T& v) {
39 return Result<T, E>(v);
40 }
41
42 static Result<T, E> withError(const E& e) {
43 return Result<T, E>(e, true);
44 }
45
46 const T& value() const {
47 assert(hasValue());
48 return m_Value;
49 }
50
51 const E& error() const {
52 assert(hasError());
53 return m_Error;
54 }
55
56 bool hasError() const {
57 return m_HasError;
58 }
59
60 bool hasValue() const {
61 return !hasError();
62 }
63
64 private:
65 Result() = delete;
66
67 Result(const T& v) : m_Value(v), m_Error(), m_HasError(false) {}
68
69 Result(const E& e, bool) : m_Value(m_DefaultValue), m_Error(e), m_HasError(true) {}
70
71 T m_Value;
72 E m_Error;
73 bool m_HasError;
74
75 typedef typename pedigree_std::remove_reference<T>::type BaseValueType;
76 static const BaseValueType m_DefaultValue;
77};
78
79template <class T, class E>
80const typename Result<T, E>::BaseValueType Result<T, E>::m_DefaultValue =
81 Result<T, E>::BaseValueType();
82
83#endif // KERNEL_UTILITIES_RESULT_H