blob: 02c94757f310c7c9b48762591fd3906e7b2c12c1 [file] [log] [blame]
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -07001.. _module-pw_result:
Alexei Frolov41b32d32019-11-13 17:22:03 -08002
3---------
4pw_result
5---------
Ewout van Bekkum0d04fbc2020-07-23 15:58:04 -07006``pw::Result`` is a convenient wrapper around returning a Status along side some
7data when the status is OK. This is meant for returning lightweight result
8types or references to larger results.
9
Ewout van Bekkum3a260a22021-04-20 13:52:27 -070010``pw::Result`` is compatible with ``PW_TRY`` and ``PW_TRY_ASSIGN``, for example:
11
12.. code-block:: cpp
13
14 #include "pw_status/try.h"
15 #include "pw_result/result.h"
16
17 pw::Result<int> GetAnswer(); // Example function.
18
19 pw::Status UseAnswer() {
20 const pw::Result<int> answer = GetAnswer();
21 if (!answer.ok()) {
22 return answer.status();
23 }
24 if (answer.value() == 42) {
25 WhatWasTheUltimateQuestion();
26 }
27 return pw::OkStatus();
28 }
29
30 pw::Status UseAnswerWithTry() {
31 const pw::Result<int> answer = GetAnswer();
32 PW_TRY(answer.status());
33 if (answer.value() == 42) {
34 WhatWasTheUltimateQuestion();
35 }
36 return pw::OkStatus();
37 }
38
39 pw::Status UseAnswerWithTryAssign() {
40 PW_TRY_ASSIGN(const int answer, GetAnswer());
41 if (answer == 42) {
42 WhatWasTheUltimateQuestion();
43 }
44 return pw::OkStatus();
45 }
46
Adam MacBeth518f7c12021-07-30 19:06:12 +000047``pw::Result`` can be used to directly access the contained type:
48
49.. code-block:: cpp
50
51 #include "pw_result/result.h"
52
53 pw::Result<Foo> foo = TryCreateFoo();
54 if (foo.ok()) {
55 foo->DoBar();
56 }
57
58or in C++17:
59
60.. code-block:: cpp
61
62 if (pw::Result<Foo> foo = TryCreateFoo(); foo.ok()) {
63 foo->DoBar();
64 }
65
66See `Abseil's StatusOr <https://abseil.io/tips/181>`_ for guidance on using a
67similar type.
Ewout van Bekkum3a260a22021-04-20 13:52:27 -070068
Ewout van Bekkum0d04fbc2020-07-23 15:58:04 -070069.. warning::
70
71 Be careful not to use larger types by value as this can quickly consume
72 unnecessary stack.
Alexei Frolov41b32d32019-11-13 17:22:03 -080073
74.. warning::
75
76 This module is experimental. Its impact on code size and stack usage has not
77 yet been profiled. Use at your own risk.
Ewout van Bekkum0d04fbc2020-07-23 15:58:04 -070078
79Compatibility
80=============
81Works with C++11, but some features require C++17.
Alexei Frolovde3c2a12020-08-31 10:57:25 -070082
83Size report
84===========
85The table below showcases the difference in size between functions returning a
86Status with an output pointer, and functions returning a Result, in various
87situations.
88
89Note that these are simplified examples which do not necessarily reflect the
90usage of Result in real code. Make sure to always run your own size reports to
91check if Result is suitable for you.
92
93.. include:: result_size