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