mirror of
https://github.com/mozilla/gecko-dev.git
synced 2024-10-07 09:54:42 +00:00
Bug 1550108 - Add mapErr method to Result r=froydnj
Adds an explicit error mapping function to Result, to simplify using MOZ_TRY... macros. Differential Revision: https://phabricator.services.mozilla.com/D47466 --HG-- extra : moz-landing-system : lando
This commit is contained in:
parent
076597dbc2
commit
d27f7199e1
@ -9,6 +9,7 @@
|
||||
#ifndef mozilla_Result_h
|
||||
#define mozilla_Result_h
|
||||
|
||||
#include <type_traits>
|
||||
#include "mozilla/Alignment.h"
|
||||
#include "mozilla/Assertions.h"
|
||||
#include "mozilla/Attributes.h"
|
||||
@ -433,6 +434,37 @@ class MOZ_MUST_USE_TYPE Result final {
|
||||
return isOk() ? RetResult(f(unwrap())) : RetResult(unwrapErr());
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a function V -> W over this result's error variant. If this result is
|
||||
* a success, do not invoke the function and move the success over.
|
||||
*
|
||||
* Mapping over error values invokes the function to produce a new error
|
||||
* value:
|
||||
*
|
||||
* // Map Result<V, int> to another Result<V, int>
|
||||
* Result<V, int> res(5);
|
||||
* Result<V, int> res2 = res.mapErr([](int x) { return x * x; });
|
||||
* MOZ_ASSERT(res2.unwrapErr() == 25);
|
||||
*
|
||||
* // Map Result<V, const char*> to Result<V, size_t>
|
||||
* Result<V, const char*> res("hello, map!");
|
||||
* Result<size_t, E> res2 = res.mapErr(strlen);
|
||||
* MOZ_ASSERT(res2.unwrapErr() == 11);
|
||||
*
|
||||
* Mapping over a success does not invoke the function and copies the error:
|
||||
*
|
||||
* Result<int, V> res(5);
|
||||
* MOZ_ASSERT(res.isOk());
|
||||
* Result<int, W> res2 = res.mapErr([](V v) { ... });
|
||||
* MOZ_ASSERT(res2.isOk());
|
||||
* MOZ_ASSERT(res2.unwrap() == 5);
|
||||
*/
|
||||
template <typename F>
|
||||
auto mapErr(F f) -> Result<V, std::result_of_t<F(E)>> {
|
||||
using RetResult = Result<V, std::result_of_t<F(E)>>;
|
||||
return isOk() ? RetResult(unwrap()) : RetResult(f(unwrapErr()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a function V -> Result<W, E>, apply it to this result's success value
|
||||
* and return its result. If this result is an error value, then return a
|
||||
|
Loading…
Reference in New Issue
Block a user