Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/videos/_index.md
+++ title = "Videos" weight = 40 +++ Outcome has been presented at some of the major C++ conferences as it has evolved. As the older content is less relevant to Outcome today, this list is given in reverse chronological order. --- ## Dublin C++ users group 2018 *"Deterministic Disappointment"* *Literature review of the WG21 papers relating to deterministically handling failure, and using libraries such as Outcome to implement the same.* {{< youtube cbUTAoHy6Ls >}} {{< slides "d/e/2PACX-1vRR3_ZXU8pC_1oFH6rctPJ1wijWCQY-uGIBEK2SzOLaVnuFjn7Ed76sYs8QE6pUl-oP2nrggw-b4fma" >}} --- ## Meeting C++ 2017 *"Introduction to proposed std::expected&lt;T, E&gt;"* *Literature review of the several WG21 papers relating to std::expected<T, E>.* {{< youtube JfMBLx7qE0I >}} {{< slides "d/e/2PACX-1vSnTCn_hX3_uKNco8LtJTgAg2LrRO0zOJ3JiQiWMFFG8pNVwvUZr2ooYjXO9V94kdlqLxSB7DLTLPf5" >}} --- ## ACCU 2017 *"Mongrel Monads, Dirty, dirty, dirty"* *Covers the history of error handling in C++, and how the LEWG Expected works.* *(Note that the Expected presented here no longer exists, it was substantially changed after the Outcome v1 peer review. Furthermore the Outcome presented here no longer exists, the peer review demanded a complete rebuild)* {{< youtube XVofgKH-uu4 >}} {{< slides "d/e/2PACX-1vQZXLxkB716ZIMcEqV8QkeUvKhG33BmzKJdzSvx6QRfEGjmjXjHjeLrXSjgTZwG2rCaBNAZTxj41r5n" >}}
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/_index.md
+++ title = "Experimental" weight = 15 +++ In `<outcome/experimental>`, there ships an Outcome-based simulation of the proposed [P1095 *Zero overhead deterministic failure*](https://wg21.link/P1095) specific implementation of [P0709 *Zero overhead exceptions: Throwing values*](http://wg21.link/P0709). This library-only implementation lets you use a close simulacrum of potential future C++ lightweight exceptions today in [any C++ 14 compiler which Outcome supports]({{< relref "/requirements" >}}). This Experimental Outcome implementation has been in production use for some years now. It has shipped on at least one billion devices, as part of a games suite very popular on Microsoft Windows, Apple iOS and Google Android devices. It powers big iron enterprise applications as well, indeed all trades including futures in the United States are captured live into a database for the SEC by an Experimental Outcome based codebase. Finally, Experimental Outcome is used in the firmware of parts of driver assisting cars where its particularly rich and flexible failure added information combined with compatibility with globally disabled C++ exceptions proved to be a big win. The base for failure handling in future C++ might be `std::error` from [P1028 `status_code`](https://wg21.link/P1028). This proposal is currently being refined before WG21's Library Evolution Working Group with the expectation that it will be standardised as a large enhancement and backwards compatible superset of `std::error_code` which is also capable of transporting any move-only type such as `std::exception_ptr`. Like `std::error_code`, proposed `std::error` occupies exactly two CPU registers of layout, and thus is extremely lightweight. It can wrap arbitrary third party error handling systems, and automatically constructs from `std::error_code` and `std::exception_ptr`, propagating the original underlying implementations (no matter how customised) exactly (e.g. `boost::exception_ptr`). Unlike `<system_error>`, `std::error` does not have dependencies on expensive standard library headers, so including it into your global build has a very low build time impact. `std::error` knows how to throw itself as a conventional C++ exception, and knows how to losslessly consume arbitrary C++ exception throws. Finally, `std::error` is ABI stable, and is a [P1029 move bitcopying](https://wg21.link/P1029) type whereby moved-from objects do not need to be destroyed. --- Experimental Outcome uses the [same proposed `std::error` object as P1095 would do for its `E` type](https://wg21.link/P1028) by bundling internally a copy of https://ned14.github.io/status-code/, the reference implementation library for proposed `std::error`. Outcome emulates move bitcopying semantics for types declaring themselves move bitcopying via the trait {{% api "is_move_bitcopying<T>" %}}, and status codes opt into this. This greatly improves codegen to be no worse than with `std::error_code` (a trivially copyable type), as https://godbolt.org/z/GEdEGc demonstrates, despite that proposed `std::error` is a move-only type with a non-trivial destructor. Outcome binds `status_code` into `basic_result` and `basic_outcome` customisations via the following headers: - `<outcome/experimental/status_result.hpp>` - `<outcome/experimental/status_outcome.hpp>` These headers import the entire contents of the `SYSTEM_ERROR2_NAMESPACE` namespace into the `OUTCOME_V2_NAMESPACE::experimental` namespace. You can thus address everything in `SYSTEM_ERROR2_NAMESPACE` via `OUTCOME_V2_NAMESPACE::experimental`. As P1095 also proposes C language support for lightweight C++ exceptions, experimental Outcome also has a macro-based C interface that enables C code to work with the C-compatible subset of `status_result<T, E>`: - `<outcome/experimental/result.h>` For non-Windows non-POSIX platforms such as some embedded systems, standalone Experimental Outcome can be used with the `SYSTEM_ERROR2_NOT_POSIX` macro defined. This does not include POSIX headers, and makes available a high fidelity, fully deterministic, alternative to C++ exceptions on such platforms. Finally, there is a single include edition of Experimental Outcome, which can be found at https://github.com/ned14/outcome/blob/develop/single-header/outcome-experimental.hpp. You can play with this on godbolt by `#include <outcome-experimental.hpp>`. {{% notice warning %}} <b>It is stressed, in the strongest possible terms, that any item inside `<outcome/experimental>` is subject to unannounced breaking change based on WG21 standards committee feedback</b>. That said, the chances are high that most of those breaking changes will be to naming rather than to fundamental semantics, so you can upgrade with a bit of find and replace. {{% /notice %}}
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/map.md
+++ title = "Approximate map between error code designs" weight = 10 +++ Much of the design of Boost.System (which went on to become `<system_error>`) has been retained in proposed `<system_error2>`, so an approximate map between `<system_error2>` and `<system_error>` and Boost.System can be given: <table width="100%" cellpadding="5" border="1"> <colgroup> <col width="25%"> <col width="25%"> <col width="50%"> </colgroup> <tr><th>C++ 17 <tt>&lt;system_error&gt;</tt><th>Boost.System<th>Proposed <tt>&lt;system_error2&gt;</tt> <tr> <td style="vertical-align: top;"><tt>std::errc</tt> <td style="vertical-align: top;"><tt>boost::system::errc</tt> <td style="vertical-align: top;"><tt>experimental::errc</tt> (almost identical) <tr> <td style="vertical-align: top;"><tt>std::error_category</tt> <td style="vertical-align: top;"><tt>boost::system::error_category</tt> <td style="vertical-align: top;"><tt>experimental::status_code_domain</tt> <tr> <td style="vertical-align: top;"><tt>std::generic_category</tt> <td style="vertical-align: top;"><tt>boost::system::generic_category</tt> <td style="vertical-align: top;"><tt>experimental::generic_code_domain</tt> <tr> <td style="vertical-align: top;"><tt>std::system_category</tt> <td style="vertical-align: top;"><tt>boost::system::system_category</tt> <td style="vertical-align: top;">One of:<ul> <li><tt>experimental::posix_code_domain</tt> (POSIX systems)<p> <li><tt>experimental::win32_code_domain</tt> (Microsoft Windows)<p> <li><tt>experimental::nt_code_domain</tt> (Microsoft Windows) </ul> Note that there are more precanned code categories though they require additional header inclusions: <tt>com_code</tt>, <tt>getaddrinfo_code</tt>. <tr> <td style="vertical-align: top;"><tt>std::error_condition</tt> <td style="vertical-align: top;"><tt>boost::system::error_condition</tt> <td style="vertical-align: top;"><b>No equivalent</b> (deliberately removed as hindsight proved it to be a design mistake leading to much confusing and hard to audit for correctness code) <tr> <td style="vertical-align: top;"><tt>std::error_code</tt> <td style="vertical-align: top;"><tt>boost::system::error_code</tt> <td style="vertical-align: top;">One of:<ul> <li><tt>experimental::status_code&lt;DomainType&gt;</tt><p> <li><tt>const experimental::status_code&lt;void&gt; &amp;</tt><p> <li><tt>experimental::status_code&lt;erased&lt;intptr_t&gt;&gt;</tt> (aliased to <tt>experimental::system_code</tt>)<p> <li><tt>experimental::errored_status_code&lt;DomainType&gt;</tt><p> <li><tt>const experimental::errored_status_code&lt;void&gt; &amp;</tt><p> <li><tt>experimental::errored_status_code&lt;erased&lt;intptr_t&gt;&gt;</tt> (aliased to <tt>experimental::error</tt>) </ul> The difference between status codes and errored status codes is that the latter are guaranteed to refer to a failure, whereas the former may refer to a success (including warnings and informationals). <tr> <td style="vertical-align: top;"><tt>std::system_error</tt> <td style="vertical-align: top;"><tt>boost::system::system_error</tt> <td style="vertical-align: top;">One of:<ul> <li><tt>const experimental::status_error&lt;void&gt; &amp;</tt><p> <li><tt>experimental::status_error&lt;DomainType&gt;</tt> </ul> </table> As is obvious from the above, in `<system_error2>` one must be much more specific and accurate with respect to intent and specification and desired semantics than with `<system_error>`. Much ambiguity and incorrectness which flies silently in `<system_error>` will refuse to compile in `<system_error2>`.
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/outcome.md
+++ title = "Tying it all together" weight = 75 +++ Firstly let's alias a more convenient form of `status_result`: {{% snippet "experimental_status_code.cpp" "typedef" %}} (The defaulting of `default_result_policy` is superfluous, it's already the default) What follows now is very standard Outcome code. Indeed, it would compile just fine under standard Outcome with only a few typedefs. {{% snippet "experimental_status_code.cpp" "open_file" %}} And running this program yields: ``` Returned error has a code domain of 'file i/o error domain', a message of 'No such file or directory (c:\users\ned\documents\boostish\outcome\doc\src\snippets\experimental_status_code.cpp:195)' And semantically comparing it to 'errc::no_such_file_or_directory' = 1 ``` ### Conclusion Once you get used to `<system_error2>` and the fact that any `result` with `E = error` is always move-only, using experimental Outcome is just like using normal Outcome. Except that codegen will be better, custom domains are safe to use in headers, semantic comparisons have guaranteed complexity bounds, and build times are much reduced. What's not to like? :) Finally, if you have feedback on using experimental Outcome which you think would be of use to the standards committee when evaluating possible implementations of [P0709 *Zero overhead exceptions: Throwing values*](http://wg21.link/P0709), please do get in touch! This **especially** includes successful experiences!!!
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/status_result.md
+++ title = "`status_result` and `status_outcome`" weight = 40 +++ `status_result` and `status_outcome` are type aliases to {{< api "basic_result<T, E, NoValuePolicy>" >}} and {{< api "basic_outcome<T, EC, EP, NoValuePolicy>" >}} in the usual way, but with a defaulted `NoValuePolicy` which selects on the basis of `status_code<DomainType>` instead. {{% notice note %}} If the `E` type is not some `status_code<>`, the default policy selector will complain. {{% /notice %}} The specifications are: ```c++ experimental::status_result<T, E = experimental::error> experimental::status_outcome<T, E = experimental::error, EP = std::exception_ptr> ``` So, the default `E` is the erased errored status code `system_code`, which can represent any `generic_code`, `posix_code`, `win32_code`, `nt_code`, `com_code` and many other integer error and status codings. Because it is an errored status code, it will always represent a failure. You can absolutely choose an `E` type which is non-erased e.g. `posix_code` directly. You can also choose an `E` type which is not contract guaranteed to be a failure, though your users may find that surprising. Whether to choose typed status codes versus the erased status codes depends on your use cases. Outcome replicates faithfully the implicit and explicit conversion semantics of its underlying types, so you can mix results and outcomes of `<system_error2>` types exactly as you can the `<system_error2>` types themselves e.g. typed forms will implicitly convert into erased forms if the source type is trivially copyable or move relocating. This means that you can return a `generic_code` from a function returning a `system_code` or `error`, and it'll work exactly as you'd expect (implicit conversion). {{% notice note %}} As `status_code<erased<T>>` is move-only, so is any `status_result` or `status_outcome`. For some reason this surprises a lot of people, and they tend to react by not using the erased form because it seems "difficult". {{% /notice %}} It is actually, in fact, a wise discipline to follow to make all functions return move-only types if you care about determinism and performance. Whilst C++ 17 onwards does much to have the compiler avoid copying of identical function return values thanks to guaranteed copy elision, when a chain of functions return different types, if the programmer forgets to scatter `std::move()` appropriately, copies rather than moves tend to occur in non-obvious ways. No doubt future C++ standards will improve on the automatic use of moves instead of copies where possible, but until then making all your `result` and `outcome` types move-only is an excellent discipline. Note that move-only `result` and `outcome` capable code (i.e. your project is in Experimental Outcome configuration) usually compiles fine when `result` and `outcome` are copyable (i.e. your project is in Standard Outcome configuration), albeit sometimes with a few compiler warnings about unnecessary use of `std::move()`.
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/advantages.md
+++ title = "The main advantages" weight = 5 +++ The main advantages of choosing `<outcome/experimental>` over default Outcome: 1. Codegen is tighter and less verbose[^1], sometimes remarkably so. 2. Build time impact is markedly lower, barely above the inclusion of naked `<basic_result.hpp>`, as the STL allocator machinery and `std::string` et al is not dragged into inclusion by including `<system_error>`. Note that `<outcome/experimental/status_outcome.hpp>` bring in `<exception>`, however `<outcome/experimental/status_result.hpp>` brings in no extra system headers. 3. More discipline is imposed on your use of Outcome, leading to less ambiguous code which is easier to optimise by the compiler, lower cost to maintain, and lower cognitive load to audit code based on experimental Outcome for correctness. 4. Code written to `<outcome/experimental>` can be fairly easily dual targeted, with just a few switching type aliases, to default Outcome. This author has several Outcome-based libraries with identical source code which can target either configuration of Outcome. The experimental Outcome build regularly beats the default Outcome build in benchmarks by 2-3%, and the dual target source code, being written to tighter discipline, is faster and more deterministic in the default target than it was before the (non-trivial) port to `<outcome/experimental>`. 5. If you want 'official' C support, experimental Outcome is able to provide that in a way not possible for default Outcome which cannot make sufficiently strong C compatibility assumptions about `std::error_code`. If you are building a codebase on top of Outcome expecting long term maintenance, the author's personal recommendation is that you design, write, test and optimise it for `<outcome/experimental>`. What you ship to your customers ought to be targeted at default Outcome however, so employ type aliases and macros as appropriate to switch the build configuration for production releases. This is what the Outcome author does himself, to date with great success, despite the fundamental architectural differences between `<system_error>` and proposed `<system_error2>`. [^1]: Boost.System's `error_code` has incorporated some of the design improvements of experimental `status_code`, and produces codegen somewhere in between experimental `status_code` and `std::error_code`.
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/experimental/differences.md
+++ title = "Major differences" weight = 20 +++ The major design differences between `<system_error>` and proposed `<system_error2>` are as follows: 1. `experimental::status_code<DomainType>` can represent warnings and form-of-success codes as well as failure codes. `experimental::errored_status_code<DomainType>` is more similar to `std::error_code`, in that it can only represent failures (this is enforced by C++ 20 contract or runtime assertion check). 2. The code's domain implementation defines the payload type to be transported around by `experimental::status_code<DomainType>`, rather than it being hardcoded to `int` as in `std::error_code`. The payload type can be anything you like, including non-trivially-copyable, move-only, complex etc types. This facility is extremely useful. Extra failure metadata such as stack backtraces can be returned, for example. You can absolutely vary the payload depending on whether `NDEBUG` or `_DEBUG` is defined, too. 3. If your domain defines a payload type which is trivially copyable or move relocating[^1], it gains an implicit convertibility to a move-only `experimental::status_code<erased<T>>` where `T` is another trivially copyable or move relocating type. This permits global headers to use a single, common, type erased, status code type which is highly desirable for code bases of any complexity. However, unlike `std::error_code`, which fulfils the exact same role in `<system_error>` based code, the type erased payload can be bigger than the hardcoded `int` in `std::error_code`. This facility is also extremely useful, as extra failure metadata can be type erased, transported through code with no knowledge of such things, and the original type with failure metadata resurrected at the handling point. Indeed P1095 proposed `std::error` is a type alias to `experimental::status_code<erased<intptr_t>>`, and it can transport erased `std::exception_ptr` instances, POSIX error codes, and much more besides. 4. Equality comparisons between status code's with non-identical domains are always <b><em>semantic</em></b> i.e. are they semantically equivalent, rather than exactly equal? This mirrors when you compare `std::error_code` to a `std::error_condition`, but as there is no equivalent for the latter in `<system_error2>`, this means that when you see the code: ```c++ if(code1 == code2) ... ``` ... you can be highly confident that this is an inexact, semantic, match operation. The same code under `<system_error>` is highly ambiguous as to whether exact or inexact comparison is being performed (after all, all there is is "`code1 == code2`", so it depends on the types of `code1` and `code2` which usually is not obvious). The ambiguity, and high cognitive load during auditing `<system_error>` code for correctness, has led to many surprising and unexpected failure handling bugs during the past decade in production C++. 5. `<system_error2>`, being a new design, has all-constexpr construction and destruction which avoids the need for static global variables, as `<system_error>` has. Each of those static global variables requires an atomic fence just in case it has not been initialised, thus every retrieval of an error category bloats code and inhibits optimisation, plus makes the use of custom error code categories in header-only libraries unreliable. Boost.System has replicated the all-constexpr construction and destruction from `<system_error2>`, and thus now has similar characteristics in this regard. 6. Finally, this is a small but important difference. Under `<system_error>`, this extremely common use case is ambiguous: ```c++ if(ec) ... ``` Does this code mean "if there was an error?", or "if the error code is set?", or "is the error code non-zero?". The correct answer according to the standard is the last choice, but a quick survey of open source `<system_error>` based code on github quickly demonstrates there is widespread confusion regarding correct usage. `<system_error2>` solves this by removing the boolean test entirely. One now writes `if(sc.success()) ...`, `if(sc.failure()) ...`, `if(sc.empty()) ...` and so on, thus eliminating ambiguity. [^1]: [Move relocating is not in the standard, it is currently within WG21 Evolution Working Group Incubator](http://wg21.link/P1029). It is defined to be a type whose move constructor `memcpy()`'s the bits from source to destination, followed by `memcpy()` of the bits of a default constructed instance to source, and with a programmer-given guarantee that the destructor, when called on a default constructed instance, has no observable side effects. A surprising number of standard library types can meet this definition of move relocating, including `std::vector<T>`, `std::shared_ptr<T>`, and `std::exception_ptr`.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/c-api/_index.md
+++ title = "Using Outcome from C code" description = "Interacting with `result` returning C++ functions from C code." weight = 90 +++ A long standing problem for C code (or more usually nowadays, the many other programming languages which can speak the C ABI but not the C++ ABI) is how to interpret C++ exception throws. The answer is of course that they cannot, thus requiring one to write C shim code on the C++ side of things of the form: ```c++ // The API we wish to expose to C const char *get_value(double v); // The C shim function for the C++ get_value() function. extern "C" int c_get_value(const char **ret, double v) { try { *ret = get_value(v); return 0; // success } catch(const std::range_error &) { return ERANGE; } // More catch clauses may go in here ... catch(...) { return EAGAIN; } } ``` This is sufficiently painful that most reach for a bindings generator tool like [SWIG](http://www.swig.org/) to automate this sort of tedious boilerplate generation. And this is fine for larger projects, but for smaller projects the cost of setting up and configuring SWIG is also non-trivial. What would be really great is if `result<T>` returning `noexcept` C++ functions could be used straight from C. And indeed Experimental Outcome provides just that facility which this section covers next.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-cxx/example.md
+++ title = "Example C++ function" description = "" weight = 20 +++ Let us start with a simple C++ function which we wish to make available to C code: {{% snippet "cpp_api.cpp" "function" %}} As the alias `status_result<size_t>` defaults the erased type to the alias `system_code`, the `to_string()` function returns (in concrete types) `basic_result<size_t, status_code<erased<intptr_t>>>`. The standard Outcome function referenced is documented at {{% api "std::error_code error_from_exception(std::exception_ptr &&ep = std::current_exception(), std::error_code not_matched = std::make_error_code(std::errc::resource_unavailable_try_again)) noexcept" %}}. The proposed `<system_error2>` reference library implementation provides an identically named function taking similar parameters, but it returns a `outcome_e::system_code` (`status_code<erased<intptr_t>>`) instead of a `std::error_code`.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-cxx/_index.md
+++ title = "Calling C++ from C" description = "" weight = 20 +++ C++ has excellent two-way compatibility with the C ABI, but there are some limitations you must observe to write C++ code which C code can call without marshalling at the ABI boundary: 1. A C++ function may not throw exceptions if it is safe to call from C, and so should always be marked `noexcept`. 2. A C++ function should be annotated with `extern "C"` to prevent its symbol being mangled, and thus give it the C rather than C++ ABI. 3. You cannot use overloading in your `extern "C"` functions. 4. You may only use types in your C++ function declaration for which these traits are both true: - [`std::is_standard_layout_v<T>`](http://en.cppreference.com/w/cpp/types/is_standard_layout) - [`std::is_trivially_copyable_v<T>`](http://en.cppreference.com/w/cpp/types/is_trivially_copyable) (Note that `std::is_trivially_copyable_v<T>` requires trivial destruction, but NOT trivial construction. This means that C++ can do non-trivial construction of otherwise trivial types) --- The above is what the standard officially requires for *well defined* C and C++ interop. However, all of the three major compilers MSVC, GCC and clang are considerably more relaxed. In those three major compilers, "almost-standard-layout" C++ types work fine in C. "Almost-standard-layout" C++ types have these requirements: 1. No virtual functions or virtual base classes i.e. [`std::is_polymorphic_v<T>`](http://en.cppreference.com/w/cpp/types/is_polymorphic) must be false. This is because the vptrs offset the proper front of the data layout in an unknowable way to C. 2. Non-static data members of reference type appear to C as pointers. You must never supply from C to C++ a non-null pointer which is seen as a reference in C++. 3. C++ inheritance is seen in C data layout as if the most derived class has nested variables of the inherited types at the top, in order of inheritance. 4. Types with non-trivial destructors work fine so long as at least move construction and assignment is the same as copying bits like `memcpy()`. You just need to make sure instances of the type return to C++, and don't get orphaned in C. This was referred to in previous pages in this section as "move relocating" types. Experimental Outcome's support for being used from C does not meet the current strict requirements, and thus relies on the (very common) implementation defined behaviour just described (it is hoped that future C++ standards can relax the requirements to those just described). Specifically, proposed `status_code` is an almost-standard-layout type, and thus while it can't be returned from `extern "C"` functions as the compiler will complain, it is perfectly safe to return from C++ functions to C code on the three major compilers, as it is an "almost-standard-layout" C++ type if `T` is an "almost-standard-layout" C++ type.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-cxx/example2.md
+++ title = "Calling it from C" description = "" weight = 30 +++ Firstly we need to declare to C our `result` returning C++ function: {{% snippet "c_api.c" "preamble" %}} Now let's call the C++ function from C: {{% snippet "c_api.c" "example" %}} Running this C program yields: ``` to_string(9) fills buffer with '9' of 1 characters to_string(99) fills buffer with '99' of 2 characters to_string(999) fills buffer with '999' of 3 characters to_string(9999) failed with error code 105 (No buffer space available) ```
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-c/_index.md
+++ title = "C Results" description = "Outcome's C Result support" weight = 30 +++ The C macro API header `<outcome/experimental/result.h>` has some macros for working with any kind of Result: <dl> <dt><code>CXX_DECLARE_RESULT(ident, T, E)</code> <dd>Declares to C a <code>basic_result<T, E></code> type uniquely identified by <code>ident</code>. <code>T</code> is available at the member variable <code>.value</code>, and <code>E</code> is available at the member variable <code>.error</code>. If you call this from within C++, make SURE it is not within a <code>extern "C"</code> block! <dt><code>CXX_RESULT(ident)</code> <dd>A reference to a previously declared <code>result</code> type with unique <code>ident</code>. <dt><code>CXX_RESULT_HAS_VALUE(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code> has a value. <dt><code>CXX_RESULT_HAS_ERROR(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code> has an error. <dt><code>CXX_RESULT_ERROR_IS_ERRNO(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code>'s error value is a code in the POSIX <code>errno</code> domain. </dl> The above let you work, somewhat awkwardly, with any C-compatible `basic_result<T, E>`. `basic_result<T, E>` is trivially copyable and standard layout if its `T` and `E` are both so, and it has the C layout: ```c++ struct cxx_result_##ident { union { T value; E error; }; unsigned flags; }; ``` Note that this layout is different to that of [`CXX_DECLARE_STATUS_CODE`]({{% relref "../from-c" %}}) as the C++ `result` has a different layout if `E` is a status code.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-c/system_code.md
+++ title = "C system error results" description = "Status code's `std::error` in C" weight = 10 +++ In v2.2.11, C Result support went from second tier to first tier status, and now you can create, query and manipulate a subset of Result types entirely from within C by including `<outcome/experimental/result.h>`. The subset supported are those `result<T, E>` which are [a `status_result<T>`]({{% relref "../../status_result" %}}) i.e. the `E` is hardcoded to `experimental::error` which is the type erased runtime polymorphic holder for any errored `status_code` whose payload is not bigger than an `intptr_t`. This is the most useful subset of Outcome Experimental's possible Result types, allowing arbitrary custom error coding schemes from any unknown source to work seamlessly with all others, including errors from the system or third party libraries. The operations available to C are: <dl> <dt><code>CXX_DECLARE_RESULT_SYSTEM(ident, T)</code> <dd>Declares to C a <code>status_result<T></code> type uniquely identified by <code>ident</code>. <code>T</code> is available at the member variable <code>.value</code>, and <code>struct cxx_status_code_system</code> is available at the member variable <code>.error</code>. If in C++, implements C extern functions for making successful and failure results of this type. If you call this from within C++, make SURE it is not within a <code>extern "C"</code> block! <dt><code>CXX_RESULT_SYSTEM(ident)</code> <dd>A reference to a previously declared <code>status_result</code> type with unique <code>ident</code>. <dt><code>CXX_MAKE_RESULT_SYSTEM_SUCCESS(ident, expr)</code> (needs C++ counterpart linked into final binary) <dd>This invokes the aforementioned extern function which creates a <code>status_result</code> with a successful value of type <code>T</code>. <dt><code>CXX_MAKE_RESULT_SYSTEM_FAILURE_POSIX(ident, expr)</code> (needs C++ counterpart linked into final binary) <dd>This invokes the aforementioned extern function which creates a <code>status_result</code> with a failure of type <code>posix_code</code> representing a POSIX <code>errno</code>. <dt><code>CXX_MAKE_RESULT_SYSTEM_FAILURE_SYSTEM(ident, expr)</code> (needs C++ counterpart linked into final binary) <dd>This invokes the aforementioned extern function which creates a <code>status_result</code> with a failure of type <code>posix_code</code> representing a POSIX <code>errno</code> if on POSIX; if on Windows then a failure of type <code>win32_code</code> representing a Win32 error code from a Windows API. <br><br> <dt><code>CXX_RESULT_HAS_VALUE(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code> has a value. <dt><code>CXX_RESULT_HAS_ERROR(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code> has an error. <dt><code>CXX_RESULT_ERROR_IS_ERRNO(r)</code> <dd>Evaluates to 1 (true) if the input <code>result</code>'s error value is a code in the POSIX <code>errno</code> domain. <br><br> <dt><code>CXX_RESULT_SYSTEM_TRY(expr)</code> <dd>If the <code>status_result</code> returned by <code>expr</code> is errored, exit the current function returning the result. This obviously requires that the return type of the current function matches that of <code> expr</code>. <dt><code>CXX_RESULT_SYSTEM_TRY(cleanup, expr)</code> <dd>Same as the above, but execute <code>cleanup</code> just before exiting the function if returning failure. <dt><code>CXX_RESULT_SYSTEM_TRY(var, cleanup, expr)</code> <dd>Same as the above, but set <code>var</code> equal to the result's <code>.value</code> on success. <dt><code>CXX_RESULT_SYSTEM_TRY(var, ident, cleanup, expr)</code> <dd>Same as the above, but use <code>ident</code> as the return type instead. This allows the return type of the calling function to differ from that of <code>expr</code>. <br><br> <dt><code>CXX_DECLARE_RESULT_SYSTEM_FROM_ENUM(ident, enum_name, uuid, {enum mapping-sequence, ...})</code> <dd>This declares to C an extern function which creates a <code>status_result</code> from a C enum. If in C++, it implements a <code>quick_status_code_from_enum</code> for the C enum and the associated extern function, and you will need to supply <code>uuid</code> and the appropriate enum value mapping sequence <a href="{{% relref "../../worked-example" %}}"> as per the <code>quick_status_code_from_enum</code> documentation</a>. <dt><code>CXX_MAKE_RESULT_SYSTEM_FROM_ENUM(ident, enum_name, expr)</code> (needs C++ counterpart linked into final binary) <dd>This invokes the aforementioned extern function which creates a <code>status_result</code> from a C enum. </dl> The operations available to C++ are: <dl> <dt><code>CXX_TO_RESULT_SYSTEM_CODE(ident, status_code&lt;T&gt;)</code> <dd>Returns a previously declared C Result from its matching C++ <code>status_code</code>. NOTE that the destructor of the C++ status code is NOT called. If this is important to your status code, it is 100% on you to ensure that your C Result reenters a C++ Result at the end of its lifetime. <dt><code>to_result(any C Result)</code> <dd>This is an overloaded C++ free function which returns the C++ status_code&lt;T&gt; matching its input C Result. </dl> Using the above you can write C code using Outcome.Experimental's Result type quite effectively. Let's look at an example of use next.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-c/declare.md
+++ title = "Declare a Result" description = "Declaring a C Result" weight = 20 +++ {{% snippet "c_api2.cpp" "preamble" %}} The key to making C programming easy is to alias the long complex things into short easy thing. Obviously `SUCCESS(expr)` and `FAILURE(expr)` is too generic, but for the purposes of this documentation it makes thing easier.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-c/use.md
+++ title = "Using a Result" description = "Using a C Result" weight = 30 +++ This models [the earlier C++ example of use]({{% relref "/experimental/worked-example/implicit-construction" %}}), and its C equivalent isn't much more verbose thanks to our helper typedefs and macros: {{% snippet "c_api2.cpp" "using" %}} For this to link, the `CXX_DECLARE_RESULT_SYSTEM_FROM_ENUM` macro needs to be compiled at least once within C++ within the final binary to emit the extern functions needed by C.
0
repos/outcome/doc/src/content/experimental/c-api
repos/outcome/doc/src/content/experimental/c-api/from-c/try.md
+++ title = "TRY a C Result" description = "Operation TRY on a C Result" weight = 40 +++ Thanks to much of the magic of {{< api "OUTCOME_TRY(var, expr)" >}} being implemented using C preprocessor metaprogramming, we can offer a very similar experience for the C try operation and without needing anything compiled in C++ as support functions: {{% snippet "c_api2.cpp" "try" %}} The principle difference is that you can specify a cleanup routine to perform if failure is encountered. This is especially useful in C, which has no stack unwinding. Also due to lack of type sugaring and user defined implicit conversions, if your callers result type isn't your callee's, you may need to specify what your caller's result type is so the error state can be correctly propagated.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/string_ref.md
+++ title = "String refs" weight = 40 +++ `<system_error2>` does not use `std::string` to return possibly statically or dynamically allocated strings, and thus avoids dragging in a lot of the standard library which impacts build times. Instead status code domains have a [`string_ref`](https://ned14.github.io/status-code/doc_status_code_domain.html#standardese-system_error2__status_code_domain__string_ref), which has a polymorphic implementation which may or may not [manage a dynamic memory allocation using an atomic reference counter](https://ned14.github.io/status-code/doc_status_code_domain.html#standardese-system_error2__status_code_domain__atomic_refcounted_string_ref). Due to this polymorphism, you don't need to worry which implementation is actually in use under the bonnet when you pass around `string_ref` instances. `string_ref` provides the same member functions as a `span<const char>`, and so participates ordinarily in STL algorithms and containers. In particular, if you need to string search or slice it, you can construct a `string_view` on top easily. {{% snippet "experimental_status_code.cpp" "string_ref" %}} Now you understand what `string_ref` does, returning the name of the status code domain is self describing. Note we use the non-managing constructor of `string_ref`, as the string `"file i/o error domain"` is statically stored. We cache the returned value locally in static storage.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/_index.md
+++ title = "Worked example: Custom domain (the long way)" weight = 85 +++ Here follows a longer worked example of use of Experimental Outcome. It presents the same sample program I sent to the San Diego 2018 WG21 standards meeting after I was asked by the committee to demonstrate how P1095 implements P0709 in a working code example they could study and discuss. We will walk through this worked example, step by step, explaining how each part works in detail. This will help you implement your own code based on Experimental Outcome. Most users will not need this level of customisation, and for them the preceding [quick and easy approach]({{% relref "../worked-example" %}}) will be much easier. You may find it useful to open now in a separate browser tab the reference API documentation for proposed `<system_error2>` at https://ned14.github.io/status-code/ (scroll half way down). The references in the comments to P1028 are to [P1028 *SG14 status_code and standard error object for P0709 Zero-overhead deterministic exceptions*](http://wg21.link/P1028), which is the WG21 proposal paper for potential `<system_error2>`. ### Goal of this section We are going to define a simple custom code domain which defines that the status code's payload will consist of a POSIX error code, and the `__FILE__` and `__LINE__` where the failure occurred. This custom status code will have an implicit conversion to type erased `error` defined, which dynamically allocates memory for the original status code, and outputs an `error` which manages that dynamic allocation, indirecting all queries etc to the erased custom status code type such that the `error` instance quacks as if just like the original. This demonstrates that `error` could just as equally convey a `std::exception_ptr`, for example, or indeed manage the lifetime of any pointer.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/message.md
+++ title = "Redefining `message()`" weight = 50 +++ You may remember that our custom `_file_io_error_domain` inherits from `outcome_e::posix_code::domain_type`, and thus does not have to implement the many pure virtual functions required by `outcome_e::status_code_domain`. What we do need to do is reimplement `_do_message()` to append the file and line information to the POSIX error description string returned by `outcome_e::posix_code::domain_type`. This causes the status code's `.message()` observer to return a string with the extra payload information represented in text. {{% snippet "experimental_status_code.cpp" "message" %}}
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/implicit_conversion.md
+++ title = "Implicit conversion" weight = 70 +++ Back in [The payload]({{< relref "value_type" >}}), we mentioned that there was no default implicit conversion of `file_io_error` (`status_code<_file_io_error_domain>`) to `error`, as `error` is too small to hold `_file_io_error_domain::value_type`. We can tell the framework about available implicit conversions by defining an ADL discovered free function `make_status_code()` which takes our custom status code as input, and returns an `error`: {{% snippet "experimental_status_code.cpp" "implicit_conversion" %}} We are now ready to use Experimental Outcome!
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/value_type.md
+++ title = "The payload" weight = 20 +++ We define the code domain's `value_type` -- the payload to be transported by status codes using this code domain -- to be a POSIX `errno` value, an integer line number and a const char pointer. {{% snippet "experimental_status_code.cpp" "value_type" %}} You will note that this is a `TriviallyCopyable` type, and so gains an implicit conversion to any `status_code<erased<T>>` where `sizeof(T) >= sizeof(value_type)`. `error` is however `status_code<erased<intptr_t>>`, and `sizeof(intptr_t) < sizeof(value_type)`, so it is not possible to implicitly convert status codes from this domain into `error`. Instead, you must tell the compiler how to do the conversion, as we shall see later.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/preamble.md
+++ title = "Define a custom code domain" weight = 10 +++ Firstly let's alias the experimental Outcome namespace into something less tedious to type, declare our custom status code type, and get started on defining the custom status code domain implementation. {{% snippet "experimental_status_code.cpp" "preamble" %}} Note that we inherit from `outcome_e::posix_code::domain_type`, not from `outcome_e::status_code_domain`. We thus reuse most of the implementation of `outcome_e::posix_code::domain_type` rather than implementing required functionality. If you would like to see a fuller treatment of defining a custom status code domain from scratch, see [this worked example here](https://github.com/ned14/status-code/blob/master/doc/custom_domain_worked_example.md). [You may find looking at the API reference documentation for `status_code_domain` useful in the next few pages ](https://ned14.github.io/status-code/doc_status_code_domain.html#standardese-system_error2__status_code_domain).
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/source.md
+++ title = "Constexpr domain source" weight = 60 +++ Back in [The constructor]({{< relref "constructor" >}}), we declared but did not implement a `.get()` function which returns a constexpr static instance of the domain. We implement this now: {{% snippet "experimental_status_code.cpp" "constexpr_source" %}} As this is 100% constexpr, it can be (and is under optimisation) implemented entirely in the mind of the compiler with no run time representation.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example-long/constructor.md
+++ title = "The constructor" weight = 30 +++ Code domains are 100% constexpr to construct and destruct, as are status codes. This enables the compiler to 100% instantiate both only in its mind, and to emit zero code and thus zero overhead. Unfortunately it also means that it must be possible for each domain to be instantiated an infinite number of times, and being 100% in constexpr, any instances never have a unique address in memory either. Thus we cannot compare domains for equivalence using their address in memory, as {{% api "std::error_category" %}} does. We solve this by using a *very* random 64 bit number taken from a hard random number source. The website https://www.random.org/cgi-bin/randbyte?nbytes=8&format=h is strongly suggested as the source for this number. (In case you are wondering about the chance of collision for a 64 bit integer, SG14 estimated that approximately 190,000 separate domains would need to exist in a single process for there to be a 0.00000001% probability of collision if the random number source is very random) {{% snippet "experimental_status_code.cpp" "constructor" %}} A nice side effect of this approach is that custom error domains in header-only libraries are safe, unlike custom `<system_error>` error categories. Boost.System's error categories can now opt into this same safe mechanism in order to also be safe in header only library use cases.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example/_index.md
+++ title = "Worked example: Custom domain (the short way)" weight = 80 +++ The section after this one will take the long way through defining a custom domain which sometimes is necessary if you have particularly bespoke requirements. If however you just want to wrap a custom `enum` type of yours into its own custom code domain, the boilerplate can be automated away by filling in a few simple fields like this: {{% snippet "quick_status_code_from_enum.cpp" "preamble" %}} Here we supply the bare minimum requirements for a status code domain: 1. The name in text, so it can be printed. 2. The unique UUID to identify when multiple copies of the domain are the same. PLEASE use https://www.random.org/cgi-bin/randbyte?nbytes=16&format=h to generate this, do not twiddle a few bits. 3. For each enum value, its printable text and a sequence of `errc::` enumerations which you think it is semantically equivalent to i.e. its mapping onto `generic_code` which is how status code defines the common mapping between status codes. If you later compare the status code to one of those values (or to another status code which also provides a mapping), if the generic codes are equivalent then the comparison will return true. This means code like `if(sc == errc::no_such_file_or_directory) ...` would match all custom error codes which mean 'something was not found'. 4. OPTIONAL: if you would like the custom status code type generated by this to have additional member functions or additional payload, you can define a mixin here to inject either data or functions or both. If you omit this, nothing gets injected.
0
repos/outcome/doc/src/content/experimental
repos/outcome/doc/src/content/experimental/worked-example/implicit-construction.md
+++ title = "Implicit construction" weight = 10 +++ The preceding code had the compiler stamp out a custom status code domain for a user supplied `enum`. You now get the following types: {{% snippet "quick_status_code_from_enum.cpp" "implicit_construction" %}} As you can see, this is less work than [plugging your custom enum into `std::error_code`]({{% relref "/motivation/plug_error_code" %}}). It also has C compatibility, and generates better codegen.
0
repos/outcome/doc/src/content
repos/outcome/doc/src/content/tutorial/_index.md
+++ title = "Tutorial" weight = 10 +++ {{% children description="true" depth="2" %}}
0
repos/outcome/doc/src/content/tutorial
repos/outcome/doc/src/content/tutorial/advanced/_index.md
+++ title = "Advanced" description = "If you have a bit more time, this covers all the time-saving ways you can customise and automate Outcome for various use cases, especially in larger codebases made up of multiple third party libraries." weight = 20 +++ {{% children description="true" depth="2" %}}
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/conclusion.md
+++ title = "Conclusion" weight = 55 +++ This worked example was in fact excessively complex: a quicker route to achieving the same thing would be to add explicit converting constructors to `app::error_code` for each of the third party library `E` types. One then could have saved oneself with having to bother injecting custom converters into the `OUTCOME_V2_NAMESPACE::convert` namespace. If you control your application's `E` type, then that is probably a better, and certainly simpler, approach. However there are occasions when you don't have control over the implementation of the destination `E` type e.g. in callbacks. Outcome's `value_or_error` infrastructure lets you inject custom interop code for any pair of incommensurate third party `E` types, without needing to modify either's source code. This is without doubt a "power users" feature, but one which will prove useful as `T|E` based C++ code proliferates.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/value-or-error.md
+++ title = "value_or_error Concept" weight = 7 tags = [ "value-or-error" ] +++ Something not really mentioned until now is how Outcome interoperates with the proposed {{% api "std::expected<T, E>" %}}, whose design lands in between {{% api "unchecked<T, E = varies>" %}} and {{% api "checked<T, E = varies>" %}} (both of which are type aliases hard coding no-value policies [as previously covered in this tutorial]({{< relref "/tutorial/essential/no-value/builtin" >}})). Expected and Outcome are [isomorphic to one another in design intent]({{< relref "/faq" >}}#why-doesn-t-outcome-duplicate-std-expected-t-e-s-design), but interoperation for code using Expected and Outcome ought to be seamless thanks to the [proposed `ValueOrError` concept framework](https://wg21.link/P0786), a subset of which Outcome implements. The {{% api "explicit basic_result(concepts::value_or_error<T, E> &&)" %}} and {{% api "explicit basic_outcome(concepts::value_or_error<T, E> &&)" %}} constructors will explicitly construct from any type matching the {{% api "concepts::value_or_error<T, E>" %}} concept, which includes `std::expected<A, B>`, if `A` is constructible to `X`, and `B` is constructible to `Y`. The `value_or_error` concept in turn is true if and only if the input type has: 1. A `.has_value()` observer returning a `bool`. 2. `.value()` and `.error()` observers. ## Implementation Outcome's machinery for implementing `concepts::value_or_error` conversion is user extensible by injection of specialisations of the {{% api "value_or_error<T, U>" %}} type into the `OUTCOME_V2_NAMESPACE::convert` namespace. Outcome's default `convert::value_or_error<T, U>` implementation explicitly excludes Outcome `result` and `outcome` types from the default mechanism as there is a major gotcha: the `value_or_error` matched type's `.value()` is often not callable in constexpr as it can throw, which makes this conversion mechanism pretty much useless for constexpr code. Besides, `outcome` has a converting constructor overload for `result` inputs which is constexpr capable. Note that if you do enable `outcome` inputs, a `result` will match an input `outcome`, but silently dropping any exception state. This is probably undesirable. Examples of how to implement your own `convert::value_or_error<T, U>` converter is demonstrated in the worked example, next.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/_index.md
+++ title = "Interoperation" description = "Interoperating with std::expected<T, E> and other ValueOrError concept matching types." weight = 80 +++ This is the final section of the tutorial, and it is unavoidably quite lengthy as we are going to tie together all of the material covered in the tutorial so far into a single, unified, application of Outcome's facilities. One thing which Outcome solves -- and which alternatives do not -- is how to **non-intrusively** tie together multiple third party libraries, each using Outcome -- or some other `T|E` implementatation like {{% api "std::expected<T, E>" %}} -- with custom incommensurate `E` types, or indeed arbitrary return types which are "split" `T|E` return types. Solving this well is the *coup de grâce* of Outcome against alternative approaches to this problem domain, including `std::expected<T, E>`. It is the major reason why you should consider using Outcome over alternatives, including Expected. Firstly we shall explore some of the problems faced by the software developer when `T|E` return type based code proliferates at scale, where dozens of libraries may be using completely incompatible `T|E` return types. Secondly we shall introduce the `ValueOrError` concept support in Outcome, which implements a subset of the proposed [WG21 `ValueOrError` concept framework](https://wg21.link/P0786). Finally, we shall then step through a worked example which mocks up a realistic situation that the software developer may find themselves in: tying together disparate third party libraries, whose source code cannot be modified, into an application-wide, mixed-mode `T|E` and exception throwing universal error handling system which is capable of accurately representing the original failure, but also propagating it in a way that the application can deal with universally.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/tidylib.md
+++ title = "The HTMLTidy library" weight = 15 +++ {{% snippet "finale.cpp" "tidylib" %}} A C API may not initially appear to be a `T|E` based API, but if failure returns some domained error code and causes no other effects, and success returns some value, then it is effectively a "split" `T|E` API. The above is an example of exactly that form of "split" `T|E` API.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app-map-httplib2.md
+++ title = "Mapping the HTTP library into the Application `2/2`" weight = 35 +++ If you remember the tutorial section on the [`value_or_error` Concept](../value-or-error), this is an example of how to implement a custom `value_or_error` Concept converter in Outcome: {{% snippet "finale.cpp" "app_map_httplib2" %}} The first thing that you should note is that these custom converters must be injected directly into the `OUTCOME_V2_NAMESPACE::convert` namespace, and they must partially or completely specialise {{% api "value_or_error<T, U>" %}}. Here we specialise the converter for `value_or_error` conversions from `httplib::result<U>` to `app::outcome<T>` i.e. from our third party HTTP library's error type into our application's `outcome` type (which is unique to our application, as we hard code an `app`-local error type). The second thing to note is that you need to set `enable_result_inputs` and `enable_outcome_inputs` appropriately, otherwise `result` and `outcome` inputs will not be matched by this converter[^1]. In this converter, we really do wish to convert other `result` and `outcome` inputs, so we mark these booleans as `true`. The third thing to note is the requirements on `operator()`. If the requirements are not met, the `value_or_error` converting constructor in `basic_result` and `basic_outcome` disables. Note the requirement that the decayed `operator()` input `X` matches `httplib::result<U>`, and that `T` is constructible from `U`. This means that the {{% api "explicit basic_result(concepts::value_or_error<T, E> &&)" %}} and {{% api "explicit basic_outcome(concepts::value_or_error<T, E> &&)" %}} constructors are available if, and only if, the input type is a `httplib::result<U>`, and the result's value type is constructible from the input's value type. If `operator()` is available, it naturally converts a `httplib::result<U>` into an `app::outcome<T>` by either forwarding any success as-is, or calling `app::make_httplib_exception()` to type erase the `httplib::failure` into an `app::httplib_error`. [^1]: Here we refer to `result` and `outcome` as defined by this specific Outcome library. If `result` or `outcome` from another Outcome implementation is seen, those **always** must get parsed via the `ValueOrError` matching conversion framework.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/filelib.md
+++ title = "The File I/O library" weight = 20 +++ The File I/O library we shall be using is very similar [to the one we saw earlier in this tutorial](../../payload/copy_file2): {{% snippet "finale.cpp" "filelib" %}} This uses the advanced Outcome feature of programming the lazy synthesis of custom C++ exception throws from a payload carrying `E` type called `failure_info`. Like the HTTP library, it too template aliases a localised `result` implementation into its namespace with ADL bridging so Outcome customisation points can be discovered.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app-map-filelib.md
+++ title = "Mapping the File I/O library into the Application" weight = 40 +++ To handle the File I/O library, once again we turn to custom `ValueOrError` converters: {{% snippet "finale.cpp" "app_map_filelib" %}} Note that the conversion exactly duplicates the implementation of `throw_as_system_error_with_payload(failure_info fi)` from namespace `filelib`. In a production implementation, you probably ought to call that function and catch the exception it throws into a pointer, as that would be more long term maintainable.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app-go.md
+++ title = "In use" weight = 50 +++ This is how you might now write application code using these three libraries: {{% snippet "finale.cpp" "app_go" %}} The curiosity will be surely the `ext()` markup function, which needs explaining. It was felt important during Outcome's design that `value_or_error` conversions never be implicit, as they almost always represent a transition across an ABI or semantic boundary. They are also usually non-trivial to implement and compile, and it was felt important that the programmer ought to always mark the semantic boundary transition at the point of every use, as considerable amounts of code may execute. How the end user chooses to mark up their code is up to them, however above we use a simple `ext()` function to mark up that the function being called is *external* to the application. This ticks our box of requiring the documentation, at the point of use, of every transition in failure handling boundaries. Note that we are able to use `TRY` as normal throughout this function. Everything "just works". And most especially note that we never, **at any stage**, needed to modify the source code of `httplib`, `tidylib` nor `filelib`, nor inject custom things into their namespaces. This entire worked example was achieved solely by `app` based customisation points, and via `convert`.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app.md
+++ title = "The Application" weight = 25 +++ The application is of course also based on Outcome, and like the HTTP library is also of mixed-failure design in that failure can be returned via error code, type erased `exception_ptr` or indeed a C++ exception throw. {{% snippet "finale.cpp" "app" %}} Here we localise a passthrough `error_code` solely for the purpose of ADL bridging, otherwise the localised `outcome` configured is the default one which comes with Outcome. [We covered this technique of "passthrough `error_code`" earlier in this tutorial]({{< relref "/tutorial/advanced/hooks/adl_bridging" >}}). The way we are going to configure interop is as follows: 1. The application shall use `error_code` for anticipated failure and C++ exception throws for unanticipated failure. 2. We shall choose the convention that `app::outcome` with exception ptr solely and exclusively represents a type erased failure from a third party library. Thus if one calls `.value()` on an `app::outcome`, both anticipated failure within the app and type erased failure from a third party library shall be converted to a C++ exception throw.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/httplib.md
+++ title = "The HTTP library" weight = 10 +++ Let us imagine a simple application: it fetches a HTTP page using a HTTP library, sends it through HTML tidy via the htmltidy library, and then writes it to disc using a filelib library. So three third party libraries, two using Outcome in incompatible ways, and the third being a C library just for kicks. Let us imagine that the HTTP library has the following public interface: {{% snippet "finale.cpp" "httplib" %}} The HTTP library is a mixed-failure design. Likely failures (HTTP status codes) are returned via `httplib::failure`, unlikely failures (e.g. out of memory) are returned via throw of the usual STL exception types. The sole API we bother describing is an implementation of HTTP GET. It fetches a URL, and either returns the contents or the failure reason why not.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app-map-httplib1.md
+++ title = "Mapping the HTTP library into the Application `1/2`" weight = 30 +++ Firstly, remember that we are the application writer who has the problem of integrating three third party libraries into our application's Outcome-based failure handling mechanism. We cannot modify those third party library sources; we must be *non-intrusive*. We start by dealing with the HTTP library. We will integrate this into our application by wrapping up `httplib::failure` into a custom STL exception type. We then type erase it into an `exception_ptr` instance. Please note that this code is exclusively defined in the `app` namespace: {{% snippet "finale.cpp" "app_map_httplib1" %}} Most of the complexity in this code fragment is driven by the need to create some sort of descriptive string for `std::runtime_error` so its `.what()` returns a useful summary of the original failure. This is the main purpose of the `app::make_httplib_exception()` function. (Note that if you have Reflection in your C++ compiler, it may be possible to script the conversion of enum values to string representations) The only real thing to note about `app::httplib_error` is that it squirrels away the original `httplib::failure` in case that is ever needed.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/problem.md
+++ title = "Incommensurate E types" weight = 5 +++ Back in the essential tutorial section on `result`, we studied a likely very common initial choice of `E` type: [a strongly typed enum]({{< relref "/tutorial/essential/result" >}}). We saw how [by marking up strongly typed enums to tell the C++ standard library what they are]({{< relref "/motivation/plug_error_code" >}}), they gain implicit convertibility into `std::error_code`, and we then pointed out that you might as well now always set `E = std::error_code`, as that comes with the enormous advantage that you can use the boilerplate saving `OUTCOME_TRY` macro when the `E` type is always the same. We thus strongly recommend to users that for any given piece of code, always using the same `E` type across the codebase is very wise, except where you explicitly want to prevent implicit propagation of failure up a call stack e.g. local failures in some domain specific piece of code. However it is unreasonable to expect that any non-trivial codebase can make do with `E = std::error_code`. This is why Outcome allows you to use [custom `E` types which carry payload](../../payload) in addition to an error code, yet still have that custom type treated as if a `std::error_code`, including [lazy custom exception throw synthesis](../../payload/copy_file3). All this is good, but if library A uses `result<T, libraryA::failure_info>`, and library B uses `result<T, libraryB::error_info>` and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer. The application writer has one of three choices: 1. In the application, the form of result used is `result<T, std::variant<E1, E2, ...>>` where `E1`, `E2` ... are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail. 2. One can translate/map the third party's failure type into the application's failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one. 3. One can type erase the third party's failure type into some application failure type, which can later be reconstituted if necessary. This is the cleanest solution with the least coupling issues and no problems with mis-mapping, but it almost certainly requires the use of `malloc`, which the previous two did not. Things get even more complicated in the presence of callbacks. If in the callback you supply to library A, you call library B, you may need to insert switch statement maps or other mechanisms to convert library B's failures into something library A can understand, and then somehow extract that out -- preferably without loss of original information -- into the application's failure handling mechanism if library A subsequently returns failure as well. This implies transmitting state by which to track these interrelated pieces of failure data. Let us see what Outcome can do to help the application writer address some of these issues, next.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/interop/app-map-tidylib.md
+++ title = "Mapping the HTMLTidy library into the Application" weight = 45 +++ Once again, we create a custom STL exception type to represent failure from the HTMLTidy library. We also create an `app` namespace wrapper for the C `tidy_html()` function which is more C++ friendly. {{% snippet "finale.cpp" "app_map_tidylib" %}}
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/hook_result.md
+++ title = "Hook result" description = "" weight = 30 +++ We now tell Outcome that for every instance of our localised `result<T>`, that on failure construction only, we want custom code to be run which increments the current slot in TLS storage and writes the current stack backtrace into it. For Outcome before v2.2, we must do this by inserting a specially named free function into a namespace searched by ADL: {{% snippet "error_code_extended.cpp" "error_code_extended3" %}} For Outcome v2.2 and later, we must do this by using a custom no value policy which contains a function named `on_result_construction()`. The function implementation is identical between both mechanisms, just the name and placement of the function declaration differs. The only non-obvious part above is the call to {{< api "void set_spare_storage(basic_result|basic_outcome *, uint16_t) noexcept" >}}. Both `result` and `outcome` keep their internal state metadata in a `uint32_t`, half of which is not used by Outcome. As it can be very useful to keep a small unique number attached to any particular `result` or `outcome` instance, we permit user code to set those sixteen bits to anything they feel like. The corresponding function to retrieve those sixteen bits is {{< api "uint16_t spare_storage(const basic_result|basic_outcome *) noexcept" >}}. The state of the sixteen bits of spare storage are ignored during comparison operations. The sixteen bits of spare storage propagate during the following operations: 1. Copy and move construction between `result`'s. 2. Copy and move construction between `outcome`'s. 3. Copy and move construction from a `result` to an `outcome`. 4. Converting copy and move constructions for all the above. 5. Assignment for all of the above. They are NOT propagated in these operations: 1. Any conversion or translation which goes through a `failure_type` or `success_type`. 2. Any conversion or translation which goes through a `ValueOrError` concept match. 3. Any unpacking or repacking of value/error/exception e.g. a manual repack of an `outcome` into a `result`.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/_index.md
+++ title = "Hooking events" description = "Intercepting useful events such as initial construction, copies and moves so you can capture backtraces, fire debug breakpoints etc." weight = 50 tags = ["hooks"] +++ Outcome provides multiple methods for user code to intercept various lifecycle events which occur. The deepest method is simply to inherit from `basic_result` or `basic_outcome`, and override member functions, for which you will need to study the source code as that form of customisation is out of scope for this tutorial. Another option is to supply a custom `NoValuePolicy` ([see preceding section]({{< relref "/tutorial/essential/no-value/custom" >}})). From Outcome v2.2 onwards, intercepting construction, copies and moves *requires* a custom `NoValuePolicy`. Before Outcome v2.2, there was an ADL discovered event hook mechanism for intercepting construction, copies and moves (it was found to be brittle, error prone and surprising in empirical use, which is why it was replaced). The ADL discovered event hooks still function in Outcome v2.2 and later if {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to enable emulation. You will note that the naming is simply one of `hook_*` => `on_*`, the parameters remain identical. This eases porting code from Outcome v2.1 to v2.2, it's usually just a case of copy-pasting the ADL hook code into a custom `NoValuePolicy`. --- **Policy set event hooks (Outcome v2.2 onwards):** - Constructed - {{< api "void on_result_construction(T *, U &&) noexcept" >}} - {{< api "void on_outcome_construction(T *, U &&) noexcept" >}} - In-place constructed - {{< api "void on_result_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" >}} - {{< api "void on_outcome_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" >}} - Copied - {{< api "void on_result_copy_construction(T *, U &&) noexcept" >}} - {{< api "void on_outcome_copy_construction(T *, U &&) noexcept" >}} - Moved - {{< api "void on_result_move_construction(T *, U &&) noexcept" >}} - {{< api "void on_outcome_move_construction(T *, U &&) noexcept" >}} --- **ADL discovered event hooks (before Outcome v2.2):** - Constructed - {{< api "void hook_result_construction(T *, U &&) noexcept" >}} - {{< api "void hook_outcome_construction(T *, U &&) noexcept" >}} - In-place constructed - {{< api "void hook_result_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" >}} - {{< api "void hook_outcome_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" >}} - Copied - {{< api "void hook_result_copy_construction(T *, U &&) noexcept" >}} - {{< api "void hook_outcome_copy_construction(T *, U &&) noexcept" >}} - Moved - {{< api "void hook_result_move_construction(T *, U &&) noexcept" >}} - {{< api "void hook_outcome_move_construction(T *, U &&) noexcept" >}} --- One criticism often levelled against library-based exception throw alternatives is that they do not provide as rich a set of facilities as C++ exception throws. This section shows you how to configure Outcome, using the event hooks, to take a stack backtrace on construction of an errored `result<T, error_code>`, and if that `result<T, error_code>` should ever be converted into an `outcome<T, error_code, std::exception_ptr>`, a custom `std::exception_ptr` will be just-in-time synthesised consisting of the `std::system_error` for the error code, plus an expanded message string containing the stack backtrace of where the error originally occurred. One can see the use case for such a configuration where low-level, deterministic, fixed latency code is built with `result`, and it dovetails into higher-level application code built with `outcome` where execution time guarantees are not important, and thus where a `malloc` is okay. One effectively has constructed a "lazy indeterminism", or "just-in-time indeterminism" mechanism for handling failure, but with all the rich information of throwing C++ exceptions.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/keeping_state.md
+++ title = "Keeping state" description = "" weight = 10 tags = ["backtrace"] +++ The first thing we are going to need is somewhere to store the stack backtrace. We could take the easier route and simply store it into an allocated block and keep the pointer as a custom payload in a `result<T, std::pair<error_code, std::unique_ptr<stack_backtrace>>>` (see previous section on [Custom payloads](../../payload)). But let us assume that we care so deeply about bounded execution times that ever calling `malloc` is unacceptable. We therefore are going to need some completely static and trivially typed storage perhaps kept per-thread to avoid the need to keep mutexes. {{% snippet "error_code_extended.cpp" "error_code_extended1" %}} The extended error info is kept in a sixteen item long, thread local, ring buffer. We continuously increment the current index pointer which is a 16 bit value which will wrap after 65,535. This lets us detect an attempt to access recycled storage, and thus return item-not-found instead of the wrong extended error info.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/adl_bridging.md
+++ title = "ADL bridging" description = "" weight = 20 tags = [ "adl-bridging"] +++ {{% notice note %}} In Outcome v2.2 the ADL-based event hooks were replaced with policy-based event hooks (next page). The code in this section is still valid in v2.2 onwards, it's just that ADL is no longer used to find the hooks. {{% /notice %}} In a previous section, we used the `failure_info` type to create the ADL bridge into the namespace where the ADL discovered [`outcome_throw_as_system_error_with_payload()`]({{< relref "/reference/functions/policy" >}}) function was to be found. Here we do the same, but more directly by creating a thin clone of `std::error_code` into the local namespace. This ensures that this namespace will be searched by the compiler when discovering the event hooks (Outcome v2.1 and earlier only). {{% snippet "error_code_extended.cpp" "error_code_extended2" %}} For convenience, we template alias local copies of `result` and `outcome` in this namespace bound to the ADL bridging `error_code`.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/hook_outcome.md
+++ title = "Hook outcome" description = "" weight = 50 +++ The final step is to add event hooks for the very specific case of when our localised `outcome` is copy or move constructed from our localised `result`. You ought to be very careful that the `noexcept`-ness of these matches the `noexcept`-ness of the types in the `outcome`. You may have noticed that `poke_exception()` creates a `std::string` and appends to it. This can throw an exception. If the copy and/or move constructors of `T`, `EC` and `EP` are `noexcept`, then so will be `outcome`'s copy and/or move constructor. Thus if `poke_exception()` throws, instant program termination would occur, which is bad. We avoid that problem in this case by wrapping `poke_exception()` in a `try...catch` which throws away any exceptions thrown. For Outcome before v2.2, these specially named free functions must be placed into a namespace which is ADL searched: {{% snippet "error_code_extended.cpp" "error_code_extended5" %}} For Outcome v2.2 and later, these functions must be placed into a custom no value policy with the names `on_outcome_copy_construction()` and `on_outcome_move_construction()` respectively. As with before, the implementation of the functions is identical, just the name and location has changed.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/hooks/poke_exception.md
+++ title = "Custom exception ptr" description = "" weight = 40 +++ If you merely want `result` to capture stack backtraces without calling a memory allocator and retaining any triviality of copy which is important for optimisation, you already have everything you need. But let's keep going by intercepting any construction of our localised `outcome` from our localised `result`, retrieving any stored backtrace and using it to synthesise an exception ptr with a message text including the backtrace. Firstly let us look at the function which synthesises the exception ptr: {{% snippet "error_code_extended.cpp" "error_code_extended4" %}} If the localised `outcome` being constructed is errored, try fetching the TLS slot for the unique 16-bit value in its spare storage. If that is valid, symbolise the stack backtrace into a string and make an exception ptr with a runtime error with that string. Finally, override the payload/exception member in our just-copy-constructed localised `outcome` with the new exception ptr. <hr> As the reference documentation for {{% api "void override_outcome_exception(basic_outcome<T, EC, EP, NoValuePolicy> *, U &&) noexcept" %}} points out, you *almost certainly* never want to use this function if there is any other alternative. It is worth explaining what is meant by this. In this section, we *always* synthesise an exception ptr from the stored state and error code at the exact point of transition from `result` based APIs to `outcome` based APIs. This is acceptable only because we know that our code enforces that discipline. If one were designing a library facility, one could not assume such discipline in the library user. One would probably be better off making the exception ptr synthesis *lazy* via a custom no-value policy which generates the stacktrace-containing error message only on demand e.g. `.exception()` observation, or a `.value()` observation where no value is available. Such a design is however more indeterminate than the design presented in this section, because the indeterminacy is less predictable than in this design. Ultimately which strategy you adopt depends on how important absolute determinism is to your Outcome-based application.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/_index.md
+++ title = "Result returning constructors" description = "How to metaprogram construction of objects which use result<T, EC> to return failure instead of throwing a C++ exception." weight = 47 tags = ["constructors"] +++ An oft-asked question during conference talks on Expected/Outcome is how to exclusively use `result` to implement constructor failure. This is asked because whilst almost every member function in a class can return a `result`, constructors do not return values and thus cannot return a `result`. The implication is that one cannot avoid throwing C++ exceptions to abort a construction. As with most things in C++, one can achieve zero-exception-throw object construction using a lot of extra typing of boilerplate, and a little bit of simple C++ metaprogramming. This section shows you how to implement these for those who are absolutely adverse to ever throwing an exception, or cannot because C++ exceptions have been globally disabled. The technique described here is not suitable for non-copyable and non-movable types. There is also an assumption that moving your type is cheap.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/metaprogrammg3.md
+++ title = "Alternatives" description = "" weight = 60 +++ No doubt many will dislike the two-stage invocation pattern i.e. ```c++ make<file_handle>{"hello"}(); ``` So let us examine the most obvious alternative: a templated free function `make<T>`. Due to the inability to partially specialise templated functions in C++, you need to use tagged overloading e.g. ```c++ template<class... Args> inline outcome::result<file_handle> make(std::in_place_type_t<file_handle>, Args&& ... args) { return file_handle::file(std::forward<Args>(args)...); } ... // Now you must always write this: make(std::in_place_type<file_handle>, "hello"); ``` Tagged overloading is fine for smaller projects, but for larger code bases: 1. It takes longer to type `make(std::in_place_type<file_handle>, "hello")`, and is possibly less intuitive to write, than it does `make<file_handle>{"hello"}()`. 2. Compiler error messages are enormously clearer if you encode the permitted overloads for construction into the `make<file_handle>` type rather than letting a variadic free function fail to resolve an appropriate overload. 3. Resolving variadic free function overloads is not constant time for the compiler, whereas resolving the type specialisation for `make<file_handle>` is constant time. In other words, free functions are *expensive* on build times, whereas fully specialised types are not. 4. It actually turns out to be quite useful when writing generic code to pass around object constructing factory objects all of which have no parameters for their call operator. It becomes, effectively, a *lazy construction* mechanism.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/static-constructor.md
+++ title = "Phase 2 construction" description = "" weight = 30 +++ Its phase 2 constructor: {{% snippet "constructors.cpp" "file" %}} The static member function implementing phase 2 firstly calls phase 1 which puts the object into a legally destructible state. We then proceed to implement phase 2 of construction, filling in the various parts as we go, reporting via `result` any failures. {{% notice note %}} Remember that `operator new` has a non-throwing form, `new(std::nothrow)`. {{% /notice %}} For the final return, in theory we could just `return ret` and depending on the C++ version currently in force, it might work via move, or via copy, or it might refuse to compile. You can of course type lots of boilerplate to be explicit, but this use via initialiser list is a reasonable balance of explicitness versus brevity, and it should generate minimum overhead code irrespective of compiler, C++ version, or any other factor.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/file_handle.md
+++ title = "A file handle" description = "" weight = 20 +++ Borrowing from [`llfio::file_handle`](https://ned14.github.io/llfio/classllfio__v2__xxx_1_1file__handle.html) which uses this design pattern[^1], here is a simplified `file_handle` implementation: {{% snippet "constructors.cpp" "file_handle" %}} Note the default member initialisers, these are particularly convenient for implementing phase 1 of construction. Note also the `constexpr` constructor, which thanks to the default member initialisers is otherwise empty. File handles are very expensive to copy as they involve a syscall to duplicate the file descriptor, so we enable moves only. The destructor closes the file descriptor if it is not -1, and if the close fails, seeing as there is nothing else we can do without leaking the file descriptor, we fatal exit the process. Finally we declare the phase 2 constructor which is a static member function. [^1]: LLFIO uses Outcome "in anger", both in Standard and Experimental configurations. If you would like a real world user of Outcome to study the source code of, it can be studied at https://github.com/ned14/llfio/.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/metaprogrammg2.md
+++ title = "construct<T>" description = "" weight = 50 +++ First, we need a base definition for `make<T>`: {{% snippet "constructors.cpp" "construct-declaration" %}} This fails a static assert if the type is ever instantiated unspecialised. We then specialise for `make<file_handle>`: {{% snippet "constructors.cpp" "construct-specialisation" %}} Because this is a struct, we can list initialise `make`, and use default member initialisers to implement default arguments. This can get you surprisingly far before you need to start writing custom constructors. But in more complex code, you will usually provide all the initialisation overloads that you would for the constructors of your main type. You then implement a single phase 2 constructing function which accepts `make<YOURTYPE>` as input, and construct solely from that source.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/two-phase-init.md
+++ title = "Two phase construction" description = "" weight = 10 +++ The first thing to do is to break your object's construction into two phases: 1. Place the object into a state where it can be legally destructed without doing any initialisation which could throw an exception (i.e. everything done in phase 1 is `constexpr`). This phase usually involves initialising member variables to various default values, most often using default member initialisers. Most standard C++ library objects and containers have `constexpr` constructors, and thus can be initialised during phase 1. If you need to initialise a member variable without a `constexpr` constructor, {{% api "std::optional<T>" %}} is the usual workaround. 2. Do the remainder of the construction, the parts which could fail. Because phase 1 placed the object into a legally destructible state, it is usually the case that one can bail out during phase 2 and the destructor will clean things up correctly. The phase 1 construction will be placed into a *private* `constexpr` constructor so nobody external can call it. The phase 2 construction will be placed into a static member initialisation function which returns a `result` with either the successfully constructed object, or the cause of any failure to construct the object. Finally, as a phase 3, some simple metaprogramming will implement a `make<T>{Args...}()` free function which will construct any object `T` by calling its static initialisation function with `Args...` and returning the `result` returned. This isn't as nice as calling `T(Args...)` directly, but it's not too bad in practice. And more importantly, it lets you write generic code which can construct any unknown object which fails via returning `result`, completely avoiding C++ exception throws.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/constructors/metaprogrammg1.md
+++ title = "Phase 3" description = "" weight = 40 +++ We have built our first two phases of construction for `file_handle`, and for some users they might be happy writing: {{% snippet "constructors.cpp" "static-use" %}} ... and be done with it. But wouldn't it be nicer if we could instead write: {{% snippet "constructors.cpp" "construct-use" %}} The eye is immediately drawn to the two-stage invocation pattern, so we are constructing a type `make<file_handle>` using the arguments with which we wish to invoke the `file_handle` constructor with, and then invoking the call operator on that `make<file_handle>` instance to do the actual construction. It may seem a bit clunky to use brace initialisation for parameters followed by a "spurious" set of empty brackets, but we think that this is a better approach than alternatives. We shall briefly cover those at the end of this section.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/payload/_index.md
+++ title = "Custom payloads" description = "Success-or-failure return types where extra information in addition to the error code accompanies failure." weight = 30 tags = [ "payload", "has_error_code", "make_error_code" ] +++ So far in this tutorial, type `EC` in `result<T, EC>` has always been a `std::error_code` or `boost::system::error_code`. With `NoValuePolicy` set to {{% api "default_policy<T, EC, EP>" %}}, `EC` needs in fact to merely satisfy the trait {{< api "is_error_code_available<T>">}} for `EC` to be treated as if an `error_code`. Outcome specialises that trait for `std::error_code` and `boost::system::error_code`, hence they "just work". If no specialisation exists, `trait::is_error_code_available<EC>` is true if there exists some ADL discovered free function `make_error_code(EC)`. Thus, we can in fact use any custom `EC` type we like, including one carrying additional information, or *payload*. This payload can carry anything you like, and you can tell Outcome to do various things with that payload under various circumstances. For example: 1. If the user tries to observe an unsuccessful `result`, throw a custom exception containing the cause of failure with accompanying context from the payload. 2. If the user ever constructs an `outcome` from a payload carrying `result`, set the exception ptr in the constructed `outcome` to a custom exception containing the cause of the failure with accompanying context from the payload. 3. Transmit a stack backtrace specifying the exact point at which failure occurred, symbolising that backtrace into human readable text at the moment of conversion into human readable text. 4. Upon a namespace-localised `result` from library A being copy/moved into a namespace-localised `result` from C bindings library B, set the C `errno` if the error code and category map onto the `errno` domain. There are many, many other options of course. This tutorial can only cover a reasonable subset. This section covers Example 1 above, throwing custom exceptions with payload upon observation of an unsuccessful `result`.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/payload/copy_file2.md
+++ title = "Upgrading the Filesystem TS" description = "" weight = 20 tags = ["payload"] +++ An Outcome based solution to the dual overload problem is straightforward: {{% snippet "outcome_payload.cpp" "filesystem_api_fixed" %}} Starting at the bottom, there is now a single `copy_file()` function which returns a `fs_result<void>`. As `result` is either successful or not, there is no longer any point in returning a boolean, so we simply return `void` on success. On failure, as the template alias `fs_result<T>` above it shows, we are returning a `failure_info` structure containing an error code and the same additional information as `filesystem_error` provides. It is important to note that the fact that `failure_info` is defined in namespace `filesystem2` is very important. This is because Outcome uses [Argument Dependent Lookup (ADL)](http://en.cppreference.com/w/cpp/language/adl) to find the `make_error_code()` function, as well as other customisation point free functions. In other words, only the namespaces as defined by ADL are searched when finding a free function telling us what to do for `failure_info`, which includes the namespace `failure_info` is declared into.
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/payload/copy_file3.md
+++ title = "Auto-throwing filesystem_error" description = "" weight = 30 tags = ["default-actions", "value"] +++ Something not mentioned at all until now (and properly described in the next section, [Default actions](../../default-actions/)) is that Outcome can be programmed take various actions when the user tries to observe `.value()` when there is no value, and so on for the other possible state observations. Seeing as we are replacing the throwing overload of `copy_file()` in the Filesystem TS with a `result` returning edition instead, it would make sense if an attempt to observe the value of an unsuccessful `fs_result` threw the exact same `filesystem_error` as the Filesystem TS does. Telling Outcome how to throw a `filesystem_error` with payload of the failing paths is easy: {{% snippet "outcome_payload.cpp" "filesystem_api_custom_throw" %}} Reference documentation for the above functions: - [List of builtin `outcome_throw_as_system_error_with_payload()` overloads]({{< relref "/reference/functions/policy" >}}) - {{% api "void try_throw_std_exception_from_error(std::error_code ec, const std::string &msg = std::string{})" %}} Usage of our new "upgraded" Filesystem `copy_file()` might now be as follows: {{% snippet "outcome_payload.cpp" "filesystem_api_custom_throw_demo" %}}
0
repos/outcome/doc/src/content/tutorial/advanced
repos/outcome/doc/src/content/tutorial/advanced/payload/copy_file.md
+++ title = "The Filesystem TS" description = "" weight = 10 tags = ["dual-api"] +++ Something which has long annoyed the purists in the C++ leadership is the problem of dual overloads in `error_code` capable standard library APIs. Consider the [`copy_file()`](http://en.cppreference.com/w/cpp/filesystem/copy_file) API from the Filesystem TS: {{% snippet "outcome_payload.cpp" "filesystem_api_problem" %}} Before Outcome, the common design pattern was to provide throwing and non-throwing overloads of every API. As you can see above, the throwing API throws a [`filesystem::filesystem_error`](http://en.cppreference.com/w/cpp/filesystem/filesystem_error) exception type which carries additional information, specifically two paths. These paths may refer to the files which were the source of any failure. However the non-throwing overload does **not** provide this additional information, which can make it more annoying to use the non-throwing overload sometimes. What if we could replace these two overloads of every API in the Filesystem TS with a single API, and additionally have the non-throwing edition return the exact same additional information as the throwing edition?
0
repos/outcome/doc/src/content/tutorial
repos/outcome/doc/src/content/tutorial/essential/_index.md
+++ title = "Essential" description = "The absolute minimum that you need to know to get started with Outcome immediately." weight = 10 +++ {{% children description="true" depth="2" %}}
0
repos/outcome/doc/src/content/tutorial
repos/outcome/doc/src/content/tutorial/essential/before.md
+++ title = "Before we begin" description = "Essential information before you begin the tutorial." weight = 5 tags = ["namespace", "playpen"] +++ ## Outcome v2 namespace It is recommended that you refer to entities from this Outcome v2 via the following namespace alias: {{% snippet "using_result.cpp" "namespace" %}} On standalone Outcome only, as patches and modifications are applied to this library, namespaces get permuted in order to not to cause binary incompatibility. At some point namespace `outcome_v2` will be defined, and this will be the preferred namespace. Until then `OUTCOME_V2_NAMESPACE` denotes the most recently updated version, getting closer to `outcome_v2`. On Boost.Outcome only, as Boost provides no binary compatibility across releases, `OUTCOME_V2_NAMESPACE` always expands into `boost::outcome_v2`. ## Online compilers If you've never used them before, you will find [Godbolt](https://godbolt.org/) and [Wandbox](https://wandbox.org/) invaluable. These let you play with C++ inside your web browser. Most of the source code snippets in Outcome have a link in their top right to the original source code on github. You can copy and paste this source code into Godbolt (if you wish to study the assembler generated) or Wandbox (if you wish to run the program). ### Godbolt Godbolt is invaluable for visualising online the assembler generated for a piece of C++, for all the major compilers and CPU architectures. Standalone Outcome is built into Godbolt! In the right hand pane toolbar, click the libraries dropdown (currently third from the right, looks like a book), find Outcome and choose the version you want. After this is selected, you can `#include` any of these editions of Outcome: <dl> <dt><code>&lt;outcome-basic.hpp&gt;</code></dt> <dd>An inclusion of <code>basic_outcome.hpp</code> + <code>try.hpp</code> which includes as few system headers as possible in order to give an absolute minimum compile time impact edition of Outcome. See <a href="https://github.com/ned14/stl-header-heft">https://github.com/ned14/stl-header-heft</a>. </dd> <dt><code>&lt;outcome-experimental.hpp&gt;</code></dt> <dd>An inclusion of <code>experimental/status_outcome.hpp</code> + <code>try.hpp</code> which is the low compile time impact of the basic edition combined with <code>status_code</code> from <a href="https://ned14.github.io/status-code/">https://ned14.github.io/status-code/</a>. If you are on an embedded system where binary bloat must be absolutely avoided, and don't mind the potentially unstable <code>status_code</code>, this is definitely the edition for you. </dd> <dt><code>&lt;outcome.hpp&gt;</code></dt> <dd>An inclusion of <code>outcome.hpp</code> which brings in all the specialisations for the <code>std</code> STL types, plus iostreams support. If you don't know which edition to use, you should use this one, it ought to "just work".</dd> </dl> Here is the first tutorial topic's source code loaded into Godbolt: https://godbolt.org/z/4of3c8 ### Wandbox Wandbox lets you place a third party header into a separate tab. It also comes with a recent Boost libraries. Either technique can be used to explore Outcome. Here is the first tutorial topic's source code loaded into Wandbox: https://wandbox.org/permlink/sJoeKHXSyCU5Avft
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/no-value/_index.md
+++ title = "No-value policies" description = "Describes the concept of NoValuePolicy and how to use no-value policies." weight = 25 tags = [ "policies" ] +++ In the previous section we have seen that it would be useful if calling member function `.value()` on object of type `outcome<T>` that did not contain a value, would cause an exception to be thrown according to some user-defined policy. Let us consider `result<T>` first. It is an alias to {{% api "basic_result<T, E, NoValuePolicy>" %}}, where `E` is the type storing error information and defaulted to `std::error_code`/`boost::system::error_code`, and `NoValuePolicy` is a *no-value policy* defaulted to {{% api "default_policy<T, EC, EP>" %}}. The semantics of `basic_result::value()` are: 1. Calls `NoValuePolicy::wide_value_check(*this)`. 2. Return a reference to the contained value. If no value is actually stored, your program has entered undefined behaviour. Thus, the semantics of function `.value()` depend on the no-value policy. The default policy (`policy::default_policy<T, EC, void>`) for `EC` of type `std::error_code`[^1] does the following: * If `r.has_value() == false` throws exception `std::system_error{r.error()}`, * otherwise no effect. {{% notice note %}} Class templates {{% api "basic_result<T, E, NoValuePolicy>" %}} and {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}} never use exceptions. Any exception-related logic is provided exclusively through no-value policies. {{% /notice %}} When designing your own success-or-failure type using templates `basic_result<>` or `basic_outcome<>` you have to decide what no-value policy you want to use. Either create your own, or [use one of the predefined policies]({{< relref "/tutorial/essential/no-value/builtin" >}}). You can also use one of the two other predefined aliases for `basic_result<>`: * {{< api "unchecked<T, E = varies>" >}}: it uses policy {{< api "all_narrow" >}}, where any observation of a missing value or error is undefined behavior; * {{< api "checked<T, E = varies>" >}}: it uses policy {{< api "throw_bad_result_access<EC>" >}}, where any observation of a missing value or error throws {{< api "bad_result_access_with<EC>" >}} or {{< api "bad_result_access" >}} respectively. [^1]: Similar overloads exist for throwing `boost::system::system_error` when `EC` is `boost::system::error_code`.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/no-value/custom.md
+++ title = "A custom no-value policy" description = "" weight = 10 +++ If you want your `basic_outcome<>` or `basic_result<>` instances to call `std::abort()` whenever `.value()` is called on an object that does not contain a value, or `.error()` is called on an object that does not contain an error, you will need to define your own no-value policy as follows: {{% snippet "policies.cpp" "abort_policy" %}} All policies ought to inherit from {{% api "base" %}} in order to provide your policy implementation with the internal policy API for accessing and manipulating `result` and `outcome` state. Once the policy is defined, you have to specify it when providing your own `basic_outcome` specialization: {{% snippet "policies.cpp" "outcome_spec" %}}
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/no-value/builtin.md
+++ title = "Built-in policies" description = "" weight = 20 +++ These are the predefined policies built into Outcome: <hr style="border-color: black;"> &nbsp; {{< api "all_narrow" >}} If there is an observation of a value/error/exception which is not present, the program is put into a **hard undefined behaviour** situation. The compiler *literally* compiles no code for an invalid observation -- the CPU "runs off" into the unknown. As bad as this may sound, it generates the most optimal code, and such hard UB is very tool-friendly for detection e.g. undefined behaviour sanitiser, valgrind memcheck, etc. If you are considering choosing this policy, definitely read {{% api "static void _ub(Impl &&)" %}} first. Note that {{< api "unchecked<T, E = varies>" >}} aliases a `basic_result` with the `all_narrow` no-value policy. <hr style="border-color: black;"> &nbsp; {{< api "terminate" >}} Observation of a missing value/error/exception causes a call to `std::terminate()`. Note that configuring `EC = void` or `EP = void` causes {{% api "default_policy" %}} to choose `terminate` as the no-value policy. <hr style="border-color: black;"> &nbsp; {{< api "error_code_throw_as_system_error<T, EC, EP>" >}} This policy assumes that `EC` has the interface of `std::error_code`, and `EP` has the interface of `std::exception_ptr`. Upon missing value observation: * if an exception is stored through pointer of type `EP` it is rethrown; * otherwise, if an error of type `EC` is stored, it is converted to `error_code` and then thrown as `system_error`. Upon missing error observation throws: * `bad_result_access("no error")` from instances of `basic_result<>`. * `bad_outcome_access("no error")` from instances of `basic_outcome<>`. Upon missing exception observation throws `bad_outcome_access("no exception")`. Overloads are provided for `boost::system::error_code` and `boost::exception_ptr`. Note that if {{% api "is_error_code_available<T>" %}} is true for `EC`, and (if `basic_outcome`) {{% api "is_exception_ptr_available<T>" %}} is true for `EP`, {{% api "default_policy" %}} chooses `error_code_throw_as_system_error<T, EC, EP>` as the no-value policy. <hr style="border-color: black;"> &nbsp; {{< api "exception_ptr_rethrow<T, EC, EP>" >}} This policy assumes that either `EC` or `EP` (unless `void`) has the interface of `std::exception_ptr`. Upon missing value observation: * in instances of `basic_result<>`, rethrows exception pointed to by `EC`; * in instances of `basic_outcome<>`, if exception `EP` is present rethrows it, otherwise rethrows `EC`. Upon missing error observation: * in instances of `basic_result<>`, throws `bad_result_access("no error")` ; * in instances of `basic_outcome<>`, throws `bad_outcome_access("no error")`. Upon missing exception observation throws `bad_outcome_access("no exception")`. Overloads are provided for `boost::exception_ptr`. Note that if {{% api "is_exception_ptr_available<T>" %}} is true for `EC`, or (if `basic_outcome`) {{% api "is_exception_ptr_available<T>" %}} is true for `EP`, {{% api "default_policy" %}} chooses `exception_ptr_rethrow<T, EC, EP>` as the no-value policy. <hr style="border-color: black;"> &nbsp; {{< api "throw_bad_result_access<EC>" >}} Upon missing value observation throws `bad_result_access_with<EC>(ec)`, where `ec` is the value of the stored error. If error is not stored, the behaviour is undefined. Upon missing error observation throws `bad_result_access("no error")`. This policy can be used with `basic_outcome<>` instances, where it always throws `bad_outcome_access` for all no-value/error/exception observations. Note that {{< api "checked<T, E = varies>" >}} aliases a `basic_result` with the `throw_bad_result_access<EC>` no-value policy.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/result/_index.md
+++ title = "result<>" description = "Gentle introduction to writing code with simple success-or-failure return types." weight = 10 tags = ["result", "try", "namespace"] +++ We will define a function that converts a `std::string` to an `int`. This function can fail for a number of reasons; if it does we want to communicate the failure reason. {{% snippet "using_result.cpp" "convert_decl" %}} Template alias {{< api "result<T, E = varies, NoValuePolicy = policy::default_policy<T, E, void>>" >}} has three template parameters, but the last two have default values. The first (`T`) represents the type of the object returned from the function upon success. The second (`EC`) is the type of object containing information about the reason for failure when the function fails. A result object stores either a `T` or an `EC` at any given moment, and is therefore conceptually similar to `variant<T, EC>`. `EC` is defaulted to `std::error_code` in standalone Outcome, or to `boost::system::error_code` in Boost.Outcome[^1]. The third parameter (`NoValuePolicy`) is called a no-value policy. We will cover it later. If both `T` and `EC` are [trivially copyable](https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable), `result<T, EC, NVP>` is also trivially copyable. Triviality, complexity and constexpr-ness of each operation (construction, copy construction, assignment, destruction etc) is always the intersection of the corresponding operation in `T` and `EC`, so for example if both `T` and `EC` are [literal types](https://en.cppreference.com/w/cpp/named_req/LiteralType), so will be `result<T, EC, NVP>`. Additionally, if both `T` and `EC` have [standard layout](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType), `result<T, EC, NVP>` has standard layout; thus if both `T` and `EC` are C-compatible, so will `result<T, EC, NVP>` be C-compatible. Now, we will define an enumeration describing different failure situations during conversion. {{% snippet "using_result.cpp" "enum" %}} Assume we have plugged it into `std::error_code` framework, as described in [this section]({{% relref "../../../motivation/plug_error_code" %}}). One notable effect of such plugging is that `ConversionErrc` is now convertible to `std::error_code`. Now we can implement function `convert` as follows: {{% snippet "using_result.cpp" "convert" %}} `result<T, EC>` is convertible from any `T2` convertible to `T` as well as any `EC2` convertible to `EC`, provided that there is no constructability possible in either direction between `T` and `EC`. If there is, all implicit conversion is disabled, and you will need to use one of the tagged constructors: {{% snippet "using_result.cpp" "explicit" %}} Or use helper functions: {{% snippet "using_result.cpp" "factory" %}} {{% notice note %}} The functions {{< api "auto failure(T &&, ...)" >}} and {{< api "auto success(T &&, ...)" >}} return special types implicitly convertible to failed or successful `result` (and `outcome`). {{% /notice %}} [^1]: You can mandate a choice using `std_result<T>` or `boost_result<T>`.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/result/try_greedy.md
+++ title = "TRY is greedy" description = "" weight = 40 tags = ["try"] +++ {{< api "OUTCOME_TRYV(expr)/OUTCOME_TRY(expr)" >}} has 'greedier' implicit conversion semantics than {{< api "basic_result<T, E, NoValuePolicy>" >}}. For example, this code won't compile: ```c++ outcome::result<int, std::error_code> test(outcome::result<int, std::errc> r) { return r; // you need to use explicit construction here // i.e. return outcome::result<int>(r); } ``` This is chosen because there is a non-trivial conversion between `std::errc` and `std::error_code`, so even though that conversion is implicit for `std::error_code`, Outcome does not expose the implicitness here in order to keep the implicit constructor count low (implicit constructors add significantly to build times). The `TRY` operation is more greedy though: ```c++ outcome::result<int, std::error_code> test(outcome::result<int, std::errc> r) { OUTCOME_TRY(r); // no explicit conversion needed return r.value(); } ``` This is because `result<int, std::error_code>` will implicitly construct from anything which either `int` or `std::error_code` will implicitly construct from. However, `result<int, std::error_code>` will not implicitly construct from `result<int, std::errc>`. Thus bear this in mind during usage: `TRY` is greedier for implicit conversions than the Outcome types themselves.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/result/try.md
+++ title = "TRY operations" description = "" weight = 30 tags = ["try"] +++ In the implementation of function `print_half` we have seen the usage of the macro {{< api "OUTCOME_TRYV(expr)/OUTCOME_TRY(expr)" >}}: ```c++ OUTCOME_TRY (auto i, BigInt::fromString(text)); ``` The `OUTCOME_TRY` macro uses C macro overloading to select between two implementations based on the number of input parameters. If there is exactly one input parameter i.e. without the `i`, the control statement is roughly equivalent to: ```c++ auto __result = BigInt::fromString(text); if (!__result) return __result.as_failure(); ``` Where `__result` is a compile time generated unique name. This single argument form is equivalent to `OUTCOME_TRYV(expr)`, incidentally. If there are between two and eight parameters, this control statement is roughly equivalent to: ```c++ auto __result = BigInt::fromString(text); if (!__result) return __result.as_failure(); auto i = __result.value(); ``` So here `i` as the first C macro parameter is set to the value of any successful result. C macro overloads are provided for up to eight arguments. To prevent the confounding of the C preprocessor by commas in template specifications causing more than eight arguments appearing to the C preprocessor, you should consider wrapping the second argument in brackets. If you are within a C++ Coroutine, you ought to use {{< api "OUTCOME_CO_TRYV(expr)/OUTCOME_CO_TRY(expr)" >}} instead. <hr> ### Compiler-specific extension: `OUTCOME_TRYX` {{% notice note %}} This macro makes use of a proprietary extension in GCC and clang, and is not portable. The macro is not made available on unsupported compilers, so you can test for its presence using `#ifdef OUTCOME_TRYX`. {{% /notice %}} GCC and Clang provide an extension to C++ known as [statement expressions](https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html "GCC docs on statement expressions"). These make it possible to use a more convenient macro: `OUTCOME_TRYX`, which is an expression. With the above macro, the above declaration of variable `i` can be rewritten to: ```c++ int i = OUTCOME_TRYX (BigInt::fromString(text)); ``` This has an advantage that you can use it any place where you can put an expression, e.g., in "simple initialization": ```c++ if (int i = OUTCOME_TRYX(BigInt::fromString(text))) use_a_non_zero_int(i); ``` or in as a subexpression of a bigger full expression: ```c++ int ans = OUTCOME_TRYX(BigInt::fromString("1")) + OUTCOME_TRYX(BigInt::fromString("2")); ``` There is also an {{< api "OUTCOME_CO_TRYX(expr)" >}} if you are inside a C++ Coroutine.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/result/try_ref.md
+++ title = "TRY avoiding copy/move" description = "" weight = 50 tags = ["try"] +++ {{< api "OUTCOME_TRYV(expr)/OUTCOME_TRY(expr)" >}} works by creating an internal uniquely named variable which holds the value emitted by the expression. This implies that a copy or move operation shall be performed on the object emitted (unless you are on C++ 17 or later, which has guaranteed copy elision), which may be undesirable for your use case. You can tell `OUTCOME_TRY` to use a reference rather than a value for the internal uniquely named variable like this: ```c++ // This refers to a Result containing an immovable object outcome::result<Immovable> &&res; // For when you do want to extract the value // This creates an auto &&unique = res, followed by an // auto &&v = std::move(unique).assume_value() OUTCOME_TRY((auto &&, v), res); ``` If you don't care about extracting the value: ```c++ // For when you don't want to extract the value // This creates an auto &&unique = res OUTCOME_TRYV2(auto &&, res); ```
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/result/inspecting.md
+++ title = "Inspecting result<T, EC>" description = "" weight = 20 tags = ["nodiscard", "value", "error", "try"] +++ Suppose we will be writing a function `print_half` that takes a `std::string` representing an integer and prints half the integer: {{% snippet "using_result.cpp" "half_decl" %}} The type `result<void>` means that there is no value to be returned upon success, but that the operation might still fail, and we may be interested in inspecting the cause of the failure. The class template `result<>` is declared with the attribute `[[nodiscard]]`, which means the compiler will warn you if you forget to inspect the returned object (in C++ 17 or later). The implementation will do the following: if the integral number can be represented by an `int`, we will convert to `int` and use its arithmetical operations. If the number is too large, we will fall back to using a custom `BigInt` implementation that needs to allocate memory. In the implementation we will use the function `convert` defined in the previous section. {{% snippet "using_result.cpp" "half_impl" %}} #1. You test if `result<>` object represents a successful operation with contextual conversion to `bool`. #2. The function `.value()` extracts the successfully returned `int`. #3. The function `.error()` allows you to inspect the error sub-object, representing information about the reason for failure. #4. Macro `OUTCOME_TRY` represents a control statement. It implies that the expression in the second argument returns a `result<>`. The function is defined as: {{% snippet "using_result.cpp" "from_string" %}} Our control statement means: if `fromString` returned failure, this same error information should be returned from `print_half`, even though the type of `result<>` is different. If `fromString` returned success, we create variable `i` of type `BigInt` with the value returned from `fromString`. If control goes to subsequent line, it means `fromString` succeeded and variable of type `BigInt` is in scope. #5. In the return statement we extract the error information and use it to initialize the return value from `print_half`. We could have written `return r.error();` instead, and it would have the same effect, but `r.as_failure()` will work when implicit construction from `E` has been disabled due to `T` and `E` having a constructibility relationship. #6. Function `success()` returns an object of type `success<void>` representing success. This is implicitly converted by all `result` and `outcome` types into a successful return, default constructing any `T` if necessary.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/coroutines/_index.md
+++ title = "Coroutines" description = "Using Outcome in C++ Coroutines" weight = 30 tags = [ "coroutines" ] +++ [In v2.1.2]({{< relref "/changelog" >}}) Outcome published official support for using Outcome within C++ coroutines. This page documents that support. All standard C++ Coroutines have the following form: ```c++ // Coroutine functions MUST return an AWAITABLE type AWAITABLE<int> function_name(Args ...) { ... ordinary C++ ... if(!...) { co_return 5; // CANNOT use ordinary 'return' from coroutines } ... // Possibly suspend this coroutine's execution until the // awaitable resumes execution of dependent code auto x = co_await expr_resulting_in_AWAITABLE; ... } ``` The type `AWAITABLE<T>` is any type which publishes the Coroutine protocol telling C++ how to suspend and resume execution of a coroutine which returns a `T`. It is out of scope of this page to document how to do this, however note that the `eager<T, Executor = void>` and `lazy<T, Executor = void>` types below are completely generic awaitables suitable for use in ANY code. They **only** behave differently if `T`, the type being returned by the awaitable, is an Outcome type e.g. `outcome::basic_result` or `outcome::basic_outcome`.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/coroutines/co_await.md
+++ title = "`operator co_await` as TRY operator" weight = 40 tags = [ "coroutines", "co_await" ] +++ Many people have requested that `operator co_await` be overloaded to behave as a TRY operator when supplied with an Outcome type. Outcome does not implement that extension, nor will we accept PRs contributing support for this. We think you should use `OUTCOME_CO_TRY()` as this will lead to more maintainable and future proof code. However, we deliberately do not get in the way of you implementing that overload yourself in your own Outcome-based code. Just be sure that you document what you are doing loudly and clearly, and be aware that future C++ standards may have a proper `operator try` overload mechanism.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/coroutines/returning.md
+++ title = "Returning Outcome types from Coroutines" weight = 30 tags = [ "coroutines" ] +++ `eager<T, Executor = void>` and `lazy<T, Executor = void>` and their atomic editions are completely standard awaitables with no special behaviours, **except** if `T` is a `basic_result` or `basic_outcome`. In that situation, the following occurs: If the Coroutine throws a C++ exception which was not handled inside the Coroutine body, Outcome's awaitable types try to convert it into a form which your Result or Outcome type being returned can transport. For example: - If your Coroutine were returning a `result<T, std::exception_ptr>`, an errored Result with a pointer to the exception thrown would be returned. - If your Coroutine were returning a `result<T, std::error_code>`, the exception ptr is passed to {{% api "error_from_exception(" %}}`)` to see if it can be matched to an equivalent `std::error_code`. If it can, an errored Result with the equivalent error code would be returned. - If your Coroutine were returning an `outcome<T, std::error_code, std::exception_ptr>`, an Errored Outcome is chosen preferentially to an Excepted Outcome. - If your Coroutine were returning an `experimental::status_result<T, system_code>`, because Experimental SG14 `system_code` can transport error codes or exception ptrs (or indeed `std::error_code`'s), an errored Result is returned.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/coroutines/try.md
+++ title = "Coroutine TRY operation" weight = 10 tags = [ "coroutines", "try" ] +++ As one cannot call statement `return` from within a Coroutine, the very first part of Outcome's support for Coroutines is {{% api "OUTCOME_CO_TRYV(expr)/OUTCOME_CO_TRY(expr)" %}}, which is literally the same as `OUTCOME_TRY()` except that `co_return` is called to return early instead of `return`. ```c++ eager<result<std::string>> to_string(int x) { if(x >= 0) { OUTCOME_CO_TRY(convert(x)); } co_return "out of range"; } ```
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/coroutines/awaitables.md
+++ title = "Coroutine awaitables" weight = 20 tags = [ "coroutines", "eager", "lazy", "awaitables" ] +++ The second part of the support is provided by header `<outcome/coroutine_support.hpp>` (or `<outcome/experimental/coroutine_support.hpp>` if you want Coroutine support for Experimental Outcome). This adds into namespace `OUTCOME_V2_NAMESPACE::awaitables` (or `OUTCOME_V2_NAMESPACE::experimental::awaitables`) these awaitable types suitable for returning from a Coroutinised function: - {{% api "eager<T, Executor = void>" %}} An eagerly evaluated Coroutine: invoking `co_await` upon a function returning one of these immediately begins the execution of the function now. If the function never suspends, the overhead is similar to calling an ordinary function. - {{% api "lazy<T, Executor = void>" %}} A lazily evaluated Coroutine (often named `task<T>` in most C++ Coroutine literature): invoking `co_await` upon a function returning one of these causes the function to be immediately suspended as soon as execution begins. Only resuming the execution of the coroutine proceeds execution. - {{% api "generator<T, Executor = void>" %}} A lazily evaluated generator of values: the coroutine is resumed to generate the next value, upon which it is suspended until the next iteration. - `atomic_eager<T, Executor = void>` `eager<T>` does not employ thread synchronisation during resumption of dependent coroutines which is fine if you do not traverse kernel threads during a suspend-resume cycle. If you do however potentially traverse kernel threads during suspend-resume, you ought to use `atomic_eager<T>` instead -- this uses atomics to synchronise the setting and checking of state to ensure correctness. - `atomic_lazy<T, Executor = void>` Same for `lazy<T>` as `atomic_eager<T>` is for `eager<T>`.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/conventions/_index.md
+++ title = "Conventions" description = "Why you should avoid custom `E` types in public APIs." weight = 80 tags = [ "best-practice", "conventions", "idioms" ] +++ You now know everything you need to get started with using Outcome immediately. The initial temptation for most beginners will be to use a bespoke strongly typed enumeration on a case by case basis i.e. a "once off" custom `E` type. This is usually due to experience in other languages with sum types e.g. Rust, Haskell, Swift etc. However this is C++! Not Rust, not Swift, not Haskell! I must caution you to always avoid using custom `E` types in public APIs. The reason is that every time library A using custom `E1` type must interface with library B using custom `E2` type, you must map between those `E1` and `E2` types. This is information lossy, i.e. fidelity of failure gets lost after multiple translations. It involves writing, and then *maintaining*, a lot of annoying boilerplate. It leaks internal implementation detail, and fails to separate concerns. And one cannot use {{< api "OUTCOME_TRYV(expr)/OUTCOME_TRY(expr)" >}} if there is no convertibility between `E` types. The C++ 11 standard library, and Boost, specifically ships `<system_error>` for the purpose of wrapping up individual custom `E` types into a generic framework, where disparate custom `E` types can discover and interact with one another. That ships with every C++ compiler. For all these reasons, this is why `result` and `outcome` default the `EC` type to error code. You should leave that default alone where possible. --- ### tl;dr; Please [plug your library into `std::error_code`]({{< relref "/motivation/plug_error_code" >}}), or [equivalent]({{< relref "/experimental" >}}), and do not expose custom `E` types in ANY public API. `result` and `outcome` default `EC` to an error code for good reason.
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/outcome/_index.md
+++ title = "outcome<>" description = "Success-or-failure return types where failure can take two forms, expected/handled failure and unexpected/abort failure." weight = 20 tags = ["outcome"] +++ Type {{< api "outcome<T, EC = varies, EP = varies, NoValuePolicy = policy::default_policy<T, EC, EP>>" >}} represents either a successfully computed value of type `T`, or one or two reasons for failure. Failure can be represented by `EC`, or `EP`, or both, although usually it will either be an `EC` or an `EP`. Similarly to `result`, `EC` defaults to `std::error_code`/`boost::system::error_code`, and `EP` defaults to `std::exception_ptr`/`boost::exception_ptr`. The distinction is made into two types, `EC` and `EP`: - `EC` represents a *recoverable* failure from a lower-layer function, perhaps which was returned through {{< api "result<T, E = varies, NoValuePolicy = policy::default_policy<T, E, void>>" >}}. - `EP` represents an *unrecoverable* failure where a C++ exception would ordinarily have been thrown. This is usually a pointer to an exception throw. It should be emphasised that this distinction is by convention only, but it will be confusing to your users if you deviate significantly from this convention. <hr> ### Legacy codebases `outcome` is useful for transporting exceptions across layers of the program that were never designed with exception safety in mind. Consider a program consisting of three layers: {{<if_boost "/tutorial/essential/outcome/layer_chart.gif">}} {{<mermaid>}} graph BT L3["Layer3"] L2["Layer2_old"] --> L3 L1["Layer1"] --> L2 {{</mermaid>}} {{</if_boost>}} The highest-level layer, `Layer3`, uses exceptions for signalling failures. The middle layer, `Layer2_old`, was not designed with exception safety in mind and functions need to return information about failures in return value. But down in the implementation details, in `Layer1`, another library is used that again throws exceptions. The goal is to be able to transfer an exception thrown in `Layer1` through `Layer2_old`, which is not exception-safe, and be able to rethrow it in `Layer3`. In `Layer1` we have two functions from two libraries: one reports failures by throwing exceptions, the other by returning `result<>`: {{% snippet "using_outcome.cpp" "decl_f_g" %}} In `Layer2_old` we cannot use exceptions, so its function `h` uses return type `outcome<>` to report failures. It is using functions `f` and `g` and reports their failures inside `outcome<>`: {{% snippet "using_outcome.cpp" "def_h" %}} #1. Operator `TRY` can forward failures encoded in `result<T, EC>` as `outcome<T, EC, EP>` without any loss in information. You can also use `TRY` to forward failure from one `outcome<>` to another. #2. You can store the current exception through `std::exception_ptr` inside `outcome<T, EC, EP>` without any loss in information (provided that `EP` is `std::exception_ptr`).
0
repos/outcome/doc/src/content/tutorial/essential
repos/outcome/doc/src/content/tutorial/essential/outcome/inspecting.md
+++ title = "Inspecting outcome<T, EC, EP>" description = "" weight = 30 tags = ["outcome", "value", "error", "exception"] +++ Continuing with the previous example, in `Layer3` we have function `z` which again reports failures via exceptions. It will call function `h` from `Layer2_old` which returns `outcome<int>` (which may store an `int` or a `std::error_code` or a `std::exception_ptr`). The goal is to unpack it to either the successful return value `int` or to throw an appropriate exception: if we are storing an `std::exception_ptr`, just rethrow it. If we are storing a `std::error_code` throw it as `std::system_error`, which is designed to store `std::error_code`'s: {{% snippet "using_outcome.cpp" "def_z" %}} Function `has_exception()` checks if it is `EP` (`std::exception_ptr`) that is stored, function `exception()` accesses it. Similarly, function `error()` accesses the `EC` (`std::error_code`) if it is stored. `outcome<>` also has a function `has_failure()` to check if either `EC` or `EP` is being stored. It would seem obvious that the above pattern of 'unpacking' `outcome<>` is so common that it ought to be implemented inside function `.value()`, so function `z` could be written as: ```c++ return old::h().value(); ``` And this is exactly what the aforementioned no-value policy template argument is for, which is described in the next section.
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/partials/custom-head.html
<link href="{{"css/local.css" | relURL}}" rel="stylesheet">
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/partials/menu.html
{{- $currentNode := . }} {{- $showvisitedlinks := .Site.Params.showVisitedLinks -}} {{- if eq .Site.Params.ordersectionsby "title"}} {{- range .Site.Home.Sections.ByTitle}} {{- template "section-tree-nav" dict "sect" . "currentnode" $currentNode "showvisitedlinks" $showvisitedlinks}} {{- end}} {{- else}} {{- range .Site.Home.Sections.ByWeight}} {{- template "section-tree-nav" dict "sect" . "currentnode" $currentNode "showvisitedlinks" $showvisitedlinks}} {{- end}} {{- end}} <!-- templates --> {{- define "section-tree-nav" }} {{- $showvisitedlinks := .showvisitedlinks }} {{- $currentNode := .currentnode }} {{- with .sect}} {{- if and .IsSection (or (not .Params.hidden) $.showhidden)}} {{- $numberOfPages := (add (len .Pages) (len .Sections)) }} {{- safeHTML .Params.head}} <li data-nav-id="{{.URL}}" class="dd-item {{- if .IsAncestor $currentNode}} parent{{end}} {{- if eq .URL $currentNode.URL}} active{{end}} {{- if .Params.alwaysopen}} alwaysopen{{end -}} {{- if ne $numberOfPages 0 }} haschildren{{end}} "> <div> <a href="{{ .RelPermalink}}">{{safeHTML .Params.Pre}}{{.Title | markdownify}}{{safeHTML .Params.Post}}</a> {{- if ne $numberOfPages 0 }} {{- if or (.IsAncestor $currentNode) (.Params.alwaysopen) }} <i class="fa fa-angle-down fa-lg category-icon"></i> {{- else -}} <i class="fa fa-angle-right fa-lg category-icon"></i> {{- end}} {{- end}} {{- if $showvisitedlinks}}<i class="fa fa-circle-thin read-icon"></i>{{end}} </div> {{- if ne $numberOfPages 0 }} <ul> {{- .Scratch.Set "pages" .Pages }} {{- if .Sections}} {{- .Scratch.Set "pages" (.Pages | union .Sections) }} {{- end}} {{- $pages := (.Scratch.Get "pages") }} {{- if eq .Site.Params.ordersectionsby "title"}} {{- range $pages.ByTitle }} {{- if and .Params.hidden (not $.showhidden) }} {{- else}} {{- template "section-tree-nav" dict "sect" . "currentnode" $currentNode "showvisitedlinks" $showvisitedlinks }} {{- end}} {{- end}} {{- else}} {{- range $pages.ByWeight }} {{- if and .Params.hidden (not $.showhidden) }} {{- else}} {{- template "section-tree-nav" dict "sect" . "currentnode" $currentNode "showvisitedlinks" $showvisitedlinks }} {{- end}} {{- end}} {{- end}} </ul> {{- end}} </li> {{- else}} {{- if not .Params.Hidden }} <li data-nav-id="{{.URL}}" class="dd-item {{- if eq .URL $currentNode.URL}} active{{end -}} "> <div> <a href="{{ .RelPermalink}}"> {{safeHTML .Params.Pre}}{{.LinkTitle | markdownify}}{{safeHTML .Params.Post}} </a> {{- if $showvisitedlinks}}<i class="fa fa-circle-thin read-icon"></i>{{end}} </div> </li> {{- end}} {{- end}} {{- end}} {{- end}}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/partials/next-prev-page.html
<div id="navigation"> <!-- Next prev page --> {{- $currentNode := . -}} {{- template "menu-nextprev" dict "menu" .Site.Home "currentnode" $currentNode -}} {{- define "menu-nextprev" -}} {{- $currentNode := .currentnode -}} {{- if ne .menu.Params.hidden true -}} {{- if hasPrefix $currentNode.URL .menu.URL -}} {{- $currentNode.Scratch.Set "NextPageOK" "OK" -}} {{- $currentNode.Scratch.Set "prevPage" ($currentNode.Scratch.Get "prevPageTmp") -}} {{- else -}} {{- if eq ($currentNode.Scratch.Get "NextPageOK") "OK" -}} {{- $currentNode.Scratch.Set "NextPageOK" nil -}} {{- $currentNode.Scratch.Set "nextPage" .menu -}} {{- end -}} {{- end -}} {{- $currentNode.Scratch.Set "prevPageTmp" .menu -}} {{- $currentNode.Scratch.Set "pages" .menu.Pages -}} {{- if .menu.IsHome -}} {{- $currentNode.Scratch.Set "pages" .menu.Sections -}} {{- else if .menu.Sections -}} {{- $currentNode.Scratch.Set "pages" (.menu.Pages | union .menu.Sections) -}} {{- end -}} {{- $pages := ($currentNode.Scratch.Get "pages") -}} {{- range $pages.ByWeight -}} {{- template "menu-nextprev" dict "menu" . "currentnode" $currentNode -}} {{- end -}} {{- end -}} {{- end -}} {{- if not $.Site.Params.disableNavChevron -}} {{- with ($.Scratch.Get "prevPage") -}} <a class="nav nav-prev" href="{{.URL}}" title="{{.Title}}"> <i class="fa fa-chevron-left"></i><label>{{.Title | markdownify}}</label></a> {{ end -}} {{- with ($.Scratch.Get "nextPage") -}} <a class="nav nav-next" href="{{.URL}}" title="{{.Title}}" style="margin-right: 0px;"><label>{{.Title | markdownify}}</label><i class="fa fa-chevron-right"></i></a> {{- end }} {{- end -}} </div>
0
repos/outcome/doc/src/layouts/partials
repos/outcome/doc/src/layouts/partials/flex/body-beforecontent.html
<header> <div class="logo"> {{ partial "header.html" . }} </div> <div class="burger"><a href="javascript:void(0);" style="font-size:15px;">&#9776;</a></div> {{- with .Site.Menus.shortcuts}} <nav class="shortcuts"> {{- range sort . "Weight"}} <li class="" role=""> <a href="{{.URL}}" {{if eq $.Site.Params.menushortcutsnewtab true}}target="_blank"{{end}} rel="noopener"> {{safeHTML .Name}} </a> </li> {{- end}} </nav> {{- end}} </header> <article> <aside> <ul class="menu"> {{- if not .Site.Params.disableHomeIcon}} <li data-nav-id="{{"/" | relLangURL}}" class="dd-item"> <a href="{{"/" | relLangURL}}"> <i class="fa fa-fw fa-home"></i> </a> </li> {{- end}} {{- partial "menu.html" . }} </ul> {{- partial "language-selector.html" . }} <section> {{- partial "menu-footer.html" . }} </section> </aside> <section class="page"> <div class="nav-select"> <center>Navigation : <select onchange="javascript:location.href = this.value;"> {{partial "flex/selectnavigation.html" .}} </select> </center> </div> {{- if not .Site.Params.disableSearch}} <div> <div class="searchbox"> <input data-search-input id="search-by" type="text" placeholder="{{T "Search-placeholder"}}"> </div> <script type="text/javascript" src="{{"js/lunr.min.js" | relURL}}"></script> <script type="text/javascript" src="{{"js/auto-complete.js" | relURL}}"></script> <link href="{{"css/auto-complete.css" | relURL}}" rel="stylesheet"> <script type="text/javascript"> {{ if .Site.IsMultiLingual }} var baseurl = "{{.Site.BaseURL}}{{.Site.LanguagePrefix}}"; {{ else }} var baseurl = "{{.Site.BaseURL}}"; {{ end }} </script> <script type="text/javascript" src="{{"js/search.js" | relURL}}"></script> </div> {{- end}} {{if not .IsHome}}<h1>{{.Title | markdownify}}</h1>{{end}}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/toc.html
{{if not (in .Site.Title "Boost.") }}{{ $.Page.TableOfContents }}{{end}}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/boost-copyright.html
{{- if in .Site.Title "Boost." }}<div> <div class="author"> <h3 class="author"><span class="firstname">Niall</span> <span class="surname">Douglas</span></h3> </div> </div> <div><p class="copyright">Copyright &#169; 2014-{{ now.Format "2006" }} Niall Douglas <a href="{{"/credits.html" | relURL}}">and others</a></p></div> <div><div class="legalnotice"> <a name="outcome.legal"></a><p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></div> {{ partial "boost-index" (dict "context" . "toc_depth" 2) }} <h2 class="title">Introduction</h2> {{- end}}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/api.html
{{- if and (hasPrefix (.Get 0) "std::") (not (hasPrefix (.Get 0) "std::experimental")) (not (in (.Get 0) "print(")) }} {{- if hasPrefix (.Get 0) "std::errc" }} <a href="https://en.cppreference.com/w/cpp/error/errc" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::error_category" }} <a href="https://en.cppreference.com/w/cpp/error/error_category" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::error_code" }} <a href="https://en.cppreference.com/w/cpp/error/error_code" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::exception_ptr" }} <a href="https://en.cppreference.com/w/cpp/error/exception_ptr" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::generic_category" }} <a href="https://en.cppreference.com/w/cpp/error/generic_category" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::is_error_code_enum" }} <a href="https://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::is_error_condition_enum" }} <a href="https://en.cppreference.com/w/cpp/error/error_condition/is_error_condition_enum" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::in_place_type_t" }} <a href="https://en.cppreference.com/w/cpp/utility/in_place" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::launder" }} <a href="https://en.cppreference.com/w/cpp/utility/launder" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::logic_error" }} <a href="https://en.cppreference.com/w/cpp/error/logic_error" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::make_error_code" }} <a href="https://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search=make_error_code" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::make_exception_ptr" }} <a href="https://en.cppreference.com/w/cpp/error/make_exception_ptr" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::optional" }} <a href="https://en.cppreference.com/w/cpp/utility/optional" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::rethrow_exception" }} <a href="https://en.cppreference.com/w/cpp/error/rethrow_exception" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::system_category" }} <a href="https://en.cppreference.com/w/cpp/error/system_category" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::system_error" }} <a href="https://en.cppreference.com/w/cpp/error/system_error" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::terminate" }} <a href="https://en.cppreference.com/w/cpp/error/terminate" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::variant" }} <a href="https://en.cppreference.com/w/cpp/utility/variant" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::expected" }} <a href="https://wg21.link/P0323" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> P0323 <code>{{ .Get 0 }}</code></a> {{- else if hasPrefix (.Get 0) "std::unexpected" }} <a href="https://wg21.link/P0323" class="api-reference" target="_blank"><i class="fa fa-book" aria-hidden="true"></i> P0323 <code>{{ .Get 0 }}</code></a> {{- else }} {{- errorf "Unknown cppreference target %s" (.Get 0) }} {{- end }} {{- else }} {{- $api_found := false }} {{- $api_title := "" }} {{- $api_url := "" }} {{- $api := .Get 0 }} {{- range .Site.Pages }} {{- if in .Title $api -}} {{- if $api_found }} {{- if lt (len .Title) (len $api_title) }} {{- $api_title = .Title }} {{- $api_url = .URL }} {{- end }} {{- else }} {{- $api_title = .Title }} {{- $api_url = .URL }} {{- $api_found = true }} {{- end }} {{- end }} {{- end }} {{- if $api_found -}} <a href="{{ $api_url }}" class="api-reference"><code>{{ $api }}</code></a> {{- else }} {{- errorf "%s: API reference page for '%s' not found, please use an identifier wholly contained in a page title" .Position (.Get 0) }} <b>API NOT FOUND IN DOCS <code>{{ .Get 0 }}</code></b> {{- end }} {{- end }}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/figure.html
<figure{{ with .Get "class" }} class="{{ . }}"{{ end }}> {{- if .Get "link" -}} <a href="{{ .Get "link" }}"{{ with .Get "target" }} target="{{ . }}"{{ end }}{{ with .Get "rel" }} rel="{{ . }}"{{ end }}> {{- end }} <img src="{{ .Get "src" | relURL }}" {{- if or (.Get "alt") (.Get "caption") }} alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "caption" | markdownify| plainify }}{{ end }}" {{- end -}} {{- with .Get "width" }} width="{{ . }}"{{ end -}} {{- with .Get "height" }} height="{{ . }}"{{ end -}} /> <!-- Closing img tag --> {{- if .Get "link" }}</a>{{ end -}} {{- if or (or (.Get "title") (.Get "caption")) (.Get "attr") -}} <figcaption> {{ with (.Get "title") -}} <h4>{{ . }}</h4> {{- end -}} {{- if or (.Get "caption") (.Get "attr") -}}<p> {{- .Get "caption" | markdownify -}} {{- with .Get "attrlink" }} <a href="{{ . }}"> {{- end -}} {{- .Get "attr" | markdownify -}} {{- if .Get "attrlink" }}</a>{{ end }}</p> {{- end }} </figcaption> {{- end }} </figure>
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/slides.html
<br/><iframe src="https://docs.google.com/presentation/{{ .Get 0 }}/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/if_boost.html
{{- if in .Site.Title "Boost." }} <center><img src="{{.Get 0}}"></center> {{- else }} {{ .Inner }} <noscript><center><img src="{{.Get 0}}"></center></noscript> {{- end }}
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/snippet.md
<div class="code-snippet">{{ $snippet := split (readFile (printf "snippets/%s" (.Get 0))) (printf "//! [%s]" (.Get 1)) }}{{ $lineno := split (index $snippet 0) "\n" | len }}{{highlight (strings.TrimLeft "\r\n" (strings.TrimRight "\r\n " (index $snippet 1))) "c++" ""}}<a href="{{ $.Site.Params.snippetsURL }}{{ .Get 0 }}#L{{ add 1 $lineno }}" class="code-snippet-url" target="_blank">View this code on Github</a></div>
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/ghcontributors.html
<style type="text/css"> .ghContributors{ display:flex; flex-flow: wrap; align-content: flex-start } .ghContributors > div{ width: 50% ; display: inline-flex; margin-bottom: 5px; } .ghContributors > div label{ padding-left: 4px ; } .ghContributors > div span{ font-size: x-small; padding-left: 4px ; } </style> <div class="ghContributors"> {{ $url := .Get 0 }} {{ range getJSON $url }} <div> <img src="{{.avatar_url}}" class="inline" width="32" height="32" style="height: 32px;height: 32px;margin-bottom:.25em; vertical-align:middle; "> <label><a href="{{.html_url}}">@{{.login}}</a></label> <span class="contributions">{{.contributions}} commits</span> </div> {{ end }} </div>
0
repos/outcome/doc/src/layouts
repos/outcome/doc/src/layouts/shortcodes/children.html
{{- $showhidden := .Get "showhidden"}} {{- $container := .Get "container" | default "ol" }} {{- $style := .Get "style" | default "li" }} {{- $depth := int (.Get "depth" | default "1") }} {{- $description := eq (.Get "description" | default "false") "true" }} {{- $sortTerm := .Get "sort" | default "Weight" }} {{- $categories := cond (ne (.Get "categories") "") (split (.Get "categories") ",") nil }} {{- .Scratch.Set "current" .Page }} {{- if (.Get "page")}} {{- with .Site.GetPage "section" (.Get "page") }} {{- $.Scratch.Set "current" . }} {{- end }} {{- end }} {{- $cpage := (.Scratch.Get "current") }} {{- (printf "<%s class=\"children children-%s\">" $container $style)|safeHTML}} {{- .Scratch.Set "pages" $cpage.Pages }} {{- if $cpage.Sections}} {{- .Scratch.Set "pages" ($cpage.Pages | union $cpage.Sections) }} {{- end}} {{- $pages := (.Scratch.Get "pages") }} {{- if eq $sortTerm "Weight"}} {{- template "childs2" dict "menu" $pages.ByWeight "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{- else if eq $sortTerm "Name"}} {{- template "childs2" dict "menu" $pages.ByTitle "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{- else if eq $sortTerm "PublishDate"}} {{- template "childs2" dict "menu" $pages.ByPublishDate "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{- else if eq $sortTerm "Date"}} {{- template "childs2" dict "menu" $pages.ByDate "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{- else if eq $sortTerm "Length"}} {{- template "childs2" dict "menu" $pages.ByLength "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{- else}} {{- template "childs2" dict "menu" $pages "style" $style "showhidden" $showhidden "count" 1 "depth" $depth "pages" .Site.Pages "description" $description "sortTerm" $sortTerm "container" $container "categories" $categories}} {{end}} {{- (printf "</%s>" $container)|safeHTML}} {{.Inner|safeHTML}} {{ define "childs2" }} {{- range .menu }} {{- $in_categories := intersect $.categories .Params.categories }} {{- if or (and .Params.hidden (not $.showhidden)) (and $.categories (not $in_categories)) }} {{- else}} {{- if hasPrefix $.style "h"}} {{- $num := sub ( int (trim $.style "h") ) 1 }} {{- $numn := add $num $.count }} {{- (printf "<h%d>" $numn)|safeHTML}} <a href="{{.URL}}" >{{ .Title | markdownify }}</a> {{- else}} {{- (printf "<%s>" $.style)|safeHTML}} <a href="{{.URL}}" >{{ .Title | markdownify }}</a> {{- end}} {{- if $.description}} {{- if .Description}} <p>{{.Description | markdownify}}</p> {{- end}} {{- end}} {{- if lt $.count $.depth}} {{- .Scratch.Set "pages" .Pages }} {{- if .Sections}} {{- .Scratch.Set "pages" (.Pages | union .Sections) }} {{- end}} {{- $pages := (.Scratch.Get "pages") }} {{- if $pages }} {{- if or (eq $.style "li") (eq $.style "dt") }} {{- (printf "<%s>" $.container)|safeHTML}} {{- end}} {{- if eq $.sortTerm "Weight"}} {{- template "childs2" dict "menu" $pages.ByWeight "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- else if eq $.sortTerm "Name"}} {{- template "childs2" dict "menu" $pages.ByTitle "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- else if eq $.sortTerm "PublishDate"}} {{- template "childs2" dict "menu" $pages.ByPublishDate "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- else if eq $.sortTerm "Date"}} {{- template "childs2" dict "menu" $pages.ByDate "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- else if eq $.sortTerm "Length"}} {{- template "childs2" dict "menu" $pages.ByLength "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- else}} {{- template "childs2" dict "menu" $pages "style" $.style "showhidden" $.showhidden "count" (add $.count 1) "depth" $.depth "pages" $.pages "description" $.description "sortTerm" $.sortTerm "container" $.container "categories" $.categories}} {{- end}} {{- if or (eq $.style "li") (eq $.style "dt") }} {{- (printf "</%s>" $.container)|safeHTML}} {{- end }} {{- end }} {{- end }} {{- end }} {{- end }} {{- if hasPrefix $.style "h"}} {{- $num := sub ( int (trim $.style "h") ) 1 }} {{- $numn := add $num $.count }} {{- (printf "</h%d>" $numn)|safeHTML}} {{- else}} {{- (printf "</%s>" $.style)|safeHTML}} {{- end}} {{- end }}
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/error_code_extended.cpp
/* Example of how to extend result's error code with extra information (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (7 commits) and Andrzej Krzemieński <[email protected]> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <array> #include <iostream> #ifdef _WIN32 #include "quickcpplib/execinfo_win64.h" #else #include <execinfo.h> #endif #ifdef _MSC_VER #pragma warning(disable : 4702) // unreachable code #endif namespace error_code_extended { using OUTCOME_V2_NAMESPACE::in_place_type; template <class T> using in_place_type_t = OUTCOME_V2_NAMESPACE::in_place_type_t<T>; } //! [error_code_extended1] /* Outcome's hook mechanism works vis ADL, so we will need a custom namespace to ensure the hooks apply only to the types declared in this namespace only */ namespace error_code_extended { // The extra error information we will keep struct extended_error_info { std::array<void *, 16> backtrace; // The backtrace size_t items; // Items in backtrace array which are valid }; struct mythreadlocaldata_t { // Keep 16 slots of extended error info as a ringbuffer extended_error_info slots[16]; // The current oldest slot uint16_t current{0}; // Return the oldest slot extended_error_info &next() { return slots[(current++) % 16]; } // Retrieve a previously stored slot, detecting if it is stale extended_error_info *get(uint16_t idx) { // If the idx is stale, return not found if(idx - current >= 16) { return nullptr; } return slots + (idx % 16); } }; // Meyers' singleton returning a thread local data structure for this thread inline mythreadlocaldata_t &mythreadlocaldata() { static thread_local mythreadlocaldata_t v; return v; } } //! [error_code_extended1] //! [error_code_extended2] namespace error_code_extended { // Use the error_code type as the ADL bridge for the hooks by creating a type here // It can be any type that your localised result uses, including the value type but // by localising the error code type here you prevent nasty surprises later when the // value type you use doesn't trigger the ADL bridge. struct error_code : public std::error_code { // literally passthrough using std::error_code::error_code; error_code() = default; error_code(std::error_code ec) : std::error_code(ec) { } }; // Localise result and outcome to using the local error_code so this namespace gets looked up for the hooks template <class R> using result = OUTCOME_V2_NAMESPACE::result<R, error_code>; template <class R> using outcome = OUTCOME_V2_NAMESPACE::outcome<R, error_code /*, std::exception_ptr */>; } //! [error_code_extended2] //! [error_code_extended3] namespace error_code_extended { // Specialise the result construction hook for our localised result // We hook any non-copy, non-move, non-inplace construction, capturing a stack backtrace // if the result is errored. template <class T, class U> inline void hook_result_construction(result<T> *res, U && /*unused*/) noexcept { if(res->has_error()) { // Grab the next extended info slot in the TLS extended_error_info &eei = mythreadlocaldata().next(); // Write the index just grabbed into the spare uint16_t OUTCOME_V2_NAMESPACE::hooks::set_spare_storage(res, mythreadlocaldata().current - 1); // Capture a backtrace into my claimed extended info slot in the TLS eei.items = ::backtrace(eei.backtrace.data(), eei.backtrace.size()); } } } //! [error_code_extended3] //! [error_code_extended4] namespace error_code_extended { // Synthesise a custom exception_ptr from the TLS slot and write it into the outcome template <class R> inline void poke_exception(outcome<R> *o) { if(o->has_error()) { extended_error_info *eei = mythreadlocaldata().get(OUTCOME_V2_NAMESPACE::hooks::spare_storage(o)); if(eei != nullptr) { // Make a custom string for the exception std::string str(o->error().message()); str.append(" ["); struct unsymbols // RAII cleaner for symbols { char **_{nullptr}; ~unsymbols() { ::free(_); } } symbols{::backtrace_symbols(eei->backtrace.data(), eei->items)}; if(symbols._ != nullptr) { for(size_t n = 0; n < eei->items; n++) { if(n > 0) { str.append("; "); } str.append(symbols._[n]); } } str.append("]"); // Override the payload/exception member in the outcome with our synthesised exception ptr OUTCOME_V2_NAMESPACE::hooks::override_outcome_exception(o, std::make_exception_ptr(std::runtime_error(str))); } } } } //! [error_code_extended4] //! [error_code_extended5] namespace error_code_extended { // Specialise the outcome copy and move conversion hook for when our localised result // is used as the source for copy construction our localised outcome template <class T, class U> inline void hook_outcome_copy_construction(outcome<T> *res, const result<U> & /*unused*/) noexcept { try { // when copy constructing from a result<T>, poke in an exception poke_exception(res); } catch(...) { // Do nothing } } template <class T, class U> inline void hook_outcome_move_construction(outcome<T> *res, result<U> && /*unused*/) noexcept { try { // when move constructing from a result<T>, poke in an exception poke_exception(res); } catch(...) { // Do nothing } } } //! [error_code_extended5] extern error_code_extended::result<int> func2() { using namespace error_code_extended; // At here the stack backtrace is collected and custom message stored in TLS return make_error_code(std::errc::operation_not_permitted); } extern error_code_extended::outcome<int> func1() { using namespace error_code_extended; // At here the custom message and backtrace is assembled into a custom exception_ptr return outcome<int>(func2()); } //! [error_code_extended] int main() { try { using namespace error_code_extended; outcome<int> r = func1(); r.value(); std::cerr << "Unfortunately the extension of the local result<> type to track stack backtraces and keep custom messages did not work\n"; std::cerr << "No exception was ever thrown!" << std::endl; return 1; } catch(const std::system_error &e) { std::cerr << "Unfortunately the extension of the local result<> type to track stack backtraces and keep custom messages did not work\n"; std::cerr << "The exception thrown instead says:\n\n"; std::cerr << e.what() << std::endl; return 1; } catch(const std::runtime_error &e) { std::cout << "The extension of the local result<> type to track stack backtraces and keep custom messages worked!\n"; std::cout << "Here is the extended message which should include also a backtrace:\n\n"; std::cout << e.what() << std::endl; return 0; } return 1; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/udts.cpp
/* Example of Outcome used with UDTs (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> int main() { using namespace OUTCOME_V2_NAMESPACE; //! [udts] struct udt { int a{0}; explicit udt(int _a) : a(_a) { } udt() = default; int operator*() const { return a; } }; struct err { int a{0}; explicit err(int _a) : a(_a) { } err() = default; }; //! [udts] #if 0 //! [implicit] result<udt, err> res(5); // fails to compile, cannot convert 'int' to result //! [implicit] //! [explicit] // When it is not unambiguous which to construct, we must say which we want same as with std::variant<> result<udt, err> res(in_place_type<err>, 5); //! [explicit] #endif //! [access] result<udt, err, policy::terminate> res(in_place_type<err>, 5); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [access] return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/error_code_enums2.cpp
/* Example of Outcome used with error code enums (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> //! [declaration] struct udt { int a{0}; explicit udt(int _a) : a(_a) { } udt() = default; int operator*() const { return a; } }; enum class err { success, failure1, failure2 }; // Tell the standard library that enum err is an error code enum // by specialising the is_error_code_enum trait. See // http://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum namespace std { template <> struct is_error_code_enum<err> : std::true_type { }; } // We also must declare a free function make_error_code. This is // discovered via ADL by the standard library. See // http://en.cppreference.com/w/cpp/error/errc/make_error_code inline std::error_code make_error_code(err c) { // We need to inherit from std::error_category to define // an error code domain with the standard library for // our strongly typed enum. See // http://en.cppreference.com/w/cpp/error/error_category static struct err_category : std::error_category { virtual const char *name() const noexcept override final { return "err_category"; }; virtual std::string message(int c) const override final { switch(static_cast<err>(c)) { case err::success: return "err::success"; case err::failure1: return "err::failure1"; case err::failure2: return "err::failure2"; } return "unknown"; } } category; return std::error_code(static_cast<int>(c), category); } //! [declaration] using namespace OUTCOME_V2_NAMESPACE; int main() { //! [usage] result<udt, err> res(err::failure1); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [usage] return 0; } void test() { //! [usage2] result<udt /*, std::error_code */> res(err::failure1); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { // Prints "Exception thrown was failure1", exactly the same as before std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [usage2] } //! [usage3] result<udt> boo() { return err::failure1; } result<udt> foo() { OUTCOME_TRY(auto v, (boo())); return udt{5}; // emplace construct udt with 5 } //! [usage3]
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/using_outcome.cpp
/* Example of Outcome (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits), Krzemienski <[email protected]> (3 commits) and Andrzej Krzemienski <[email protected]> (3 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> namespace outcome = OUTCOME_V2_NAMESPACE; //! [decl_f_g] auto f() -> int; // throws on failure auto g() noexcept -> outcome::result<int>; //! [decl_f_g] auto f() -> int { throw std::runtime_error{"failure"}; } auto g() noexcept -> outcome::result<int> { return 1; } namespace old { auto h() noexcept -> outcome::outcome<int>; } //! [def_h] auto old::h() noexcept -> outcome::outcome<int> { OUTCOME_TRY(auto i, (g())); // #1 try { return i + f(); } catch (...) { return std::current_exception(); // #2 } } //! [def_h] //! [def_z] auto z() -> int // throws on failure { if (outcome::outcome<int> o = old::h()) return o.value(); else if (o.has_exception()) std::rethrow_exception(o.exception()); else throw std::system_error{o.error()}; } //! [def_z] int main() try { return z(); } catch(std::runtime_error const& e) { std::cerr << e.what() << std::endl; return 1; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/exception_ptr.cpp
/* Example of Outcome used with exception ptrs (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> int main() { using namespace OUTCOME_V2_NAMESPACE; //! [exception_ptr] struct udt { int a{0}; explicit udt(int _a) : a(_a) { } udt() = default; int operator*() const { return a; } }; result<udt, std::exception_ptr> res(std::make_exception_ptr(std::runtime_error("hello"))); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [exception_ptr] return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/finale.cpp
/* Example of how to marshall Outcomes at namespace boundaries (C) 2017-2020 Niall Douglas <http://www.nedproductions.biz/> (11 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #if __has_include("quickcpplib/string_view.hpp") #include "quickcpplib/string_view.hpp" #else #include "../../../include/outcome/quickcpplib/include/quickcpplib/string_view.hpp" #endif #include <cstring> // for memcpy #if __has_include(<filesystem>) && (__cplusplus >= 201700 || _HAS_CXX17) #include <filesystem> namespace filesystem = std::filesystem; #else #include <experimental/filesystem> namespace filesystem = std::experimental::filesystem; #endif //! [httplib] // This is some standalone library implementing high level HTTP namespace httplib { // These are the error code that this HTTP library can return enum class status_code { success = 0, // not the HTTP success code of 200 // A subset of all HTTP status codes for brevity bad_request = 400, access_denied = 401, logon_failed = 402, forbidden = 403, not_found = 404, internal_error = 500 }; // This is the error type that this HTTP library can return struct failure { status_code status{status_code::success}; std::string url{}; // The failing URL }; // Localise a result implementation to this library, holding // the logic error of incorrect observation to mean program // termination. template <class T> using result = // OUTCOME_V2_NAMESPACE::result<T, failure, OUTCOME_V2_NAMESPACE::policy::terminate>; /* Performs a HTTP GET on the url, returning the body if successful, a failure with status_code if unsuccessful at the HTTP level, or a C++ exception throw if something catastrophic happened e.g. bad_alloc */ result<std::string> get(std::string url); } // namespace httplib //! [httplib] namespace httplib { result<std::string> get(std::string url) { (void) url; #if 1 return "hello world"; #else return failure{status_code::not_found, url}; #endif } } // namespace httplib namespace filelib { using QUICKCPPLIB_NAMESPACE::string_view::string_view; using filesystem::filesystem_error; using filesystem::path; } // namespace filelib namespace app { using QUICKCPPLIB_NAMESPACE::string_view::string_view; } //! [filelib] // You may remember this from the tutorial section on Custom Payloads namespace filelib { // Error code + paths related to a failure. Also causes ADL discovery // to check this namespace. struct failure_info { std::error_code ec; path path1{}, path2{}; }; // Tell Outcome that failure_info is to be treated as a std::error_code inline const std::error_code &make_error_code(const failure_info &fi) { return fi.ec; } // Tell Outcome that no-value observation should throw a custom exception inline void outcome_throw_as_system_error_with_payload(failure_info fi) { // If the error code is not filesystem related e.g. ENOMEM, throw that // as a standard STL exception. OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(fi.ec); // Throw the exact same filesystem_error exception which the throwing // copy_file() edition does. throw filesystem_error(fi.ec.message(), std::move(fi.path1), std::move(fi.path2), fi.ec); } // Localise a result implementation specific to this namespace. template <class T> using result = OUTCOME_V2_NAMESPACE::result<T, failure_info>; // Writes a chunk of data to some file. Returns bytes written, or // failure_info. Never throws exceptions. result<size_t> write_file(string_view chunk) noexcept; } // namespace filelib //! [filelib] namespace filelib { result<size_t> write_file(string_view chunk) noexcept { (void) chunk; return failure_info{make_error_code(std::errc::no_space_on_device), "somepath"}; } } // namespace filelib //! [tidylib] // There actually is a library for tidying HTML into XHTML called HTMLTidy // See http://www.html-tidy.org/ // HTMLTidy is actually a great tool for dealing with 1990s-era tag soup // HTML, I highly recommend it. // This isn't the API for Tidy, but let's assume it's a C library returning // errno domained error codes. out must be freed with free() after use. extern "C" int tidy_html(char **out, size_t *outlen, const char *in, size_t inlen); //! [tidylib] extern "C" int tidy_html(char **out, size_t *outlen, const char *in, size_t inlen) { #if 1 *out = (char *) malloc(inlen + 1); memcpy(*out, in, inlen + 1); *outlen = inlen; return 0; #else // return ENOMEM; return EROFS; #endif } //! [app] // This is the namespace of the application which is connecting together the httplib, // filelib and tidylib libraries into a solution. namespace app { // Create an ADL bridge so copy/move hooks will be searched for in this namespace struct error_code : public std::error_code { // passthrough using std::error_code::error_code; error_code() = default; error_code(std::error_code ec) : std::error_code(ec) { } }; // Localise an outcome implementation for this namespace template <class T> using outcome = // OUTCOME_V2_NAMESPACE::outcome<T, error_code /*, std::exception_ptr */>; using OUTCOME_V2_NAMESPACE::success; } // namespace app //! [app] //! [app_map_httplib1] namespace app { // Specialise an exception type for httplib errors struct httplib_error : std::runtime_error { // passthrough using std::runtime_error::runtime_error; httplib_error(httplib::failure _failure, std::string msg) : std::runtime_error(std::move(msg)) , failure(std::move(_failure)) { } // the original failure httplib::failure failure; }; // Type erase httplib::result<U> into a httplib_error exception ptr template <class U> // inline std::exception_ptr make_httplib_exception(const httplib::result<U> &src) { std::string str("httplib failed with error "); switch(src.error().status) { case httplib::status_code::success: str.append("success"); break; case httplib::status_code::bad_request: str.append("bad request"); break; case httplib::status_code::access_denied: str.append("access denied"); break; case httplib::status_code::logon_failed: str.append("logon failed"); break; case httplib::status_code::forbidden: str.append("forbidden"); break; case httplib::status_code::not_found: str.append("not found"); break; case httplib::status_code::internal_error: str.append("internal error"); break; } str.append(" [url was "); str.append(src.error().url); str.append("]"); return std::make_exception_ptr(httplib_error(src.error(), std::move(str))); } } // namespace app //! [app_map_httplib1] //! [app_map_httplib2] // Inject custom ValueOrError conversion OUTCOME_V2_NAMESPACE_BEGIN namespace convert { // Provide custom ValueOrError conversion from // httplib::result<U> into any app::outcome<T> template <class T, class U> // struct value_or_error<app::outcome<T>, httplib::result<U>> { // False to indicate that this converter wants `result`/`outcome` // to NOT reject all other `result` static constexpr bool enable_result_inputs = true; // False to indicate that this converter wants `outcome` to NOT // reject all other `outcome` static constexpr bool enable_outcome_inputs = true; template <class X, // typename = std::enable_if_t<std::is_same<httplib::result<U>, std::decay_t<X>>::value // && std::is_constructible<T, U>::value>> // constexpr app::outcome<T> operator()(X &&src) { // Forward any successful value, else synthesise an exception ptr return src.has_value() ? // app::outcome<T>{std::forward<X>(src).value()} // : app::outcome<T>{app::make_httplib_exception(std::forward<X>(src))}; } }; } // namespace convert OUTCOME_V2_NAMESPACE_END //! [app_map_httplib2] namespace app { static outcome<int> test_value_or_error2 = OUTCOME_V2_NAMESPACE::convert::value_or_error<outcome<int>, httplib::result<int>>{}(httplib::result<int>{5}); static outcome<int> test_value_or_error3(httplib::result<int>{5}); } // namespace app //! [app_map_filelib] // Inject custom ValueOrError conversion OUTCOME_V2_NAMESPACE_BEGIN namespace convert { // Provide custom ValueOrError conversion from filelib::result<U> // into any app::outcome<T> template <class T, class U> // struct value_or_error<app::outcome<T>, filelib::result<U>> { // True to indicate that this converter wants `result`/`outcome` // to NOT reject all other `result` static constexpr bool enable_result_inputs = true; // False to indicate that this converter wants `outcome` to NOT // reject all other `outcome` static constexpr bool enable_outcome_inputs = true; template <class X, // typename = std::enable_if_t<std::is_same<filelib::result<U>, std::decay_t<X>>::value // && std::is_constructible<T, U>::value>> // constexpr app::outcome<T> operator()(X &&src) { // Forward any successful value if(src.has_value()) { return {std::forward<X>(src).value()}; } // Synthesise a filesystem_error, exactly as if someone had // called src.value() auto &fi = src.error(); OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(fi.ec); // might throw return {std::make_exception_ptr( // filelib::filesystem_error(fi.ec.message(), std::move(fi.path1), std::move(fi.path2), fi.ec))}; } }; } // namespace convert OUTCOME_V2_NAMESPACE_END //! [app_map_filelib] //! [app_map_tidylib] namespace app { // Specialise an exception type for tidylib errors struct tidylib_error : std::system_error { // passthrough using std::system_error::system_error; tidylib_error() = default; explicit tidylib_error(int c) : std::system_error(c, std::generic_category()) { } }; // Create a C++ invoking wrapper for the tidylib C API, modifying data with the returned data, // returing a unique_ptr to release storage on scope exit. struct call_free { template <class T> void operator()(T *p) { ::free(p); } }; inline outcome<std::unique_ptr<char, call_free>> tidy_html(string_view &data) { char *out = nullptr; size_t outlen = 0; int errcode = ::tidy_html(&out, &outlen, data.data(), data.size()); if(errcode != 0) { // If the error code matches a standard STL exception, throw as that. OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(std::error_code(errcode, std::generic_category())); // Otherwise wrap the error code into a tidylib_error exception throw return std::make_exception_ptr(tidylib_error(errcode)); } // Reset input view to tidied html data = string_view(out, outlen); // Return a unique ptr to release storage on scope exit return std::unique_ptr<char, call_free>(out); } } // namespace app //! [app_map_tidylib] //! [app_go] namespace app { // A markup function to indicate when we are ValueOrError converting template <class T> inline outcome<typename T::value_type> ext(T &&v) { // return outcome<typename T::value_type>(std::move(v)); } outcome<void> go() // NOT noexcept, this can throw STL exceptions e.g. bad_alloc { // Note that explicit construction is required when converting between differing types // of outcome and result. This makes it explicit what you intend to do as conversion // may be a lot more expensive than moves. // Try to GET this URL. If an unsuccessful HTTP status is returned, serialise a string // containing a description of the HTTP status code and the URL which failed, storing // that into a httplib_error exception type which is stored as an exception ptr. The // TRY operation below will return that exception ptr to be rethrown in the caller. // Otherwise the fetched data is returned in a std::string data. OUTCOME_TRY(auto data, ext(httplib::get("http://www.nedproductions.biz/"))); string_view data_view(data); // HTML tidy the fetched data. If the C library fails due to an error corresponding to // a standard library exception type, throw that. Otherwise, synthesise an exception // ptr of type tidylib_error which stores the error code returned in an error code with // generic category (i.e. errno domain). // TRY operation below will return that exception ptr to be rethrown in the caller. // Otherwise the tidied data is returned into holdmem, with the string view updated to // point at the tidied data. OUTCOME_TRY(auto holdmem, ext(tidy_html(data_view))); // Write the tidied data to some file. If the write fails, synthesise a filesystem_error // exception ptr exactly as if one called filelib::write_file(data_view).value(). OUTCOME_TRY(auto written, ext(filelib::write_file(data_view))); return success(); } } // namespace app //! [app_go] int main() { try { app::go().value(); } catch(const filelib::filesystem_error &e) { std::cerr << "Exception thrown, " << e.what() // << " (path1 = " << e.path1() << ", path2 = " << e.path2() << ")" // << std::endl; return 1; } catch(const std::exception &e) { std::cerr << "Exception thrown, " << e.what() << std::endl; return 1; } return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/foreign_try.cpp
/* Example of Outcome try used with foreign object (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> namespace outcome = OUTCOME_V2_NAMESPACE; //! [foreign_type] enum Errc { kBadValue }; template <class T, class E = Errc> struct ForeignExpected { T Value; E Error; int IsErrored; ForeignExpected(T v) : Value(v) , Error() , IsErrored(0) { } ForeignExpected(E e) : Value() , Error(e) , IsErrored(1) { } }; //! [foreign_type] //! [tell_outcome] OUTCOME_V2_NAMESPACE_BEGIN template <class T, class E> // inline bool try_operation_has_value(const ForeignExpected<T, E> &v) { return 0 == v.IsErrored; } template <class T, class E> // inline auto try_operation_return_as(const ForeignExpected<T, E> &v) { switch(v.Error) { case kBadValue: return failure(make_error_code(std::errc::argument_out_of_domain)); } abort(); } template <class T, class E> // inline auto try_operation_extract_value(const ForeignExpected<T, E> &v) { return v.Value; } OUTCOME_V2_NAMESPACE_END //! [tell_outcome] //! [functions] ForeignExpected<int> old_code(int a) // old code { if(0 == a) return kBadValue; return a; } outcome::result<int> new_code(int a) // new code { OUTCOME_TRY(auto x, old_code(a)); return x; } //! [functions] int main() { //! [example] auto printresult = [](const char *desc, auto x) { if(x) { std::cout << desc << " returns successful " << x.value() << std::endl; } else { std::cout << desc << " returns failure " << x.error().message() << std::endl; } }; printresult("\nnew_code(5)", new_code(5)); printresult("\nnew_code(0)", new_code(0)); //! [example] return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/outcome_payload.cpp
/* Documentation snippet (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (8 commits) File Created: Mar 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #if __has_include(<filesystem>) && (__cplusplus >= 201700 || _HAS_CXX17) #include <filesystem> namespace std_filesystem = std::filesystem; #else #include <experimental/filesystem> namespace std_filesystem = std::experimental::filesystem; #endif namespace outcome = OUTCOME_V2_NAMESPACE; namespace filesystem { using std_filesystem::path; bool copy_file(const path &from, const path &to) { return false; } bool copy_file(const path &from, const path &to, std::error_code &ec) { return false; } } namespace filesystem2 { using std_filesystem::path; using std_filesystem::filesystem_error; } //! [filesystem_api_problem] namespace filesystem { /*! Copies the file at path `from` to path `to`. \returns True if file was successfully copied. \throws On failure throws `filesystem_error(ec.message(), from, to, ec)` with `ec` being the error code reported by the operating system. */ bool copy_file(const path &from, const path &to); /*! Copies the file at path `from` to path `to`. \returns True if file was successfully copied. If false, `ec` is written with the error code reported by the operating system. \throws May throw an exception if there is some "catastrophic" failure e.g. failure to allocate memory. */ bool copy_file(const path &from, const path &to, std::error_code &ec); } //! [filesystem_api_problem] //! [filesystem_api_fixed] namespace filesystem2 { // Error code + paths related to a failure. Also causes ADL discovery to check this namespace. struct failure_info { std::error_code ec; path path1, path2; }; // Tell Outcome that failure_info is to be treated as a std::error_code inline const std::error_code &make_error_code(const failure_info &fi) { return fi.ec; } // Localise an outcome implementation specific to this namespace. Normally would just // be `result`, but for clarity we'll use `fs_result`. template <class T> using fs_result = outcome::result<T, failure_info>; /*! Copies the file at path `from` to path `to`. \returns Successful if file was successfully copied, otherwise the error code reported by the operating system plus a payload of the paths involved. \throws Never throws. */ fs_result<void> copy_file(const path &from, const path &to) noexcept; } //! [filesystem_api_fixed] namespace filesystem2 { fs_result<void> copy_file(const path &from, const path &to) noexcept { return failure_info{make_error_code(std::errc::no_such_file_or_directory), from, to}; } } //! [filesystem_api_custom_throw] namespace filesystem2 { // If we would like Outcome to do something other than the default action (see next // section), we can declare this ADL discovered free function to customise what // to do instead. // // Note that rvalue semantics are propagated internally by Outcome, so if the user // called .value() on a rvalued result, failure_info will be moved rather than // copied from the result. That means we can overload once with value semantics, // and not need to overload for lvalue and rvalue situations unless we really feel // we need to for some reason. inline void outcome_throw_as_system_error_with_payload(failure_info fi) { // If the error code is not filesystem related e.g. ENOMEM, throw that as a // standard STL exception. outcome::try_throw_std_exception_from_error(fi.ec); // Throw the exact same filesystem_error exception which the throwing copy_file() // edition does. throw filesystem_error(fi.ec.message(), std::move(fi.path1), // std::move(fi.path2), fi.ec); } } //! [filesystem_api_custom_throw] int main() { //! [filesystem_api_custom_throw_demo] // Non-throwing use case auto o = filesystem2::copy_file("dontexist", "alsodontexist"); if(!o) { std::cerr << "Copy file failed with error " << o.error().ec.message() // << " (path1 = " << o.error().path1 << ", path2 = " << o.error().path2 << ")" // << std::endl; } // Throwing use case try { // Try to observe the successful value, thus triggering default actions which invokes // our outcome_throw_as_system_error_with_payload() above which then throws filesystem_error // exactly like the Filesystem TS does for its throwing overload. filesystem2::copy_file("dontexist", "alsodontexist").value(); } catch(const filesystem2::filesystem_error &e) { std::cerr << "Copy file failed with exception " << e.what() // << " (path1 = " << e.path1() << ", path2 = " << e.path2() << ")" // << std::endl; } catch(const std::exception &e) { std::cerr << "Copy file failed with exception " << e.what() // << std::endl; } //! [filesystem_api_custom_throw_demo] return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/expected_implementation.cpp
/* Documentation snippet (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (7 commits) File Created: Mar 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome/outcome.hpp" #if(_HAS_CXX17 || __cplusplus >= 201700) //! [expected_implementation] /* Here is a fairly conforming implementation of P0323R3 `expected<T, E>` using `checked<T, E>`. It passes the reference test suite for P0323R3 at https://github.com/viboes/std-make/blob/master/test/expected/expected_pass.cpp with modifications only to move the test much closer to the P0323R3 Expected, as the reference test suite is for a much older proposed Expected. Known differences from P0323R3 in this implementation: - `T` and `E` cannot be the same type. - `E` must be default constructible. - No variant storage is implemented (note the Expected proposal does not actually require this). */ namespace detail { template <class T, class E> using expected_result = OUTCOME_V2_NAMESPACE::checked<T, E>; template <class T, class E> struct enable_default_constructor : public expected_result<T, E> { using base = expected_result<T, E>; using base::base; constexpr enable_default_constructor() : base{OUTCOME_V2_NAMESPACE::in_place_type<T>} { } }; template <class T, class E> using select_expected_base = std::conditional_t<std::is_default_constructible<T>::value, enable_default_constructor<T, E>, expected_result<T, E>>; } template <class T, class E> class expected : public detail::select_expected_base<T, E> { static_assert(!std::is_same<T, E>::value, "T and E cannot be the same in this expected implementation"); using base = detail::select_expected_base<T, E>; public: // Inherit base's constructors using base::base; expected() = default; // Expected takes in_place not in_place_type template <class... Args> constexpr explicit expected(std::in_place_t /*unused*/, Args &&... args) : base{OUTCOME_V2_NAMESPACE::in_place_type<T>, std::forward<Args>(args)...} { } // Expected always accepts a T even if ambiguous OUTCOME_TEMPLATE(class U) OUTCOME_TREQUIRES(OUTCOME_TPRED(std::is_constructible<T, U>::value)) constexpr expected(U &&v) : base{OUTCOME_V2_NAMESPACE::in_place_type<T>, std::forward<U>(v)} { } // Expected has an emplace() modifier template <class... Args> void emplace(Args &&... args) { *static_cast<base *>(this) = base{OUTCOME_V2_NAMESPACE::in_place_type<T>, std::forward<Args>(args)...}; } // Expected has a narrow operator* and operator-> constexpr const T &operator*() const & { return base::assume_value(); } constexpr T &operator*() & { return base::assume_value(); } constexpr const T &&operator*() const && { return base::assume_value(); } constexpr T &&operator*() && { return base::assume_value(); } constexpr const T *operator->() const { return &base::assume_value(); } constexpr T *operator->() { return &base::assume_value(); } // Expected has a narrow error() observer constexpr const E &error() const & { return base::assume_error(); } constexpr E &error() & { return base::assume_error(); } constexpr const E &&error() const && { return base::assume_error(); } constexpr E &error() && { return base::assume_error(); } }; template <class E> class expected<void, E> : public OUTCOME_V2_NAMESPACE::result<void, E, OUTCOME_V2_NAMESPACE::policy::throw_bad_result_access<E, void>> { using base = OUTCOME_V2_NAMESPACE::result<void, E, OUTCOME_V2_NAMESPACE::policy::throw_bad_result_access<E, void>>; public: // Inherit base constructors using base::base; // Expected has a narrow operator* and operator-> constexpr void operator*() const { base::assume_value(); } constexpr void operator->() const { base::assume_value(); } }; template <class E> using unexpected = OUTCOME_V2_NAMESPACE::failure_type<E>; template <class E> unexpected<E> make_unexpected(E &&arg) { return OUTCOME_V2_NAMESPACE::failure<E>(std::forward<E>(arg)); } template <class E, class... Args> unexpected<E> make_unexpected(Args &&... args) { return OUTCOME_V2_NAMESPACE::failure<E>(std::forward<Args>(args)...); } template <class E> using bad_expected_access = OUTCOME_V2_NAMESPACE::bad_result_access_with<E>; //! [expected_implementation] #endif int main() { return 0; }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/using_result.cpp
/* Documentation snippet (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (7 commits), Andrzej Krzemienski <[email protected]> (4 commits) and Krzemienski <[email protected]> (2 commits) File Created: Mar 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <algorithm> #include <ctype.h> #include <string> #include <system_error> //! [namespace] namespace outcome = OUTCOME_V2_NAMESPACE; //! [namespace] //! [convert_decl] outcome::result<int> convert(const std::string& str) noexcept; //! [convert_decl] //! [enum] enum class ConversionErrc { Success = 0, // 0 should not represent an error EmptyString = 1, // (for rationale, see tutorial on error codes) IllegalChar = 2, TooLong = 3, }; // all boilerplate necessary to plug ConversionErrc // into std::error_code framework //! [enum] std::error_code make_error_code(ConversionErrc); namespace std { template <> struct is_error_code_enum<ConversionErrc> : true_type {}; } //! [convert] outcome::result<int> convert(const std::string& str) noexcept { if (str.empty()) return ConversionErrc::EmptyString; if (!std::all_of(str.begin(), str.end(), ::isdigit)) return ConversionErrc::IllegalChar; if (str.length() > 9) return ConversionErrc::TooLong; return atoi(str.c_str()); } //! [convert] namespace { struct ConversionErrorCategory : std::error_category { const char* name() const noexcept override { return "bad-convert"; } std::string message(int ev) const override; }; std::string ConversionErrorCategory::message(int ev) const { switch (static_cast<ConversionErrc>(ev)) { case ConversionErrc::Success: return "conversion successful"; case ConversionErrc::EmptyString: return "empty string provided"; case ConversionErrc::IllegalChar: return "non-digit char provided"; case ConversionErrc::TooLong: return "converted int would be too large"; } return "(UNCHARTED)"; } const ConversionErrorCategory globalConversionErrorCategory {}; } std::error_code make_error_code(ConversionErrc e) { return std::error_code{static_cast<int>(e), globalConversionErrorCategory}; } void explicit_construction() { //! [explicit] outcome::result<int> r {outcome::in_place_type<std::error_code>, ConversionErrc::EmptyString}; outcome::result<int> s {outcome::in_place_type<int>, 1}; //! [explicit] } void factory_construction() { //! [factory] outcome::result<int> r = outcome::failure(ConversionErrc::EmptyString); outcome::result<int> s = outcome::success(1); //! [factory] } struct BigInt { static outcome::result<BigInt> fromString(const std::string& s); explicit BigInt(const std::string&) {} BigInt half() const { return BigInt{""}; } friend std::ostream& operator<<(std::ostream& o, const BigInt&) { return o << "big int half"; } }; //! [from_string] /*static*/ outcome::result<BigInt> BigInt::fromString(const std::string& s) //! [from_string] { return BigInt{s}; } //! [half_decl] outcome::result<void> print_half(const std::string& text); //! [half_decl] //! [half_impl] outcome::result<void> print_half(const std::string& text) { if (outcome::result<int> r = convert(text)) // #1 { std::cout << (r.value() / 2) << std::endl; // #2 } else { if (r.error() == ConversionErrc::TooLong) // #3 { OUTCOME_TRY(auto i, BigInt::fromString(text)); // #4 std::cout << i.half() << std::endl; } else { return r.as_failure(); // #5 } } return outcome::success(); // #6 } //! [half_impl] //! [tryv] outcome::result<void> test() { OUTCOME_TRY ((print_half("2"))); OUTCOME_TRY ((print_half("X"))); OUTCOME_TRY ((print_half("4"))); // will not execute return outcome::success(); } //! [tryv] int main() { if (outcome::result<void> r = print_half("1299999999999999999999999999")) { std::cout << "ok" << std::endl; } else { std::cout << r.error() << std::endl; } (void)test(); }
0
repos/outcome/doc/src
repos/outcome/doc/src/snippets/policies.cpp
/* Documentation snippet (C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits) and Andrzej Krzemienski <[email protected]> (1 commit) File Created: Mar 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" namespace outcome = OUTCOME_V2_NAMESPACE; //! [abort_policy] struct abort_policy : outcome::policy::base { template <class Impl> static constexpr void wide_value_check(Impl &&self) { if(!base::_has_value(std::forward<Impl>(self))) std::abort(); } template <class Impl> static constexpr void wide_error_check(Impl &&self) { if(!base::_has_error(std::forward<Impl>(self))) std::abort(); } template <class Impl> static constexpr void wide_exception_check(Impl &&self) { if(!base::_has_exception(std::forward<Impl>(self))) std::abort(); } }; //! [abort_policy] //! [throwing_policy] template <typename T, typename EC, typename EP> struct throwing_policy : outcome::policy::base { static_assert(std::is_convertible<EC, std::error_code>::value, "only EC = error_code"); template <class Impl> static constexpr void wide_value_check(Impl &&self) { if(!base::_has_value(std::forward<Impl>(self))) { if(base::_has_error(std::forward<Impl>(self))) throw std::system_error(base::_error(std::forward<Impl>(self))); else std::rethrow_exception(base::_exception<T, EC, EP, throwing_policy>(std::forward<Impl>(self))); } } template <class Impl> static constexpr void wide_error_check(Impl &&self) { if(!base::_has_error(std::forward<Impl>(self))) { if(base::_has_exception(std::forward<Impl>(self))) std::rethrow_exception(base::_exception<T, EC, EP, throwing_policy>(std::forward<Impl>(self))); else base::_make_ub(std::forward<Impl>(self)); } } template <class Impl> static constexpr void wide_exception_check(Impl &&self) { if(!base::_has_exception(std::forward<Impl>(self))) base::_make_ub(std::forward<Impl>(self)); } }; //! [throwing_policy] //! [outcome_spec] template <typename T> using strictOutcome = // outcome::basic_outcome<T, std::error_code, std::exception_ptr, abort_policy>; //! [outcome_spec] template <typename T, typename EC = std::error_code> using throwingOutcome = // outcome::basic_outcome<T, EC, std::exception_ptr, throwing_policy<T, EC, std::exception_ptr>>; int main() { try { throwingOutcome<int> i = std::error_code{}; i.value(); // throws assert(false); } catch(std::system_error const &) { } strictOutcome<int> i = 1; assert(i.value() == 1); i.error(); // calls abort() }