载入中...
搜索中...
未找到
Result.h
浏览该文件的文档.
1#pragma once
2
8#include "common/Status.h"
9
10#include <exception>
11#include <functional>
12#include <optional>
13#include <string>
14#include <string_view>
15#include <type_traits>
16#include <utility>
17#include <vector>
18
19#if !defined(ZEROERR_NO_ASSERT)
20#define EV_DETAIL_RESULT_ASSERT(cond, message) \
21 ::eve::detail::checkResultInvariant((cond), #cond, __FILE__, __LINE__, (message))
22#else
23#define EV_DETAIL_RESULT_ASSERT(cond, message) ((void)0)
24#endif
25
26namespace eve {
27namespace detail {
28
39EVENGINE_API_FOUNDATION void checkResultInvariant(bool condition, const char* expression, const char* file,
40 unsigned line, const char* message);
41
52[[noreturn]] EVENGINE_API_FOUNDATION void failResultExpectation(const Status& status, std::string_view message,
53 const char* file, unsigned line,
54 bool assertionsEnabled);
55
66public:
68 ResultObservation() noexcept = default;
69
71 ResultObservation& operator=(const ResultObservation&) = delete;
72
74 struct InactiveTag {};
75 explicit ResultObservation(InactiveTag) noexcept { mustObserve_ = false; }
76
77#if !defined(ZEROERR_NO_ASSERT)
78 ~ResultObservation() noexcept(false) {
79 const bool observationSatisfied = !mustObserve_ || observed_;
80 EV_DETAIL_RESULT_ASSERT(observationSatisfied,
81 "Result destroyed without checking; inspect it or call ignore() explicitly");
82 }
83#else
84 ~ResultObservation() noexcept = default;
85#endif
86
87protected:
89 void observe() const noexcept { observed_ = true; }
90
92 template <bool AssertionsEnabled>
94 if constexpr (AssertionsEnabled) {
95 const bool observationSatisfied = !mustObserve_ || observed_;
96 checkResultInvariant(observationSatisfied, "!mustObserve_ || observed_", __FILE__, __LINE__,
97 "move assignment would overwrite an unchecked Result");
98 }
99 }
100
103 observed_ = other.observed_;
104 mustObserve_ = other.mustObserve_;
105 other.mustObserve_ = false;
106 }
107
109 void disarmObservation() noexcept { mustObserve_ = false; }
110
112 void requireObservation() noexcept {
113 observed_ = false;
114 mustObserve_ = true;
115 }
116
117private:
118 // Do not condition these fields on ZEROERR_NO_ASSERT. Public Result<T>
119 // values cross static/shared-library boundaries whose assertion policy may
120 // intentionally differ from the consumer (notably Release unit tests).
121 mutable bool observed_ = false;
122 bool mustObserve_ = true;
123};
124
125template <class T>
126using ResultReturn = std::invoke_result_t<T>;
127
135template <class From, class To>
136concept ResultConstConversion = std::is_same_v<To, const From> ||
137 (std::is_pointer_v<From> && std::is_same_v<To, const std::remove_pointer_t<From>*>);
138
145template <class T, class U>
147void moveAssignOptional(std::optional<T>& destination, std::optional<U>&& source) {
148 destination.reset();
149 if (source.has_value()) destination.emplace(std::move(*source));
150}
151
152} // namespace detail
153
174template <class T>
176class [[nodiscard("Result must be checked or explicitly ignored")]] Result : private detail::ResultObservation {
177 static_assert(!std::is_reference_v<T>, "Result<T> cannot hold a reference; use a handle or value");
178 static_assert(!std::is_void_v<T>, "Result<void> has a dedicated specialization");
179
180 template <class U>
181 friend class Result;
182
183public:
185 static Result success(T value) { return Result(Status::success(), std::optional<T>(std::move(value))); }
186
190 EV_DETAIL_RESULT_ASSERT(status.isSuccess(), "Result::success requires a successful Status");
192 return Result(std::move(status), std::optional<T>(std::move(value)));
193 }
194
198 EV_DETAIL_RESULT_ASSERT(status.isFailure(), "Result::failure requires a failure Status");
200 return Result(std::move(status), std::nullopt);
201 }
202
204 static Result failure(Diagnostic diagnostic) { return failure(Status::failure(std::move(diagnostic))); }
205
206 Result(const Result&) = delete;
207 Result& operator=(const Result&) = delete;
208
210 Result(Result&& other)
212 : detail::ResultObservation(detail::ResultObservation::InactiveTag{}),
214 status_(std::move(other.status_)),
216 value_(std::move(other.value_)) {
218 adoptObservationFrom(other);
219 }
220
227#if !defined(ZEROERR_NO_ASSERT)
228 template <bool AssertionsEnabled = true>
229#else
230 template <bool AssertionsEnabled = false>
231#endif
233 if (this == &other) return *this;
235 assertCanBeOverwritten<AssertionsEnabled>();
236 status_ = std::move(other.status_);
238 detail::moveAssignOptional(value_, std::move(other.value_));
240 adoptObservationFrom(other);
241 return *this;
242 }
243
249 template <class U>
254 : detail::ResultObservation(detail::ResultObservation::InactiveTag{}),
256 status_(std::move(other.status_)),
258 value_(std::optional<T>(std::move(other.value_))) {
260 adoptObservationFrom(other);
261 }
262
267#if !defined(ZEROERR_NO_ASSERT)
268 template <class U, bool AssertionsEnabled = true>
269#else
270 template <class U, bool AssertionsEnabled = false>
271#endif
276 assertCanBeOverwritten<AssertionsEnabled>();
277 status_ = std::move(other.status_);
279 detail::moveAssignOptional(value_, std::move(other.value_));
281 adoptObservationFrom(other);
282 return *this;
283 }
284
286 bool ok() const noexcept {
288 observe();
289 return status_.isSuccess() && value_.has_value();
290 }
291
293 bool hasValue() const noexcept {
295 observe();
296 return status_.isSuccess() && value_.has_value();
297 }
298
300 const Status& status() const noexcept {
302 observe();
303 return status_;
304 }
305
307 StatusCode code() const noexcept {
309 observe();
310 return status_.code();
311 }
312
314 const std::vector<Diagnostic>& diagnostics() const noexcept {
316 observe();
317 return status_.diagnostics();
318 }
319
329 const Diagnostic* error() const noexcept {
331 observe();
332 return status_.primaryDiagnostic();
333 }
334
336 explicit operator bool() const noexcept { return ok(); }
337
339 const T& value() const& {
341 observe();
342 [[maybe_unused]] const bool hasSuccessfulValue = status_.isSuccess() && value_.has_value();
344 EV_DETAIL_RESULT_ASSERT(hasSuccessfulValue, "Result::value requires a successful Result with a value");
345 return value_.value();
346 }
347
349 T& value() & {
351 observe();
352 [[maybe_unused]] const bool hasSuccessfulValue = status_.isSuccess() && value_.has_value();
354 EV_DETAIL_RESULT_ASSERT(hasSuccessfulValue, "Result::value requires a successful Result with a value");
355 return value_.value();
356 }
357
359 T&& value() && {
361 observe();
362 [[maybe_unused]] const bool hasSuccessfulValue = status_.isSuccess() && value_.has_value();
364 EV_DETAIL_RESULT_ASSERT(hasSuccessfulValue, "Result::value requires a successful Result with a value");
366 return std::move(value_.value());
367 }
368
370 T takeValue() && {
372 observe();
373 [[maybe_unused]] const bool hasSuccessfulValue = status_.isSuccess() && value_.has_value();
375 EV_DETAIL_RESULT_ASSERT(hasSuccessfulValue, "Result::takeValue requires a successful Result with a value");
376 T result = std::move(value_.value());
377 value_.reset();
378 return result;
379 }
380
382 T valueOr(T fallback) && {
384 observe();
385 if (status_.isSuccess() && value_.has_value()) return std::move(value_.value());
386 return fallback;
387 }
388
394 template <class Function>
396 auto andThen(Function&& function) && -> std::invoke_result_t<Function, T&&> {
398 observe();
399 using Return = std::invoke_result_t<Function, T&&>;
400 if (!status_.isSuccess() || !value_.has_value()) return Return::failure(status_);
402 return std::invoke(std::forward<Function>(function), std::move(value_.value()));
403 }
404
410 template <class Function>
412 Result orElse(Function&& function) && {
414 observe();
415 if (status_.isSuccess() && value_.has_value()) return std::move(*this);
417 return std::invoke(std::forward<Function>(function), status_);
418 }
419
424 void ignore(std::string_view reason = {}) const noexcept {
425 (void)reason;
427 observe();
428 }
429
436 T expect(std::string_view message) && {
438 observe();
439 if (!status_.isSuccess() || !value_.has_value()) {
440#if !defined(ZEROERR_NO_ASSERT)
441 detail::failResultExpectation(status_, message, __FILE__, __LINE__, true);
442#else
443 detail::failResultExpectation(status_, message, __FILE__, __LINE__, false);
444#endif
445 }
447 return std::move(value_.value());
448 }
449
450private:
451 Result(Status status, std::optional<T> value) : status_(std::move(status)), value_(std::move(value)) {}
452
453 Status status_;
454 std::optional<T> value_;
455};
456
460template <>
462class [[nodiscard("Result must be checked or explicitly ignored")]] Result<void> : private detail::ResultObservation {
463public:
465 static Result success() { return Result(Status::success()); }
466
470 EV_DETAIL_RESULT_ASSERT(status.isSuccess(), "Result::success requires a successful Status");
472 return Result(std::move(status));
473 }
474
478 EV_DETAIL_RESULT_ASSERT(status.isFailure(), "Result::failure requires a failure Status");
480 return Result(std::move(status));
481 }
482
484 static Result failure(Diagnostic diagnostic) { return failure(Status::failure(std::move(diagnostic))); }
485
486 Result(const Result&) = delete;
487 Result& operator=(const Result&) = delete;
488
490 Result(Result&& other)
492 : detail::ResultObservation(detail::ResultObservation::InactiveTag{}), status_(std::move(other.status_)) {
494 adoptObservationFrom(other);
495 }
496
498#if !defined(ZEROERR_NO_ASSERT)
499 template <bool AssertionsEnabled = true>
500#else
501 template <bool AssertionsEnabled = false>
502#endif
504 if (this == &other) return *this;
506 assertCanBeOverwritten<AssertionsEnabled>();
507 status_ = std::move(other.status_);
509 adoptObservationFrom(other);
510 return *this;
511 }
512
514 bool ok() const noexcept {
516 observe();
517 return status_.isSuccess();
518 }
519
521 const Status& status() const noexcept {
523 observe();
524 return status_;
525 }
526
528 StatusCode code() const noexcept {
530 observe();
531 return status_.code();
532 }
533
535 const std::vector<Diagnostic>& diagnostics() const noexcept {
537 observe();
538 return status_.diagnostics();
539 }
540
550 const Diagnostic* error() const noexcept {
552 observe();
553 return status_.primaryDiagnostic();
554 }
555
557 explicit operator bool() const noexcept { return ok(); }
558
560 void value() const {
562 observe();
564 EV_DETAIL_RESULT_ASSERT(status_.isSuccess(), "Result<void>::value requires a successful Result");
565 }
566
571 void ignore(std::string_view reason = {}) const noexcept {
572 (void)reason;
574 observe();
575 }
576
582 void expect(std::string_view message) const {
584 observe();
585 if (!status_.isSuccess()) {
586#if !defined(ZEROERR_NO_ASSERT)
587 detail::failResultExpectation(status_, message, __FILE__, __LINE__, true);
588#else
589 detail::failResultExpectation(status_, message, __FILE__, __LINE__, false);
590#endif
591 }
592 }
593
594private:
595 explicit Result(Status status) : status_(std::move(status)) {}
596
597 Status status_;
598};
599
616template <typename... Results>
618[[nodiscard]] bool everyResultValid(const Results&... results) noexcept {
619 static_assert(sizeof...(Results) > 0, "everyResultValid requires at least one Result");
620 return (results.ok() & ...);
621}
622
623} // namespace eve
624
625#undef EV_DETAIL_RESULT_ASSERT
eve::Value condition
#define EVENGINE_API_FOUNDATION
每个链接组(link group)各自的导出宏。
Definition Export.h:106
std::string message
wgpu::PopErrorScopeStatus status
Poco::JSON::Object::Ptr result
std::string file
Object::Ptr value
int detail
#define EV_DETAIL_RESULT_ASSERT(cond, message)
Definition Result.h:20
MigrationFunction function
unsigned line
std::string_view source
Structured operation status used by the common Result foundation.
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
const Diagnostic * error() const noexcept
Inspect the first diagnostic, or null when none was supplied.
Definition Result.h:550
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
Result & operator=(const Result &)=delete
Result(Result &&other)
Move a result and transfer its debug observation responsibility.
Definition Result.h:490
static Result failure(Status status)
Construct a failed void result from a structured status.
Definition Result.h:476
Result & operator=(Result &&other)
Move-assign after checking the destination's old result.
Definition Result.h:503
void expect(std::string_view message) const
Require success for a void operation.
Definition Result.h:582
void value() const
Mark a successful void operation as checked.
Definition Result.h:560
static Result success(Status status)
Construct a successful void result with an explicit status.
Definition Result.h:468
static Result failure(Diagnostic diagnostic)
Construct a failed void result from one structured diagnostic.
Definition Result.h:484
static Result success()
Construct a successful void result.
Definition Result.h:465
const std::vector< Diagnostic > & diagnostics() const noexcept
Inspect all diagnostics; this counts as checking the Result.
Definition Result.h:535
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
Result(const Result &)=delete
StatusCode code() const noexcept
Inspect the stable operation code.
Definition Result.h:528
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:521
Move-only operation result carrying either a value or Status.
Definition Result.h:176
const Diagnostic * error() const noexcept
Inspect the first diagnostic, or null when none was supplied.
Definition Result.h:329
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
Result orElse(Function &&function) &&
Recover a failure with a function receiving its Status.
Definition Result.h:412
T expect(std::string_view message) &&
Require success and move out the value.
Definition Result.h:436
T takeValue() &&
Move the value out and remove it from this Result.
Definition Result.h:370
T valueOr(T fallback) &&
Return the value or an explicit alternate value, consuming this Result.
Definition Result.h:382
Result & operator=(Result< U > &&other)
Move-assign from a Result whose value converts to T by adding const.
Definition Result.h:274
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:424
Result & operator=(const Result &)=delete
T && value() &&
Move the value out after checking success.
Definition Result.h:359
T & value() &
Borrow the value from a mutable lvalue after checking success.
Definition Result.h:349
Result(Result< U > &&other)
Convert a Result into a more const-qualified Result of the same outcome.
Definition Result.h:252
auto andThen(Function &&function) &&-> std::invoke_result_t< Function, T && >
Compose a successful value with a function returning another Result.
Definition Result.h:396
bool hasValue() const noexcept
Whether the result owns a value; observing this is a check.
Definition Result.h:293
const std::vector< Diagnostic > & diagnostics() const noexcept
Inspect all diagnostics; this counts as checking the Result.
Definition Result.h:314
Result(Result &&other)
Move a result and transfer its debug observation responsibility.
Definition Result.h:210
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
StatusCode code() const noexcept
Inspect the stable operation code.
Definition Result.h:307
Result & operator=(Result &&other)
Move-assign a result after checking the destination's old result.
Definition Result.h:232
Result(const Result &)=delete
static Result success(T value, Status status)
Construct a successful result with an explicit non-error status.
Definition Result.h:188
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:300
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Result failure(Diagnostic diagnostic)
Construct a failed result from one structured diagnostic.
Definition Result.h:204
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
Debug-only observation token shared by Result<T> specializations.
Definition Result.h:65
void disarmObservation() noexcept
Drop observation duty; used when a moved-from result is empty.
Definition Result.h:109
~ResultObservation() noexcept(false)
Definition Result.h:78
void observe() const noexcept
Observe.
Definition Result.h:89
ResultObservation() noexcept=default
Constructs a ResultObservation.
void assertCanBeOverwritten() const
Check the destination before a move under the caller's assertion policy.
Definition Result.h:93
void adoptObservationFrom(ResultObservation &other) noexcept
Adopt observation from.
Definition Result.h:102
ResultObservation(InactiveTag) noexcept
Definition Result.h:75
void requireObservation() noexcept
Require a fresh check after replacing the carried outcome.
Definition Result.h:112
True when From may convert into To only by adding const.
Definition Result.h:136
void moveAssignOptional(std::optional< T > &destination, std::optional< U > &&source)
Replace destination with source even when T is not assignable.
Definition Result.h:147
std::invoke_result_t< T > ResultReturn
Definition Result.h:126
void failResultExpectation(const Status &status, std::string_view message, const char *file, unsigned line, bool assertionsEnabled)
Report a failed expect operation with its Status and caller context.
Definition Result.cpp:20
void checkResultInvariant(bool condition, const char *expression, const char *file, unsigned line, const char *message)
Check one Result invariant without instantiating the assertion backend in its caller.
Definition Result.cpp:6
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
bool everyResultValid(const Results &... results) noexcept
True only when every argument Result succeeded, observing all of them.
Definition Result.h:618
Start an inactive token used while a Result move is constructed.
Definition Result.h:74