blob: b628bbd85c85284defdf873070cbf90015f3e529 [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
47
Ewout van Bekkum0d04fbc2020-07-23 15:58:04 -070048.. warning::
49
50 Be careful not to use larger types by value as this can quickly consume
51 unnecessary stack.
Alexei Frolov41b32d32019-11-13 17:22:03 -080052
53.. warning::
54
55 This module is experimental. Its impact on code size and stack usage has not
56 yet been profiled. Use at your own risk.
Ewout van Bekkum0d04fbc2020-07-23 15:58:04 -070057
58Compatibility
59=============
60Works with C++11, but some features require C++17.
Alexei Frolovde3c2a12020-08-31 10:57:25 -070061
62Size report
63===========
64The table below showcases the difference in size between functions returning a
65Status with an output pointer, and functions returning a Result, in various
66situations.
67
68Note that these are simplified examples which do not necessarily reflect the
69usage of Result in real code. Make sure to always run your own size reports to
70check if Result is suitable for you.
71
72.. include:: result_size