Wyatt Hepler | f9fb90f | 2020-09-30 18:59:33 -0700 | [diff] [blame] | 1 | .. _module-pw_result: |
Alexei Frolov | 41b32d3 | 2019-11-13 17:22:03 -0800 | [diff] [blame] | 2 | |
| 3 | --------- |
| 4 | pw_result |
| 5 | --------- |
Ewout van Bekkum | 0d04fbc | 2020-07-23 15:58:04 -0700 | [diff] [blame] | 6 | ``pw::Result`` is a convenient wrapper around returning a Status along side some |
| 7 | data when the status is OK. This is meant for returning lightweight result |
| 8 | types or references to larger results. |
| 9 | |
Ewout van Bekkum | 3a260a2 | 2021-04-20 13:52:27 -0700 | [diff] [blame^] | 10 | ``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 Bekkum | 0d04fbc | 2020-07-23 15:58:04 -0700 | [diff] [blame] | 48 | .. warning:: |
| 49 | |
| 50 | Be careful not to use larger types by value as this can quickly consume |
| 51 | unnecessary stack. |
Alexei Frolov | 41b32d3 | 2019-11-13 17:22:03 -0800 | [diff] [blame] | 52 | |
| 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 Bekkum | 0d04fbc | 2020-07-23 15:58:04 -0700 | [diff] [blame] | 57 | |
| 58 | Compatibility |
| 59 | ============= |
| 60 | Works with C++11, but some features require C++17. |
Alexei Frolov | de3c2a1 | 2020-08-31 10:57:25 -0700 | [diff] [blame] | 61 | |
| 62 | Size report |
| 63 | =========== |
| 64 | The table below showcases the difference in size between functions returning a |
| 65 | Status with an output pointer, and functions returning a Result, in various |
| 66 | situations. |
| 67 | |
| 68 | Note that these are simplified examples which do not necessarily reflect the |
| 69 | usage of Result in real code. Make sure to always run your own size reports to |
| 70 | check if Result is suitable for you. |
| 71 | |
| 72 | .. include:: result_size |