pw_result: add PW_TRY_ASSIGN support
Adds PW_TRY_ASSIGN to pw::Result<T>.
Change-Id: I7cc73c14f7f36bc048098abd17f543b8ddf252af
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/41900
Reviewed-by: Wyatt Hepler <hepler@google.com>
Pigweed-Auto-Submit: Ewout van Bekkum <ewout@google.com>
Commit-Queue: Auto-Submit <auto-submit@pigweed.google.com.iam.gserviceaccount.com>
diff --git a/pw_result/docs.rst b/pw_result/docs.rst
index bfc37cd..b628bbd 100644
--- a/pw_result/docs.rst
+++ b/pw_result/docs.rst
@@ -7,6 +7,44 @@
data when the status is OK. This is meant for returning lightweight result
types or references to larger results.
+``pw::Result`` is compatible with ``PW_TRY`` and ``PW_TRY_ASSIGN``, for example:
+
+.. code-block:: cpp
+
+ #include "pw_status/try.h"
+ #include "pw_result/result.h"
+
+ pw::Result<int> GetAnswer(); // Example function.
+
+ pw::Status UseAnswer() {
+ const pw::Result<int> answer = GetAnswer();
+ if (!answer.ok()) {
+ return answer.status();
+ }
+ if (answer.value() == 42) {
+ WhatWasTheUltimateQuestion();
+ }
+ return pw::OkStatus();
+ }
+
+ pw::Status UseAnswerWithTry() {
+ const pw::Result<int> answer = GetAnswer();
+ PW_TRY(answer.status());
+ if (answer.value() == 42) {
+ WhatWasTheUltimateQuestion();
+ }
+ return pw::OkStatus();
+ }
+
+ pw::Status UseAnswerWithTryAssign() {
+ PW_TRY_ASSIGN(const int answer, GetAnswer());
+ if (answer == 42) {
+ WhatWasTheUltimateQuestion();
+ }
+ return pw::OkStatus();
+ }
+
+
.. warning::
Be careful not to use larger types by value as this can quickly consume