1 // =================================
 2 // Copyright (c) 2024 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 namespace System
 7 {
 8     public class ErrorId
 9     {
10         public ErrorId(int value_) : value(value_) {}
11         public default ErrorId(const ErrorId&);
12         public int value;
13     }
14 
15 //  The Result<T> class template will hold either a value T or an error identifier.
16 //  An error identifier is a integer that represents an error instance contained by the runtime.
17 //  Error identifier 0 indicates success and positive integer indicates an error.
18 
19     public class Result<T>
20     {
21         public Result() : value()errorId(0) {}
22         public Result(const T& value_) : value(value_)errorId(0) {}
23         public Result(T&& value_) : value(Rvalue(value_))errorId(0) {}
24         public Result(ErrorId errorId_) : value()errorId(errorId_.value) {}
25         public Result<T> AndThen(const Result<T>& second) { if (Error()) return *this; else return second; }
26         public inline const T& Value() const { return value; }
27         public inline T& Value() { return value; }
28         public inline bool Error() const { return errorId != 0; }
29         public inline int GetErrorId() const { return errorId; }
30         public void SetErrorId(int errorId_) { errorId = errorId_; }
31         public string GetErrorMessage() const { return RtmGetErrorMessage(errorId); }
32         private T value;
33         private int errorId;
34     }
35 
36     public bool operator==<T>(const Result<T>& leftconst Result<T>& right)
37     {
38         return left.Value() == right.Value() && left.GetErrorId() == right.GetErrorId();
39     }
40 
41     public bool operator<<T>(const Result<T>& leftconst Result<T>& right)
42     {
43         if (left.Value() < right.Value()) return true;
44         if (left.Value() > right.Value()) return false;
45         return left.GetErrorId() < right.GetErrorId();
46     }
47 
48 //  AllocateError creates and returns an error identifier for an error message.
49 
50     public int AllocateError(const string& errorMessage)
51     {
52         return RtmAllocateError(errorMessage.Chars());
53     }
54 
55 //  GetErrorMessage returns an error message for an error identifier. In debug mode the error message will contain a stack trace.
56 
57     public string GetErrorMessage(int errorId)
58     {
59         return RtmGetErrorMessage(errorId);
60     }
61 
62     public int GetErrno()
63     {
64         return RtmGetErrno();
65     }