xref: /aosp_15_r20/external/openscreen/third_party/abseil/src/absl/status/status.h (revision 3f982cf4871df8771c9d4abe6e9a6f8d829b2736)
1 // Copyright 2019 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: status.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header file defines the Abseil `status` library, consisting of:
20 //
21 //   * An `absl::Status` class for holding error handling information
22 //   * A set of canonical `absl::StatusCode` error codes, and associated
23 //     utilities for generating and propagating status codes.
24 //   * A set of helper functions for creating status codes and checking their
25 //     values
26 //
27 // Within Google, `absl::Status` is the primary mechanism for gracefully
28 // handling errors across API boundaries (and in particular across RPC
29 // boundaries). Some of these errors may be recoverable, but others may not.
30 // Most functions that can produce a recoverable error should be designed to
31 // return an `absl::Status` (or `absl::StatusOr`).
32 //
33 // Example:
34 //
35 // absl::Status myFunction(absl::string_view fname, ...) {
36 //   ...
37 //   // encounter error
38 //   if (error condition) {
39 //     return absl::InvalidArgumentError("bad mode");
40 //   }
41 //   // else, return OK
42 //   return absl::OkStatus();
43 // }
44 //
45 // An `absl::Status` is designed to either return "OK" or one of a number of
46 // different error codes, corresponding to typical error conditions.
47 // In almost all cases, when using `absl::Status` you should use the canonical
48 // error codes (of type `absl::StatusCode`) enumerated in this header file.
49 // These canonical codes are understood across the codebase and will be
50 // accepted across all API and RPC boundaries.
51 #ifndef ABSL_STATUS_STATUS_H_
52 #define ABSL_STATUS_STATUS_H_
53 
54 #include <iostream>
55 #include <string>
56 
57 #include "absl/container/inlined_vector.h"
58 #include "absl/status/internal/status_internal.h"
59 #include "absl/strings/cord.h"
60 #include "absl/types/optional.h"
61 
62 namespace absl {
63 ABSL_NAMESPACE_BEGIN
64 
65 // absl::StatusCode
66 //
67 // An `absl::StatusCode` is an enumerated type indicating either no error ("OK")
68 // or an error condition. In most cases, an `absl::Status` indicates a
69 // recoverable error, and the purpose of signalling an error is to indicate what
70 // action to take in response to that error. These error codes map to the proto
71 // RPC error codes indicated in https://cloud.google.com/apis/design/errors.
72 //
73 // The errors listed below are the canonical errors associated with
74 // `absl::Status` and are used throughout the codebase. As a result, these
75 // error codes are somewhat generic.
76 //
77 // In general, try to return the most specific error that applies if more than
78 // one error may pertain. For example, prefer `kOutOfRange` over
79 // `kFailedPrecondition` if both codes apply. Similarly prefer `kNotFound` or
80 // `kAlreadyExists` over `kFailedPrecondition`.
81 //
82 // Because these errors may travel RPC boundaries, these codes are tied to the
83 // `google.rpc.Code` definitions within
84 // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
85 // The string value of these RPC codes is denoted within each enum below.
86 //
87 // If your error handling code requires more context, you can attach payloads
88 // to your status. See `absl::Status::SetPayload()` and
89 // `absl::Status::GetPayload()` below.
90 enum class StatusCode : int {
91   // StatusCode::kOk
92   //
93   // kOK (gRPC code "OK") does not indicate an error; this value is returned on
94   // success. It is typical to check for this value before proceeding on any
95   // given call across an API or RPC boundary. To check this value, use the
96   // `absl::Status::ok()` member function rather than inspecting the raw code.
97   kOk = 0,
98 
99   // StatusCode::kCancelled
100   //
101   // kCancelled (gRPC code "CANCELLED") indicates the operation was cancelled,
102   // typically by the caller.
103   kCancelled = 1,
104 
105   // StatusCode::kUnknown
106   //
107   // kUnknown (gRPC code "UNKNOWN") indicates an unknown error occurred. In
108   // general, more specific errors should be raised, if possible. Errors raised
109   // by APIs that do not return enough error information may be converted to
110   // this error.
111   kUnknown = 2,
112 
113   // StatusCode::kInvalidArgument
114   //
115   // kInvalidArgument (gRPC code "INVALID_ARGUMENT") indicates the caller
116   // specified an invalid argument, such a malformed filename. Note that such
117   // errors should be narrowly limited to indicate to the invalid nature of the
118   // arguments themselves. Errors with validly formed arguments that may cause
119   // errors with the state of the receiving system should be denoted with
120   // `kFailedPrecondition` instead.
121   kInvalidArgument = 3,
122 
123   // StatusCode::kDeadlineExceeded
124   //
125   // kDeadlineExceeded (gRPC code "DEADLINE_EXCEEDED") indicates a deadline
126   // expired before the operation could complete. For operations that may change
127   // state within a system, this error may be returned even if the operation has
128   // completed successfully. For example, a successful response from a server
129   // could have been delayed long enough for the deadline to expire.
130   kDeadlineExceeded = 4,
131 
132   // StatusCode::kNotFound
133   //
134   // kNotFound (gRPC code "NOT_FOUND") indicates some requested entity (such as
135   // a file or directory) was not found.
136   //
137   // `kNotFound` is useful if a request should be denied for an entire class of
138   // users, such as during a gradual feature rollout or undocumented allow list.
139   // If, instead, a request should be denied for specific sets of users, such as
140   // through user-based access control, use `kPermissionDenied` instead.
141   kNotFound = 5,
142 
143   // StatusCode::kAlreadyExists
144   //
145   // kAlreadyExists (gRPC code "ALREADY_EXISTS") indicates the entity that a
146   // caller attempted to create (such as file or directory) is already present.
147   kAlreadyExists = 6,
148 
149   // StatusCode::kPermissionDenied
150   //
151   // kPermissionDenied (gRPC code "PERMISSION_DENIED") indicates that the caller
152   // does not have permission to execute the specified operation. Note that this
153   // error is different than an error due to an *un*authenticated user. This
154   // error code does not imply the request is valid or the requested entity
155   // exists or satisfies any other pre-conditions.
156   //
157   // `kPermissionDenied` must not be used for rejections caused by exhausting
158   // some resource. Instead, use `kResourceExhausted` for those errors.
159   // `kPermissionDenied` must not be used if the caller cannot be identified.
160   // Instead, use `kUnauthenticated` for those errors.
161   kPermissionDenied = 7,
162 
163   // StatusCode::kResourceExhausted
164   //
165   // kResourceExhausted (gRPC code "RESOURCE_EXHAUSTED") indicates some resource
166   // has been exhausted, perhaps a per-user quota, or perhaps the entire file
167   // system is out of space.
168   kResourceExhausted = 8,
169 
170   // StatusCode::kFailedPrecondition
171   //
172   // kFailedPrecondition (gRPC code "FAILED_PRECONDITION") indicates that the
173   // operation was rejected because the system is not in a state required for
174   // the operation's execution. For example, a directory to be deleted may be
175   // non-empty, an "rmdir" operation is applied to a non-directory, etc.
176   //
177   // Some guidelines that may help a service implementer in deciding between
178   // `kFailedPrecondition`, `kAborted`, and `kUnavailable`:
179   //
180   //  (a) Use `kUnavailable` if the client can retry just the failing call.
181   //  (b) Use `kAborted` if the client should retry at a higher transaction
182   //      level (such as when a client-specified test-and-set fails, indicating
183   //      the client should restart a read-modify-write sequence).
184   //  (c) Use `kFailedPrecondition` if the client should not retry until
185   //      the system state has been explicitly fixed. For example, if an "rmdir"
186   //      fails because the directory is non-empty, `kFailedPrecondition`
187   //      should be returned since the client should not retry unless
188   //      the files are deleted from the directory.
189   kFailedPrecondition = 9,
190 
191   // StatusCode::kAborted
192   //
193   // kAborted (gRPC code "ABORTED") indicates the operation was aborted,
194   // typically due to a concurrency issue such as a sequencer check failure or a
195   // failed transaction.
196   //
197   // See the guidelines above for deciding between `kFailedPrecondition`,
198   // `kAborted`, and `kUnavailable`.
199   kAborted = 10,
200 
201   // StatusCode::kOutOfRange
202   //
203   // kOutOfRange (gRPC code "OUT_OF_RANGE") indicates the operation was
204   // attempted past the valid range, such as seeking or reading past an
205   // end-of-file.
206   //
207   // Unlike `kInvalidArgument`, this error indicates a problem that may
208   // be fixed if the system state changes. For example, a 32-bit file
209   // system will generate `kInvalidArgument` if asked to read at an
210   // offset that is not in the range [0,2^32-1], but it will generate
211   // `kOutOfRange` if asked to read from an offset past the current
212   // file size.
213   //
214   // There is a fair bit of overlap between `kFailedPrecondition` and
215   // `kOutOfRange`.  We recommend using `kOutOfRange` (the more specific
216   // error) when it applies so that callers who are iterating through
217   // a space can easily look for an `kOutOfRange` error to detect when
218   // they are done.
219   kOutOfRange = 11,
220 
221   // StatusCode::kUnimplemented
222   //
223   // kUnimplemented (gRPC code "UNIMPLEMENTED") indicates the operation is not
224   // implemented or supported in this service. In this case, the operation
225   // should not be re-attempted.
226   kUnimplemented = 12,
227 
228   // StatusCode::kInternal
229   //
230   // kInternal (gRPC code "INTERNAL") indicates an internal error has occurred
231   // and some invariants expected by the underlying system have not been
232   // satisfied. This error code is reserved for serious errors.
233   kInternal = 13,
234 
235   // StatusCode::kUnavailable
236   //
237   // kUnavailable (gRPC code "UNAVAILABLE") indicates the service is currently
238   // unavailable and that this is most likely a transient condition. An error
239   // such as this can be corrected by retrying with a backoff scheme. Note that
240   // it is not always safe to retry non-idempotent operations.
241   //
242   // See the guidelines above for deciding between `kFailedPrecondition`,
243   // `kAborted`, and `kUnavailable`.
244   kUnavailable = 14,
245 
246   // StatusCode::kDataLoss
247   //
248   // kDataLoss (gRPC code "DATA_LOSS") indicates that unrecoverable data loss or
249   // corruption has occurred. As this error is serious, proper alerting should
250   // be attached to errors such as this.
251   kDataLoss = 15,
252 
253   // StatusCode::kUnauthenticated
254   //
255   // kUnauthenticated (gRPC code "UNAUTHENTICATED") indicates that the request
256   // does not have valid authentication credentials for the operation. Correct
257   // the authentication and try again.
258   kUnauthenticated = 16,
259 
260   // StatusCode::DoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_
261   //
262   // NOTE: this error code entry should not be used and you should not rely on
263   // its value, which may change.
264   //
265   // The purpose of this enumerated value is to force people who handle status
266   // codes with `switch()` statements to *not* simply enumerate all possible
267   // values, but instead provide a "default:" case. Providing such a default
268   // case ensures that code will compile when new codes are added.
269   kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20
270 };
271 
272 // StatusCodeToString()
273 //
274 // Returns the name for the status code, or "" if it is an unknown value.
275 std::string StatusCodeToString(StatusCode code);
276 
277 // operator<<
278 //
279 // Streams StatusCodeToString(code) to `os`.
280 std::ostream& operator<<(std::ostream& os, StatusCode code);
281 
282 // absl::Status
283 //
284 // The `absl::Status` class is generally used to gracefully handle errors
285 // across API boundaries (and in particular across RPC boundaries). Some of
286 // these errors may be recoverable, but others may not. Most
287 // functions which can produce a recoverable error should be designed to return
288 // either an `absl::Status` (or the similar `absl::StatusOr<T>`, which holds
289 // either an object of type `T` or an error).
290 //
291 // API developers should construct their functions to return `absl::OkStatus()`
292 // upon success, or an `absl::StatusCode` upon another type of error (e.g
293 // an `absl::StatusCode::kInvalidArgument` error). The API provides convenience
294 // functions to constuct each status code.
295 //
296 // Example:
297 //
298 // absl::Status myFunction(absl::string_view fname, ...) {
299 //   ...
300 //   // encounter error
301 //   if (error condition) {
302 //     // Construct an absl::StatusCode::kInvalidArgument error
303 //     return absl::InvalidArgumentError("bad mode");
304 //   }
305 //   // else, return OK
306 //   return absl::OkStatus();
307 // }
308 //
309 // Users handling status error codes should prefer checking for an OK status
310 // using the `ok()` member function. Handling multiple error codes may justify
311 // use of switch statement, but only check for error codes you know how to
312 // handle; do not try to exhaustively match against all canonical error codes.
313 // Errors that cannot be handled should be logged and/or propagated for higher
314 // levels to deal with. If you do use a switch statement, make sure that you
315 // also provide a `default:` switch case, so that code does not break as other
316 // canonical codes are added to the API.
317 //
318 // Example:
319 //
320 //   absl::Status result = DoSomething();
321 //   if (!result.ok()) {
322 //     LOG(ERROR) << result;
323 //   }
324 //
325 //   // Provide a default if switching on multiple error codes
326 //   switch (result.code()) {
327 //     // The user hasn't authenticated. Ask them to reauth
328 //     case absl::StatusCode::kUnauthenticated:
329 //       DoReAuth();
330 //       break;
331 //     // The user does not have permission. Log an error.
332 //     case absl::StatusCode::kPermissionDenied:
333 //       LOG(ERROR) << result;
334 //       break;
335 //     // Propagate the error otherwise.
336 //     default:
337 //       return true;
338 //   }
339 //
340 // An `absl::Status` can optionally include a payload with more information
341 // about the error. Typically, this payload serves one of several purposes:
342 //
343 //   * It may provide more fine-grained semantic information about the error to
344 //     facilitate actionable remedies.
345 //   * It may provide human-readable contexual information that is more
346 //     appropriate to display to an end user.
347 //
348 // Example:
349 //
350 //   absl::Status result = DoSomething();
351 //   // Inform user to retry after 30 seconds
352 //   // See more error details in googleapis/google/rpc/error_details.proto
353 //   if (absl::IsResourceExhausted(result)) {
354 //     google::rpc::RetryInfo info;
355 //     info.retry_delay().seconds() = 30;
356 //     // Payloads require a unique key (a URL to ensure no collisions with
357 //     // other payloads), and an `absl::Cord` to hold the encoded data.
358 //     absl::string_view url = "type.googleapis.com/google.rpc.RetryInfo";
359 //     result.SetPayload(url, info.SerializeAsCord());
360 //     return result;
361 //   }
362 //
363 class ABSL_MUST_USE_RESULT Status final {
364  public:
365   // Constructors
366 
367   // This default constructor creates an OK status with no message or payload.
368   // Avoid this constructor and prefer explicit construction of an OK status
369   // with `absl::OkStatus()`.
370   Status();
371 
372   // Creates a status in the canonical error space with the specified
373   // `absl::StatusCode` and error message.  If `code == absl::StatusCode::kOk`,
374   // `msg` is ignored and an object identical to an OK status is constructed.
375   //
376   // The `msg` string must be in UTF-8. The implementation may complain (e.g.,
377   // by printing a warning) if it is not.
378   Status(absl::StatusCode code, absl::string_view msg);
379 
380   Status(const Status&);
381   Status& operator=(const Status& x);
382 
383   // Move operators
384 
385   // The moved-from state is valid but unspecified.
386   Status(Status&&) noexcept;
387   Status& operator=(Status&&);
388 
389   ~Status();
390 
391   // Status::Update()
392   //
393   // Updates the existing status with `new_status` provided that `this->ok()`.
394   // If the existing status already contains a non-OK error, this update has no
395   // effect and preserves the current data. Note that this behavior may change
396   // in the future to augment a current non-ok status with additional
397   // information about `new_status`.
398   //
399   // `Update()` provides a convenient way of keeping track of the first error
400   // encountered.
401   //
402   // Example:
403   //   // Instead of "if (overall_status.ok()) overall_status = new_status"
404   //   overall_status.Update(new_status);
405   //
406   void Update(const Status& new_status);
407   void Update(Status&& new_status);
408 
409   // Status::ok()
410   //
411   // Returns `true` if `this->ok()`. Prefer checking for an OK status using this
412   // member function.
413   ABSL_MUST_USE_RESULT bool ok() const;
414 
415   // Status::code()
416   //
417   // Returns the canonical error code of type `absl::StatusCode` of this status.
418   absl::StatusCode code() const;
419 
420   // Status::raw_code()
421   //
422   // Returns a raw (canonical) error code corresponding to the enum value of
423   // `google.rpc.Code` definitions within
424   // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto.
425   // These values could be out of the range of canonical `absl::StatusCode`
426   // enum values.
427   //
428   // NOTE: This function should only be called when converting to an associated
429   // wire format. Use `Status::code()` for error handling.
430   int raw_code() const;
431 
432   // Status::message()
433   //
434   // Returns the error message associated with this error code, if available.
435   // Note that this message rarely describes the error code.  It is not unusual
436   // for the error message to be the empty string. As a result, prefer
437   // `Status::ToString()` for debug logging.
438   absl::string_view message() const;
439 
440   friend bool operator==(const Status&, const Status&);
441   friend bool operator!=(const Status&, const Status&);
442 
443   // Status::ToString()
444   //
445   // Returns a combination of the error code name, the message and any
446   // associated payload messages. This string is designed simply to be human
447   // readable and its exact format should not be load bearing. Do not depend on
448   // the exact format of the result of `ToString()` which is subject to change.
449   //
450   // The printed code name and the message are generally substrings of the
451   // result, and the payloads to be printed use the status payload printer
452   // mechanism (which is internal).
453   std::string ToString() const;
454 
455   // Status::IgnoreError()
456   //
457   // Ignores any errors. This method does nothing except potentially suppress
458   // complaints from any tools that are checking that errors are not dropped on
459   // the floor.
460   void IgnoreError() const;
461 
462   // swap()
463   //
464   // Swap the contents of one status with another.
465   friend void swap(Status& a, Status& b);
466 
467   //----------------------------------------------------------------------------
468   // Payload Management APIs
469   //----------------------------------------------------------------------------
470 
471   // A payload may be attached to a status to provide additional context to an
472   // error that may not be satisifed by an existing `absl::StatusCode`.
473   // Typically, this payload serves one of several purposes:
474   //
475   //   * It may provide more fine-grained semantic information about the error
476   //     to facilitate actionable remedies.
477   //   * It may provide human-readable contexual information that is more
478   //     appropriate to display to an end user.
479   //
480   // A payload consists of a [key,value] pair, where the key is a string
481   // referring to a unique "type URL" and the value is an object of type
482   // `absl::Cord` to hold the contextual data.
483   //
484   // The "type URL" should be unique and follow the format of a URL
485   // (https://en.wikipedia.org/wiki/URL) and, ideally, provide some
486   // documentation or schema on how to interpret its associated data. For
487   // example, the default type URL for a protobuf message type is
488   // "type.googleapis.com/packagename.messagename". Other custom wire formats
489   // should define the format of type URL in a similar practice so as to
490   // minimize the chance of conflict between type URLs.
491   // Users should ensure that the type URL can be mapped to a concrete
492   // C++ type if they want to deserialize the payload and read it effectively.
493   //
494   // To attach a payload to a status object, call `Status::SetPayload()`,
495   // passing it the type URL and an `absl::Cord` of associated data. Similarly,
496   // to extract the payload from a status, call `Status::GetPayload()`. You
497   // may attach multiple payloads (with differing type URLs) to any given
498   // status object, provided that the status is currently exhibiting an error
499   // code (i.e. is not OK).
500 
501   // Status::GetPayload()
502   //
503   // Gets the payload of a status given its unique `type_url` key, if present.
504   absl::optional<absl::Cord> GetPayload(absl::string_view type_url) const;
505 
506   // Status::SetPayload()
507   //
508   // Sets the payload for a non-ok status using a `type_url` key, overwriting
509   // any existing payload for that `type_url`.
510   //
511   // NOTE: This function does nothing if the Status is ok.
512   void SetPayload(absl::string_view type_url, absl::Cord payload);
513 
514   // Status::ErasePayload()
515   //
516   // Erases the payload corresponding to the `type_url` key.  Returns `true` if
517   // the payload was present.
518   bool ErasePayload(absl::string_view type_url);
519 
520   // Status::ForEachPayload()
521   //
522   // Iterates over the stored payloads and calls the
523   // `visitor(type_key, payload)` callable for each one.
524   //
525   // NOTE: The order of calls to `visitor()` is not specified and may change at
526   // any time.
527   //
528   // NOTE: Any mutation on the same 'absl::Status' object during visitation is
529   // forbidden and could result in undefined behavior.
530   void ForEachPayload(
531       const std::function<void(absl::string_view, const absl::Cord&)>& visitor)
532       const;
533 
534  private:
535   friend Status CancelledError();
536 
537   // Creates a status in the canonical error space with the specified
538   // code, and an empty error message.
539   explicit Status(absl::StatusCode code);
540 
541   static void UnrefNonInlined(uintptr_t rep);
542   static void Ref(uintptr_t rep);
543   static void Unref(uintptr_t rep);
544 
545   // REQUIRES: !ok()
546   // Ensures rep_ is not shared with any other Status.
547   void PrepareToModify();
548 
549   const status_internal::Payloads* GetPayloads() const;
550   status_internal::Payloads* GetPayloads();
551 
552   // Takes ownership of payload.
553   static uintptr_t NewRep(absl::StatusCode code, absl::string_view msg,
554                           std::unique_ptr<status_internal::Payloads> payload);
555   static bool EqualsSlow(const absl::Status& a, const absl::Status& b);
556 
557   // MSVC 14.0 limitation requires the const.
558   static constexpr const char kMovedFromString[] =
559       "Status accessed after move.";
560 
561   static const std::string* EmptyString();
562   static const std::string* MovedFromString();
563 
564   // Returns whether rep contains an inlined representation.
565   // See rep_ for details.
566   static bool IsInlined(uintptr_t rep);
567 
568   // Indicates whether this Status was the rhs of a move operation. See rep_
569   // for details.
570   static bool IsMovedFrom(uintptr_t rep);
571   static uintptr_t MovedFromRep();
572 
573   // Convert between error::Code and the inlined uintptr_t representation used
574   // by rep_. See rep_ for details.
575   static uintptr_t CodeToInlinedRep(absl::StatusCode code);
576   static absl::StatusCode InlinedRepToCode(uintptr_t rep);
577 
578   // Converts between StatusRep* and the external uintptr_t representation used
579   // by rep_. See rep_ for details.
580   static uintptr_t PointerToRep(status_internal::StatusRep* r);
581   static status_internal::StatusRep* RepToPointer(uintptr_t r);
582 
583   // Returns string for non-ok Status.
584   std::string ToStringSlow() const;
585 
586   // Status supports two different representations.
587   //  - When the low bit is off it is an inlined representation.
588   //    It uses the canonical error space, no message or payload.
589   //    The error code is (rep_ >> 2).
590   //    The (rep_ & 2) bit is the "moved from" indicator, used in IsMovedFrom().
591   //  - When the low bit is on it is an external representation.
592   //    In this case all the data comes from a heap allocated Rep object.
593   //    (rep_ - 1) is a status_internal::StatusRep* pointer to that structure.
594   uintptr_t rep_;
595 };
596 
597 // OkStatus()
598 //
599 // Returns an OK status, equivalent to a default constructed instance. Prefer
600 // usage of `absl::OkStatus()` when constructing such an OK status.
601 Status OkStatus();
602 
603 // operator<<()
604 //
605 // Prints a human-readable representation of `x` to `os`.
606 std::ostream& operator<<(std::ostream& os, const Status& x);
607 
608 // IsAborted()
609 // IsAlreadyExists()
610 // IsCancelled()
611 // IsDataLoss()
612 // IsDeadlineExceeded()
613 // IsFailedPrecondition()
614 // IsInternal()
615 // IsInvalidArgument()
616 // IsNotFound()
617 // IsOutOfRange()
618 // IsPermissionDenied()
619 // IsResourceExhausted()
620 // IsUnauthenticated()
621 // IsUnavailable()
622 // IsUnimplemented()
623 // IsUnknown()
624 //
625 // These convenience functions return `true` if a given status matches the
626 // `absl::StatusCode` error code of its associated function.
627 ABSL_MUST_USE_RESULT bool IsAborted(const Status& status);
628 ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status);
629 ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status);
630 ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status);
631 ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status);
632 ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status);
633 ABSL_MUST_USE_RESULT bool IsInternal(const Status& status);
634 ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status);
635 ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status);
636 ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status);
637 ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status);
638 ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status);
639 ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status);
640 ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status);
641 ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status);
642 ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status);
643 
644 // AbortedError()
645 // AlreadyExistsError()
646 // CancelledError()
647 // DataLossError()
648 // DeadlineExceededError()
649 // FailedPreconditionError()
650 // InternalError()
651 // InvalidArgumentError()
652 // NotFoundError()
653 // OutOfRangeError()
654 // PermissionDeniedError()
655 // ResourceExhaustedError()
656 // UnauthenticatedError()
657 // UnavailableError()
658 // UnimplementedError()
659 // UnknownError()
660 //
661 // These convenience functions create an `absl::Status` object with an error
662 // code as indicated by the associated function name, using the error message
663 // passed in `message`.
664 Status AbortedError(absl::string_view message);
665 Status AlreadyExistsError(absl::string_view message);
666 Status CancelledError(absl::string_view message);
667 Status DataLossError(absl::string_view message);
668 Status DeadlineExceededError(absl::string_view message);
669 Status FailedPreconditionError(absl::string_view message);
670 Status InternalError(absl::string_view message);
671 Status InvalidArgumentError(absl::string_view message);
672 Status NotFoundError(absl::string_view message);
673 Status OutOfRangeError(absl::string_view message);
674 Status PermissionDeniedError(absl::string_view message);
675 Status ResourceExhaustedError(absl::string_view message);
676 Status UnauthenticatedError(absl::string_view message);
677 Status UnavailableError(absl::string_view message);
678 Status UnimplementedError(absl::string_view message);
679 Status UnknownError(absl::string_view message);
680 
681 //------------------------------------------------------------------------------
682 // Implementation details follow
683 //------------------------------------------------------------------------------
684 
Status()685 inline Status::Status() : rep_(CodeToInlinedRep(absl::StatusCode::kOk)) {}
686 
Status(absl::StatusCode code)687 inline Status::Status(absl::StatusCode code) : rep_(CodeToInlinedRep(code)) {}
688 
Status(const Status & x)689 inline Status::Status(const Status& x) : rep_(x.rep_) { Ref(rep_); }
690 
691 inline Status& Status::operator=(const Status& x) {
692   uintptr_t old_rep = rep_;
693   if (x.rep_ != old_rep) {
694     Ref(x.rep_);
695     rep_ = x.rep_;
696     Unref(old_rep);
697   }
698   return *this;
699 }
700 
Status(Status && x)701 inline Status::Status(Status&& x) noexcept : rep_(x.rep_) {
702   x.rep_ = MovedFromRep();
703 }
704 
705 inline Status& Status::operator=(Status&& x) {
706   uintptr_t old_rep = rep_;
707   rep_ = x.rep_;
708   x.rep_ = MovedFromRep();
709   Unref(old_rep);
710   return *this;
711 }
712 
Update(const Status & new_status)713 inline void Status::Update(const Status& new_status) {
714   if (ok()) {
715     *this = new_status;
716   }
717 }
718 
Update(Status && new_status)719 inline void Status::Update(Status&& new_status) {
720   if (ok()) {
721     *this = std::move(new_status);
722   }
723 }
724 
~Status()725 inline Status::~Status() { Unref(rep_); }
726 
ok()727 inline bool Status::ok() const {
728   return rep_ == CodeToInlinedRep(absl::StatusCode::kOk);
729 }
730 
message()731 inline absl::string_view Status::message() const {
732   return !IsInlined(rep_)
733              ? RepToPointer(rep_)->message
734              : (IsMovedFrom(rep_) ? absl::string_view(kMovedFromString)
735                                   : absl::string_view());
736 }
737 
738 inline bool operator==(const Status& lhs, const Status& rhs) {
739   return lhs.rep_ == rhs.rep_ || Status::EqualsSlow(lhs, rhs);
740 }
741 
742 inline bool operator!=(const Status& lhs, const Status& rhs) {
743   return !(lhs == rhs);
744 }
745 
ToString()746 inline std::string Status::ToString() const {
747   return ok() ? "OK" : ToStringSlow();
748 }
749 
IgnoreError()750 inline void Status::IgnoreError() const {
751   // no-op
752 }
753 
swap(absl::Status & a,absl::Status & b)754 inline void swap(absl::Status& a, absl::Status& b) {
755   using std::swap;
756   swap(a.rep_, b.rep_);
757 }
758 
GetPayloads()759 inline const status_internal::Payloads* Status::GetPayloads() const {
760   return IsInlined(rep_) ? nullptr : RepToPointer(rep_)->payloads.get();
761 }
762 
GetPayloads()763 inline status_internal::Payloads* Status::GetPayloads() {
764   return IsInlined(rep_) ? nullptr : RepToPointer(rep_)->payloads.get();
765 }
766 
IsInlined(uintptr_t rep)767 inline bool Status::IsInlined(uintptr_t rep) { return (rep & 1) == 0; }
768 
IsMovedFrom(uintptr_t rep)769 inline bool Status::IsMovedFrom(uintptr_t rep) {
770   return IsInlined(rep) && (rep & 2) != 0;
771 }
772 
MovedFromRep()773 inline uintptr_t Status::MovedFromRep() {
774   return CodeToInlinedRep(absl::StatusCode::kInternal) | 2;
775 }
776 
CodeToInlinedRep(absl::StatusCode code)777 inline uintptr_t Status::CodeToInlinedRep(absl::StatusCode code) {
778   return static_cast<uintptr_t>(code) << 2;
779 }
780 
InlinedRepToCode(uintptr_t rep)781 inline absl::StatusCode Status::InlinedRepToCode(uintptr_t rep) {
782   assert(IsInlined(rep));
783   return static_cast<absl::StatusCode>(rep >> 2);
784 }
785 
RepToPointer(uintptr_t rep)786 inline status_internal::StatusRep* Status::RepToPointer(uintptr_t rep) {
787   assert(!IsInlined(rep));
788   return reinterpret_cast<status_internal::StatusRep*>(rep - 1);
789 }
790 
PointerToRep(status_internal::StatusRep * rep)791 inline uintptr_t Status::PointerToRep(status_internal::StatusRep* rep) {
792   return reinterpret_cast<uintptr_t>(rep) + 1;
793 }
794 
Ref(uintptr_t rep)795 inline void Status::Ref(uintptr_t rep) {
796   if (!IsInlined(rep)) {
797     RepToPointer(rep)->ref.fetch_add(1, std::memory_order_relaxed);
798   }
799 }
800 
Unref(uintptr_t rep)801 inline void Status::Unref(uintptr_t rep) {
802   if (!IsInlined(rep)) {
803     UnrefNonInlined(rep);
804   }
805 }
806 
OkStatus()807 inline Status OkStatus() { return Status(); }
808 
809 // Creates a `Status` object with the `absl::StatusCode::kCancelled` error code
810 // and an empty message. It is provided only for efficiency, given that
811 // message-less kCancelled errors are common in the infrastructure.
CancelledError()812 inline Status CancelledError() { return Status(absl::StatusCode::kCancelled); }
813 
814 ABSL_NAMESPACE_END
815 }  // namespace absl
816 
817 #endif  // ABSL_STATUS_STATUS_H_
818