1
//! Error handling with the `Result` type.
2
//!
3
//! [`Result<T, E>`][`Result`] is the type used for returning and propagating
4
//! errors. It is an enum with the variants, [`Ok(T)`], representing
5
//! success and containing a value, and [`Err(E)`], representing error
6
//! and containing an error value.
7
//!
8
//! ```
9
//! # #[allow(dead_code)]
10
//! enum Result<T, E> {
11
//!    Ok(T),
12
//!    Err(E),
13
//! }
14
//! ```
15
//!
16
//! Functions return [`Result`] whenever errors are expected and
17
//! recoverable. In the `std` crate, [`Result`] is most prominently used
18
//! for [I/O](../../std/io/index.html).
19
//!
20
//! A simple function returning [`Result`] might be
21
//! defined and used like so:
22
//!
23
//! ```
24
//! #[derive(Debug)]
25
//! enum Version { Version1, Version2 }
26
//!
27
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
28
//!     match header.get(0) {
29
//!         None => Err("invalid header length"),
30
//!         Some(&1) => Ok(Version::Version1),
31
//!         Some(&2) => Ok(Version::Version2),
32
//!         Some(_) => Err("invalid version"),
33
//!     }
34
//! }
35
//!
36
//! let version = parse_version(&[1, 2, 3, 4]);
37
//! match version {
38
//!     Ok(v) => println!("working with version: {v:?}"),
39
//!     Err(e) => println!("error parsing header: {e:?}"),
40
//! }
41
//! ```
42
//!
43
//! Pattern matching on [`Result`]s is clear and straightforward for
44
//! simple cases, but [`Result`] comes with some convenience methods
45
//! that make working with it more succinct.
46
//!
47
//! ```
48
//! // The `is_ok` and `is_err` methods do what they say.
49
//! let good_result: Result<i32, i32> = Ok(10);
50
//! let bad_result: Result<i32, i32> = Err(10);
51
//! assert!(good_result.is_ok() && !good_result.is_err());
52
//! assert!(bad_result.is_err() && !bad_result.is_ok());
53
//!
54
//! // `map` and `map_err` consume the `Result` and produce another.
55
//! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
56
//! let bad_result: Result<i32, i32> = bad_result.map_err(|i| i - 1);
57
//! assert_eq!(good_result, Ok(11));
58
//! assert_eq!(bad_result, Err(9));
59
//!
60
//! // Use `and_then` to continue the computation.
61
//! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
62
//! assert_eq!(good_result, Ok(true));
63
//!
64
//! // Use `or_else` to handle the error.
65
//! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
66
//! assert_eq!(bad_result, Ok(29));
67
//!
68
//! // Consume the result and return the contents with `unwrap`.
69
//! let final_awesome_result = good_result.unwrap();
70
//! assert!(final_awesome_result)
71
//! ```
72
//!
73
//! # Results must be used
74
//!
75
//! A common problem with using return values to indicate errors is
76
//! that it is easy to ignore the return value, thus failing to handle
77
//! the error. [`Result`] is annotated with the `#[must_use]` attribute,
78
//! which will cause the compiler to issue a warning when a Result
79
//! value is ignored. This makes [`Result`] especially useful with
80
//! functions that may encounter errors but don't otherwise return a
81
//! useful value.
82
//!
83
//! Consider the [`write_all`] method defined for I/O types
84
//! by the [`Write`] trait:
85
//!
86
//! ```
87
//! use std::io;
88
//!
89
//! trait Write {
90
//!     fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
91
//! }
92
//! ```
93
//!
94
//! *Note: The actual definition of [`Write`] uses [`io::Result`], which
95
//! is just a synonym for <code>[Result]<T, [io::Error]></code>.*
96
//!
97
//! This method doesn't produce a value, but the write may
98
//! fail. It's crucial to handle the error case, and *not* write
99
//! something like this:
100
//!
101
//! ```no_run
102
//! # #![allow(unused_must_use)] // \o/
103
//! use std::fs::File;
104
//! use std::io::prelude::*;
105
//!
106
//! let mut file = File::create("valuable_data.txt").unwrap();
107
//! // If `write_all` errors, then we'll never know, because the return
108
//! // value is ignored.
109
//! file.write_all(b"important message");
110
//! ```
111
//!
112
//! If you *do* write that in Rust, the compiler will give you a
113
//! warning (by default, controlled by the `unused_must_use` lint).
114
//!
115
//! You might instead, if you don't want to handle the error, simply
116
//! assert success with [`expect`]. This will panic if the
117
//! write fails, providing a marginally useful message indicating why:
118
//!
119
//! ```no_run
120
//! use std::fs::File;
121
//! use std::io::prelude::*;
122
//!
123
//! let mut file = File::create("valuable_data.txt").unwrap();
124
//! file.write_all(b"important message").expect("failed to write message");
125
//! ```
126
//!
127
//! You might also simply assert success:
128
//!
129
//! ```no_run
130
//! # use std::fs::File;
131
//! # use std::io::prelude::*;
132
//! # let mut file = File::create("valuable_data.txt").unwrap();
133
//! assert!(file.write_all(b"important message").is_ok());
134
//! ```
135
//!
136
//! Or propagate the error up the call stack with [`?`]:
137
//!
138
//! ```
139
//! # use std::fs::File;
140
//! # use std::io::prelude::*;
141
//! # use std::io;
142
//! # #[allow(dead_code)]
143
//! fn write_message() -> io::Result<()> {
144
//!     let mut file = File::create("valuable_data.txt")?;
145
//!     file.write_all(b"important message")?;
146
//!     Ok(())
147
//! }
148
//! ```
149
//!
150
//! # The question mark operator, `?`
151
//!
152
//! When writing code that calls many functions that return the
153
//! [`Result`] type, the error handling can be tedious. The question mark
154
//! operator, [`?`], hides some of the boilerplate of propagating errors
155
//! up the call stack.
156
//!
157
//! It replaces this:
158
//!
159
//! ```
160
//! # #![allow(dead_code)]
161
//! use std::fs::File;
162
//! use std::io::prelude::*;
163
//! use std::io;
164
//!
165
//! struct Info {
166
//!     name: String,
167
//!     age: i32,
168
//!     rating: i32,
169
//! }
170
//!
171
//! fn write_info(info: &Info) -> io::Result<()> {
172
//!     // Early return on error
173
//!     let mut file = match File::create("my_best_friends.txt") {
174
//!            Err(e) => return Err(e),
175
//!            Ok(f) => f,
176
//!     };
177
//!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
178
//!         return Err(e)
179
//!     }
180
//!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
181
//!         return Err(e)
182
//!     }
183
//!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
184
//!         return Err(e)
185
//!     }
186
//!     Ok(())
187
//! }
188
//! ```
189
//!
190
//! With this:
191
//!
192
//! ```
193
//! # #![allow(dead_code)]
194
//! use std::fs::File;
195
//! use std::io::prelude::*;
196
//! use std::io;
197
//!
198
//! struct Info {
199
//!     name: String,
200
//!     age: i32,
201
//!     rating: i32,
202
//! }
203
//!
204
//! fn write_info(info: &Info) -> io::Result<()> {
205
//!     let mut file = File::create("my_best_friends.txt")?;
206
//!     // Early return on error
207
//!     file.write_all(format!("name: {}\n", info.name).as_bytes())?;
208
//!     file.write_all(format!("age: {}\n", info.age).as_bytes())?;
209
//!     file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
210
//!     Ok(())
211
//! }
212
//! ```
213
//!
214
//! *It's much nicer!*
215
//!
216
//! Ending the expression with [`?`] will result in the [`Ok`]'s unwrapped value, unless the result
217
//! is [`Err`], in which case [`Err`] is returned early from the enclosing function.
218
//!
219
//! [`?`] can be used in functions that return [`Result`] because of the
220
//! early return of [`Err`] that it provides.
221
//!
222
//! [`expect`]: Result::expect
223
//! [`Write`]: ../../std/io/trait.Write.html "io::Write"
224
//! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all"
225
//! [`io::Result`]: ../../std/io/type.Result.html "io::Result"
226
//! [`?`]: crate::ops::Try
227
//! [`Ok(T)`]: Ok
228
//! [`Err(E)`]: Err
229
//! [io::Error]: ../../std/io/struct.Error.html "io::Error"
230
//!
231
//! # Representation
232
//!
233
//! In some cases, [`Result<T, E>`] will gain the same size, alignment, and ABI
234
//! guarantees as [`Option<U>`] has. One of either the `T` or `E` type must be a
235
//! type that qualifies for the `Option` [representation guarantees][opt-rep],
236
//! and the *other* type must meet all of the following conditions:
237
//! * Is a zero-sized type with alignment 1 (a "1-ZST").
238
//! * Has no fields.
239
//! * Does not have the `#[non_exhaustive]` attribute.
240
//!
241
//! For example, `NonZeroI32` qualifies for the `Option` representation
242
//! guarantees, and `()` is a zero-sized type with alignment 1, no fields, and
243
//! it isn't `non_exhaustive`. This means that both `Result<NonZeroI32, ()>` and
244
//! `Result<(), NonZeroI32>` have the same size, alignment, and ABI guarantees
245
//! as `Option<NonZeroI32>`. The only difference is the implied semantics:
246
//! * `Option<NonZeroI32>` is "a non-zero i32 might be present"
247
//! * `Result<NonZeroI32, ()>` is "a non-zero i32 success result, if any"
248
//! * `Result<(), NonZeroI32>` is "a non-zero i32 error result, if any"
249
//!
250
//! [opt-rep]: ../option/index.html#representation "Option Representation"
251
//!
252
//! # Method overview
253
//!
254
//! In addition to working with pattern matching, [`Result`] provides a
255
//! wide variety of different methods.
256
//!
257
//! ## Querying the variant
258
//!
259
//! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
260
//! is [`Ok`] or [`Err`], respectively.
261
//!
262
//! The [`is_ok_and`] and [`is_err_and`] methods apply the provided function
263
//! to the contents of the [`Result`] to produce a boolean value. If the [`Result`] does not have the expected variant
264
//! then [`false`] is returned instead without executing the function.
265
//!
266
//! [`is_err`]: Result::is_err
267
//! [`is_ok`]: Result::is_ok
268
//! [`is_ok_and`]: Result::is_ok_and
269
//! [`is_err_and`]: Result::is_err_and
270
//!
271
//! ## Adapters for working with references
272
//!
273
//! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>`
274
//! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
275
//! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>`
276
//! * [`as_deref_mut`] converts from `&mut Result<T, E>` to
277
//!   `Result<&mut T::Target, &mut E>`
278
//!
279
//! [`as_deref`]: Result::as_deref
280
//! [`as_deref_mut`]: Result::as_deref_mut
281
//! [`as_mut`]: Result::as_mut
282
//! [`as_ref`]: Result::as_ref
283
//!
284
//! ## Extracting contained values
285
//!
286
//! These methods extract the contained value in a [`Result<T, E>`] when it
287
//! is the [`Ok`] variant. If the [`Result`] is [`Err`]:
288
//!
289
//! * [`expect`] panics with a provided custom message
290
//! * [`unwrap`] panics with a generic message
291
//! * [`unwrap_or`] returns the provided default value
292
//! * [`unwrap_or_default`] returns the default value of the type `T`
293
//!   (which must implement the [`Default`] trait)
294
//! * [`unwrap_or_else`] returns the result of evaluating the provided
295
//!   function
296
//! * [`unwrap_unchecked`] produces *[undefined behavior]*
297
//!
298
//! The panicking methods [`expect`] and [`unwrap`] require `E` to
299
//! implement the [`Debug`] trait.
300
//!
301
//! [`Debug`]: crate::fmt::Debug
302
//! [`expect`]: Result::expect
303
//! [`unwrap`]: Result::unwrap
304
//! [`unwrap_or`]: Result::unwrap_or
305
//! [`unwrap_or_default`]: Result::unwrap_or_default
306
//! [`unwrap_or_else`]: Result::unwrap_or_else
307
//! [`unwrap_unchecked`]: Result::unwrap_unchecked
308
//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
309
//!
310
//! These methods extract the contained value in a [`Result<T, E>`] when it
311
//! is the [`Err`] variant. They require `T` to implement the [`Debug`]
312
//! trait. If the [`Result`] is [`Ok`]:
313
//!
314
//! * [`expect_err`] panics with a provided custom message
315
//! * [`unwrap_err`] panics with a generic message
316
//! * [`unwrap_err_unchecked`] produces *[undefined behavior]*
317
//!
318
//! [`Debug`]: crate::fmt::Debug
319
//! [`expect_err`]: Result::expect_err
320
//! [`unwrap_err`]: Result::unwrap_err
321
//! [`unwrap_err_unchecked`]: Result::unwrap_err_unchecked
322
//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
323
//!
324
//! ## Transforming contained values
325
//!
326
//! These methods transform [`Result`] to [`Option`]:
327
//!
328
//! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`],
329
//!   mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`]
330
//! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`],
331
//!   mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`]
332
//! * [`transpose`] transposes a [`Result`] of an [`Option`] into an
333
//!   [`Option`] of a [`Result`]
334
//!
335
// Do NOT add link reference definitions for `err` or `ok`, because they
336
// will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due
337
// to case folding.
338
//!
339
//! [`Err(e)`]: Err
340
//! [`Ok(v)`]: Ok
341
//! [`Some(e)`]: Option::Some
342
//! [`Some(v)`]: Option::Some
343
//! [`transpose`]: Result::transpose
344
//!
345
//! These methods transform the contained value of the [`Ok`] variant:
346
//!
347
//! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
348
//!   the provided function to the contained value of [`Ok`] and leaving
349
//!   [`Err`] values unchanged
350
//! * [`inspect`] takes ownership of the [`Result`], applies the
351
//!   provided function to the contained value by reference,
352
//!   and then returns the [`Result`]
353
//!
354
//! [`map`]: Result::map
355
//! [`inspect`]: Result::inspect
356
//!
357
//! These methods transform the contained value of the [`Err`] variant:
358
//!
359
//! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
360
//!   applying the provided function to the contained value of [`Err`] and
361
//!   leaving [`Ok`] values unchanged
362
//! * [`inspect_err`] takes ownership of the [`Result`], applies the
363
//!   provided function to the contained value of [`Err`] by reference,
364
//!   and then returns the [`Result`]
365
//!
366
//! [`map_err`]: Result::map_err
367
//! [`inspect_err`]: Result::inspect_err
368
//!
369
//! These methods transform a [`Result<T, E>`] into a value of a possibly
370
//! different type `U`:
371
//!
372
//! * [`map_or`] applies the provided function to the contained value of
373
//!   [`Ok`], or returns the provided default value if the [`Result`] is
374
//!   [`Err`]
375
//! * [`map_or_else`] applies the provided function to the contained value
376
//!   of [`Ok`], or applies the provided default fallback function to the
377
//!   contained value of [`Err`]
378
//!
379
//! [`map_or`]: Result::map_or
380
//! [`map_or_else`]: Result::map_or_else
381
//!
382
//! ## Boolean operators
383
//!
384
//! These methods treat the [`Result`] as a boolean value, where [`Ok`]
385
//! acts like [`true`] and [`Err`] acts like [`false`]. There are two
386
//! categories of these methods: ones that take a [`Result`] as input, and
387
//! ones that take a function as input (to be lazily evaluated).
388
//!
389
//! The [`and`] and [`or`] methods take another [`Result`] as input, and
390
//! produce a [`Result`] as output. The [`and`] method can produce a
391
//! [`Result<U, E>`] value having a different inner type `U` than
392
//! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`]
393
//! value having a different error type `F` than [`Result<T, E>`].
394
//!
395
//! | method  | self     | input     | output   |
396
//! |---------|----------|-----------|----------|
397
//! | [`and`] | `Err(e)` | (ignored) | `Err(e)` |
398
//! | [`and`] | `Ok(x)`  | `Err(d)`  | `Err(d)` |
399
//! | [`and`] | `Ok(x)`  | `Ok(y)`   | `Ok(y)`  |
400
//! | [`or`]  | `Err(e)` | `Err(d)`  | `Err(d)` |
401
//! | [`or`]  | `Err(e)` | `Ok(y)`   | `Ok(y)`  |
402
//! | [`or`]  | `Ok(x)`  | (ignored) | `Ok(x)`  |
403
//!
404
//! [`and`]: Result::and
405
//! [`or`]: Result::or
406
//!
407
//! The [`and_then`] and [`or_else`] methods take a function as input, and
408
//! only evaluate the function when they need to produce a new value. The
409
//! [`and_then`] method can produce a [`Result<U, E>`] value having a
410
//! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method
411
//! can produce a [`Result<T, F>`] value having a different error type `F`
412
//! than [`Result<T, E>`].
413
//!
414
//! | method       | self     | function input | function result | output   |
415
//! |--------------|----------|----------------|-----------------|----------|
416
//! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
417
//! | [`and_then`] | `Ok(x)`  | `x`            | `Err(d)`        | `Err(d)` |
418
//! | [`and_then`] | `Ok(x)`  | `x`            | `Ok(y)`         | `Ok(y)`  |
419
//! | [`or_else`]  | `Err(e)` | `e`            | `Err(d)`        | `Err(d)` |
420
//! | [`or_else`]  | `Err(e)` | `e`            | `Ok(y)`         | `Ok(y)`  |
421
//! | [`or_else`]  | `Ok(x)`  | (not provided) | (not evaluated) | `Ok(x)`  |
422
//!
423
//! [`and_then`]: Result::and_then
424
//! [`or_else`]: Result::or_else
425
//!
426
//! ## Comparison operators
427
//!
428
//! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will
429
//! derive its [`PartialOrd`] implementation.  With this order, an [`Ok`]
430
//! compares as less than any [`Err`], while two [`Ok`] or two [`Err`]
431
//! compare as their contained values would in `T` or `E` respectively.  If `T`
432
//! and `E` both also implement [`Ord`], then so does [`Result<T, E>`].
433
//!
434
//! ```
435
//! assert!(Ok(1) < Err(0));
436
//! let x: Result<i32, ()> = Ok(0);
437
//! let y = Ok(1);
438
//! assert!(x < y);
439
//! let x: Result<(), i32> = Err(0);
440
//! let y = Err(1);
441
//! assert!(x < y);
442
//! ```
443
//!
444
//! ## Iterating over `Result`
445
//!
446
//! A [`Result`] can be iterated over. This can be helpful if you need an
447
//! iterator that is conditionally empty. The iterator will either produce
448
//! a single value (when the [`Result`] is [`Ok`]), or produce no values
449
//! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like
450
//! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the
451
//! [`Result`] is [`Err`].
452
//!
453
//! [`Ok(v)`]: Ok
454
//! [`empty()`]: crate::iter::empty
455
//! [`once(v)`]: crate::iter::once
456
//!
457
//! Iterators over [`Result<T, E>`] come in three types:
458
//!
459
//! * [`into_iter`] consumes the [`Result`] and produces the contained
460
//!   value
461
//! * [`iter`] produces an immutable reference of type `&T` to the
462
//!   contained value
463
//! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
464
//!   contained value
465
//!
466
//! See [Iterating over `Option`] for examples of how this can be useful.
467
//!
468
//! [Iterating over `Option`]: crate::option#iterating-over-option
469
//! [`into_iter`]: Result::into_iter
470
//! [`iter`]: Result::iter
471
//! [`iter_mut`]: Result::iter_mut
472
//!
473
//! You might want to use an iterator chain to do multiple instances of an
474
//! operation that can fail, but would like to ignore failures while
475
//! continuing to process the successful results. In this example, we take
476
//! advantage of the iterable nature of [`Result`] to select only the
477
//! [`Ok`] values using [`flatten`][Iterator::flatten].
478
//!
479
//! ```
480
//! # use std::str::FromStr;
481
//! let mut results = vec![];
482
//! let mut errs = vec![];
483
//! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"]
484
//!    .into_iter()
485
//!    .map(u8::from_str)
486
//!    // Save clones of the raw `Result` values to inspect
487
//!    .inspect(|x| results.push(x.clone()))
488
//!    // Challenge: explain how this captures only the `Err` values
489
//!    .inspect(|x| errs.extend(x.clone().err()))
490
//!    .flatten()
491
//!    .collect();
492
//! assert_eq!(errs.len(), 3);
493
//! assert_eq!(nums, [17, 99]);
494
//! println!("results {results:?}");
495
//! println!("errs {errs:?}");
496
//! println!("nums {nums:?}");
497
//! ```
498
//!
499
//! ## Collecting into `Result`
500
//!
501
//! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait,
502
//! which allows an iterator over [`Result`] values to be collected into a
503
//! [`Result`] of a collection of each contained value of the original
504
//! [`Result`] values, or [`Err`] if any of the elements was [`Err`].
505
//!
506
//! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA,+E%3E%3E-for-Result%3CV,+E%3E
507
//!
508
//! ```
509
//! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)];
510
//! let res: Result<Vec<_>, &str> = v.into_iter().collect();
511
//! assert_eq!(res, Err("err!"));
512
//! let v = [Ok(2), Ok(4), Ok(8)];
513
//! let res: Result<Vec<_>, &str> = v.into_iter().collect();
514
//! assert_eq!(res, Ok(vec![2, 4, 8]));
515
//! ```
516
//!
517
//! [`Result`] also implements the [`Product`][impl-Product] and
518
//! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values
519
//! to provide the [`product`][Iterator::product] and
520
//! [`sum`][Iterator::sum] methods.
521
//!
522
//! [impl-Product]: Result#impl-Product%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E
523
//! [impl-Sum]: Result#impl-Sum%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E
524
//!
525
//! ```
526
//! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
527
//! let res: Result<i32, &str> = v.into_iter().sum();
528
//! assert_eq!(res, Err("error!"));
529
//! let v = [Ok(1), Ok(2), Ok(21)];
530
//! let res: Result<i32, &str> = v.into_iter().product();
531
//! assert_eq!(res, Ok(42));
532
//! ```
533

            
534
#![stable(feature = "rust1", since = "1.0.0")]
535

            
536
#[cfg(not(feature = "ferrocene_certified"))]
537
use crate::iter::{self, FusedIterator, TrustedLen};
538
use crate::marker::Destruct;
539
#[cfg(not(feature = "ferrocene_certified"))]
540
use crate::ops::{self, ControlFlow, Deref, DerefMut};
541
#[cfg(feature = "ferrocene_certified")]
542
use crate::ops::{Deref, DerefMut};
543
#[cfg(not(feature = "ferrocene_certified"))]
544
use crate::{convert, fmt, hint};
545

            
546
/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
547
///
548
/// See the [module documentation](self) for details.
549
#[doc(search_unbox)]
550
#[cfg_attr(
551
    not(feature = "ferrocene_certified"),
552
    derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)
553
)]
554
#[must_use = "this `Result` may be an `Err` variant, which should be handled"]
555
#[rustc_diagnostic_item = "Result"]
556
#[stable(feature = "rust1", since = "1.0.0")]
557
pub enum Result<T, E> {
558
    /// Contains the success value
559
    #[lang = "Ok"]
560
    #[stable(feature = "rust1", since = "1.0.0")]
561
    Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
562

            
563
    /// Contains the error value
564
    #[lang = "Err"]
565
    #[stable(feature = "rust1", since = "1.0.0")]
566
    Err(#[stable(feature = "rust1", since = "1.0.0")] E),
567
}
568

            
569
/////////////////////////////////////////////////////////////////////////////
570
// Type implementation
571
/////////////////////////////////////////////////////////////////////////////
572

            
573
impl<T, E> Result<T, E> {
574
    /////////////////////////////////////////////////////////////////////////
575
    // Querying the contained values
576
    /////////////////////////////////////////////////////////////////////////
577

            
578
    /// Returns `true` if the result is [`Ok`].
579
    ///
580
    /// # Examples
581
    ///
582
    /// ```
583
    /// let x: Result<i32, &str> = Ok(-3);
584
    /// assert_eq!(x.is_ok(), true);
585
    ///
586
    /// let x: Result<i32, &str> = Err("Some error message");
587
    /// assert_eq!(x.is_ok(), false);
588
    /// ```
589
    #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
590
    #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
591
    #[inline]
592
    #[stable(feature = "rust1", since = "1.0.0")]
593
761502
    pub const fn is_ok(&self) -> bool {
594
761502
        matches!(*self, Ok(_))
595
761502
    }
596

            
597
    /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate.
598
    ///
599
    /// # Examples
600
    ///
601
    /// ```
602
    /// let x: Result<u32, &str> = Ok(2);
603
    /// assert_eq!(x.is_ok_and(|x| x > 1), true);
604
    ///
605
    /// let x: Result<u32, &str> = Ok(0);
606
    /// assert_eq!(x.is_ok_and(|x| x > 1), false);
607
    ///
608
    /// let x: Result<u32, &str> = Err("hey");
609
    /// assert_eq!(x.is_ok_and(|x| x > 1), false);
610
    ///
611
    /// let x: Result<String, &str> = Ok("ownership".to_string());
612
    /// assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true);
613
    /// println!("still alive {:?}", x);
614
    /// ```
615
    #[must_use]
616
    #[inline]
617
    #[stable(feature = "is_some_and", since = "1.70.0")]
618
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
619
    pub const fn is_ok_and<F>(self, f: F) -> bool
620
    where
621
        F: [const] FnOnce(T) -> bool + [const] Destruct,
622
        T: [const] Destruct,
623
        E: [const] Destruct,
624
    {
625
        match self {
626
            Err(_) => false,
627
            Ok(x) => f(x),
628
        }
629
    }
630

            
631
    /// Returns `true` if the result is [`Err`].
632
    ///
633
    /// # Examples
634
    ///
635
    /// ```
636
    /// let x: Result<i32, &str> = Ok(-3);
637
    /// assert_eq!(x.is_err(), false);
638
    ///
639
    /// let x: Result<i32, &str> = Err("Some error message");
640
    /// assert_eq!(x.is_err(), true);
641
    /// ```
642
    #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
643
    #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
644
    #[inline]
645
    #[stable(feature = "rust1", since = "1.0.0")]
646
8250
    pub const fn is_err(&self) -> bool {
647
8250
        !self.is_ok()
648
8250
    }
649

            
650
    /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate.
651
    ///
652
    /// # Examples
653
    ///
654
    /// ```
655
    /// use std::io::{Error, ErrorKind};
656
    ///
657
    /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
658
    /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);
659
    ///
660
    /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
661
    /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
662
    ///
663
    /// let x: Result<u32, Error> = Ok(123);
664
    /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
665
    ///
666
    /// let x: Result<u32, String> = Err("ownership".to_string());
667
    /// assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true);
668
    /// println!("still alive {:?}", x);
669
    /// ```
670
    #[must_use]
671
    #[inline]
672
    #[stable(feature = "is_some_and", since = "1.70.0")]
673
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
674
    pub const fn is_err_and<F>(self, f: F) -> bool
675
    where
676
        F: [const] FnOnce(E) -> bool + [const] Destruct,
677
        E: [const] Destruct,
678
        T: [const] Destruct,
679
    {
680
        match self {
681
            Ok(_) => false,
682
            Err(e) => f(e),
683
        }
684
    }
685

            
686
    /////////////////////////////////////////////////////////////////////////
687
    // Adapter for each variant
688
    /////////////////////////////////////////////////////////////////////////
689

            
690
    /// Converts from `Result<T, E>` to [`Option<T>`].
691
    ///
692
    /// Converts `self` into an [`Option<T>`], consuming `self`,
693
    /// and discarding the error, if any.
694
    ///
695
    /// # Examples
696
    ///
697
    /// ```
698
    /// let x: Result<u32, &str> = Ok(2);
699
    /// assert_eq!(x.ok(), Some(2));
700
    ///
701
    /// let x: Result<u32, &str> = Err("Nothing here");
702
    /// assert_eq!(x.ok(), None);
703
    /// ```
704
    #[inline]
705
    #[stable(feature = "rust1", since = "1.0.0")]
706
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
707
    #[rustc_diagnostic_item = "result_ok_method"]
708
200026
    pub const fn ok(self) -> Option<T>
709
200026
    where
710
200026
        T: [const] Destruct,
711
200026
        E: [const] Destruct,
712
    {
713
200026
        match self {
714
85087
            Ok(x) => Some(x),
715
114939
            Err(_) => None,
716
        }
717
200026
    }
718

            
719
    /// Converts from `Result<T, E>` to [`Option<E>`].
720
    ///
721
    /// Converts `self` into an [`Option<E>`], consuming `self`,
722
    /// and discarding the success value, if any.
723
    ///
724
    /// # Examples
725
    ///
726
    /// ```
727
    /// let x: Result<u32, &str> = Ok(2);
728
    /// assert_eq!(x.err(), None);
729
    ///
730
    /// let x: Result<u32, &str> = Err("Nothing here");
731
    /// assert_eq!(x.err(), Some("Nothing here"));
732
    /// ```
733
    #[inline]
734
    #[stable(feature = "rust1", since = "1.0.0")]
735
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
736
2736
    pub const fn err(self) -> Option<E>
737
2736
    where
738
2736
        T: [const] Destruct,
739
2736
        E: [const] Destruct,
740
    {
741
2736
        match self {
742
2600
            Ok(_) => None,
743
136
            Err(x) => Some(x),
744
        }
745
2736
    }
746

            
747
    /////////////////////////////////////////////////////////////////////////
748
    // Adapter for working with references
749
    /////////////////////////////////////////////////////////////////////////
750

            
751
    /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
752
    ///
753
    /// Produces a new `Result`, containing a reference
754
    /// into the original, leaving the original in place.
755
    ///
756
    /// # Examples
757
    ///
758
    /// ```
759
    /// let x: Result<u32, &str> = Ok(2);
760
    /// assert_eq!(x.as_ref(), Ok(&2));
761
    ///
762
    /// let x: Result<u32, &str> = Err("Error");
763
    /// assert_eq!(x.as_ref(), Err(&"Error"));
764
    /// ```
765
    #[inline]
766
    #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
767
    #[stable(feature = "rust1", since = "1.0.0")]
768
    pub const fn as_ref(&self) -> Result<&T, &E> {
769
        match *self {
770
            Ok(ref x) => Ok(x),
771
            Err(ref x) => Err(x),
772
        }
773
    }
774

            
775
    /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
776
    ///
777
    /// # Examples
778
    ///
779
    /// ```
780
    /// fn mutate(r: &mut Result<i32, i32>) {
781
    ///     match r.as_mut() {
782
    ///         Ok(v) => *v = 42,
783
    ///         Err(e) => *e = 0,
784
    ///     }
785
    /// }
786
    ///
787
    /// let mut x: Result<i32, i32> = Ok(2);
788
    /// mutate(&mut x);
789
    /// assert_eq!(x.unwrap(), 42);
790
    ///
791
    /// let mut x: Result<i32, i32> = Err(13);
792
    /// mutate(&mut x);
793
    /// assert_eq!(x.unwrap_err(), 0);
794
    /// ```
795
    #[inline]
796
    #[stable(feature = "rust1", since = "1.0.0")]
797
    #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
798
    pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> {
799
        match *self {
800
            Ok(ref mut x) => Ok(x),
801
            Err(ref mut x) => Err(x),
802
        }
803
    }
804

            
805
    /////////////////////////////////////////////////////////////////////////
806
    // Transforming contained values
807
    /////////////////////////////////////////////////////////////////////////
808

            
809
    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
810
    /// contained [`Ok`] value, leaving an [`Err`] value untouched.
811
    ///
812
    /// This function can be used to compose the results of two functions.
813
    ///
814
    /// # Examples
815
    ///
816
    /// Print the numbers on each line of a string multiplied by two.
817
    ///
818
    /// ```
819
    /// let line = "1\n2\n3\n4\n";
820
    ///
821
    /// for num in line.lines() {
822
    ///     match num.parse::<i32>().map(|i| i * 2) {
823
    ///         Ok(n) => println!("{n}"),
824
    ///         Err(..) => {}
825
    ///     }
826
    /// }
827
    /// ```
828
    #[inline]
829
    #[stable(feature = "rust1", since = "1.0.0")]
830
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
831
20690
    pub const fn map<U, F>(self, op: F) -> Result<U, E>
832
20690
    where
833
20690
        F: [const] FnOnce(T) -> U + [const] Destruct,
834
    {
835
20690
        match self {
836
20684
            Ok(t) => Ok(op(t)),
837
6
            Err(e) => Err(e),
838
        }
839
20690
    }
840

            
841
    /// Returns the provided default (if [`Err`]), or
842
    /// applies a function to the contained value (if [`Ok`]).
843
    ///
844
    /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
845
    /// the result of a function call, it is recommended to use [`map_or_else`],
846
    /// which is lazily evaluated.
847
    ///
848
    /// [`map_or_else`]: Result::map_or_else
849
    ///
850
    /// # Examples
851
    ///
852
    /// ```
853
    /// let x: Result<_, &str> = Ok("foo");
854
    /// assert_eq!(x.map_or(42, |v| v.len()), 3);
855
    ///
856
    /// let x: Result<&str, _> = Err("bar");
857
    /// assert_eq!(x.map_or(42, |v| v.len()), 42);
858
    /// ```
859
    #[inline]
860
    #[stable(feature = "result_map_or", since = "1.41.0")]
861
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
862
    #[must_use = "if you don't need the returned value, use `if let` instead"]
863
    pub const fn map_or<U, F>(self, default: U, f: F) -> U
864
    where
865
        F: [const] FnOnce(T) -> U + [const] Destruct,
866
        T: [const] Destruct,
867
        E: [const] Destruct,
868
        U: [const] Destruct,
869
    {
870
        match self {
871
            Ok(t) => f(t),
872
            Err(_) => default,
873
        }
874
    }
875

            
876
    /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to
877
    /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value.
878
    ///
879
    /// This function can be used to unpack a successful result
880
    /// while handling an error.
881
    ///
882
    ///
883
    /// # Examples
884
    ///
885
    /// ```
886
    /// let k = 21;
887
    ///
888
    /// let x : Result<_, &str> = Ok("foo");
889
    /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
890
    ///
891
    /// let x : Result<&str, _> = Err("bar");
892
    /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
893
    /// ```
894
    #[inline]
895
    #[stable(feature = "result_map_or_else", since = "1.41.0")]
896
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
897
    pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
898
    where
899
        D: [const] FnOnce(E) -> U + [const] Destruct,
900
        F: [const] FnOnce(T) -> U + [const] Destruct,
901
    {
902
        match self {
903
            Ok(t) => f(t),
904
            Err(e) => default(e),
905
        }
906
    }
907

            
908
    /// Maps a `Result<T, E>` to a `U` by applying function `f` to the contained
909
    /// value if the result is [`Ok`], otherwise if [`Err`], returns the
910
    /// [default value] for the type `U`.
911
    ///
912
    /// # Examples
913
    ///
914
    /// ```
915
    /// #![feature(result_option_map_or_default)]
916
    ///
917
    /// let x: Result<_, &str> = Ok("foo");
918
    /// let y: Result<&str, _> = Err("bar");
919
    ///
920
    /// assert_eq!(x.map_or_default(|x| x.len()), 3);
921
    /// assert_eq!(y.map_or_default(|y| y.len()), 0);
922
    /// ```
923
    ///
924
    /// [default value]: Default::default
925
    #[inline]
926
    #[unstable(feature = "result_option_map_or_default", issue = "138099")]
927
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
928
    pub const fn map_or_default<U, F>(self, f: F) -> U
929
    where
930
        F: [const] FnOnce(T) -> U + [const] Destruct,
931
        U: [const] Default,
932
        T: [const] Destruct,
933
        E: [const] Destruct,
934
    {
935
        match self {
936
            Ok(t) => f(t),
937
            Err(_) => U::default(),
938
        }
939
    }
940

            
941
    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
942
    /// contained [`Err`] value, leaving an [`Ok`] value untouched.
943
    ///
944
    /// This function can be used to pass through a successful result while handling
945
    /// an error.
946
    ///
947
    ///
948
    /// # Examples
949
    ///
950
    /// ```
951
    /// fn stringify(x: u32) -> String { format!("error code: {x}") }
952
    ///
953
    /// let x: Result<u32, u32> = Ok(2);
954
    /// assert_eq!(x.map_err(stringify), Ok(2));
955
    ///
956
    /// let x: Result<u32, u32> = Err(13);
957
    /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
958
    /// ```
959
    #[inline]
960
    #[stable(feature = "rust1", since = "1.0.0")]
961
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
962
28140
    pub const fn map_err<F, O>(self, op: O) -> Result<T, F>
963
28140
    where
964
28140
        O: [const] FnOnce(E) -> F + [const] Destruct,
965
    {
966
28140
        match self {
967
28140
            Ok(t) => Ok(t),
968
            Err(e) => Err(op(e)),
969
        }
970
28140
    }
971

            
972
    /// Calls a function with a reference to the contained value if [`Ok`].
973
    ///
974
    /// Returns the original result.
975
    ///
976
    /// # Examples
977
    ///
978
    /// ```
979
    /// let x: u8 = "4"
980
    ///     .parse::<u8>()
981
    ///     .inspect(|x| println!("original: {x}"))
982
    ///     .map(|x| x.pow(3))
983
    ///     .expect("failed to parse number");
984
    /// ```
985
    #[inline]
986
    #[stable(feature = "result_option_inspect", since = "1.76.0")]
987
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
988
    pub const fn inspect<F>(self, f: F) -> Self
989
    where
990
        F: [const] FnOnce(&T) + [const] Destruct,
991
    {
992
        if let Ok(ref t) = self {
993
            f(t);
994
        }
995

            
996
        self
997
    }
998

            
999
    /// Calls a function with a reference to the contained value if [`Err`].
    ///
    /// Returns the original result.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::{fs, io};
    ///
    /// fn read() -> io::Result<String> {
    ///     fs::read_to_string("address.txt")
    ///         .inspect_err(|e| eprintln!("failed to read file: {e}"))
    /// }
    /// ```
    #[inline]
    #[stable(feature = "result_option_inspect", since = "1.76.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    pub const fn inspect_err<F>(self, f: F) -> Self
    where
        F: [const] FnOnce(&E) + [const] Destruct,
    {
        if let Err(ref e) = self {
            f(e);
        }
        self
    }
    /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
    ///
    /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
    /// and returns the new [`Result`].
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<String, u32> = Ok("hello".to_string());
    /// let y: Result<&str, &u32> = Ok("hello");
    /// assert_eq!(x.as_deref(), y);
    ///
    /// let x: Result<String, u32> = Err(42);
    /// let y: Result<&str, &u32> = Err(&42);
    /// assert_eq!(x.as_deref(), y);
    /// ```
    #[inline]
    #[stable(feature = "inner_deref", since = "1.47.0")]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
    pub const fn as_deref(&self) -> Result<&T::Target, &E>
    where
        T: [const] Deref,
    {
        self.as_ref().map(Deref::deref)
    }
    /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
    ///
    /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
    /// and returns the new [`Result`].
    ///
    /// # Examples
    ///
    /// ```
    /// let mut s = "HELLO".to_string();
    /// let mut x: Result<String, u32> = Ok("hello".to_string());
    /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
    /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
    ///
    /// let mut i = 42;
    /// let mut x: Result<String, u32> = Err(42);
    /// let y: Result<&mut str, &mut u32> = Err(&mut i);
    /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
    /// ```
    #[inline]
    #[stable(feature = "inner_deref", since = "1.47.0")]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
    pub const fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E>
    where
        T: [const] DerefMut,
    {
        self.as_mut().map(DerefMut::deref_mut)
    }
    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////
    /// Returns an iterator over the possibly contained value.
    ///
    /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(7);
    /// assert_eq!(x.iter().next(), Some(&7));
    ///
    /// let x: Result<u32, &str> = Err("nothing!");
    /// assert_eq!(x.iter().next(), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    // blocked on Iterator
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn iter(&self) -> Iter<'_, T> {
        Iter { inner: self.as_ref().ok() }
    }
    /// Returns a mutable iterator over the possibly contained value.
    ///
    /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x: Result<u32, &str> = Ok(7);
    /// match x.iter_mut().next() {
    ///     Some(v) => *v = 40,
    ///     None => {},
    /// }
    /// assert_eq!(x, Ok(40));
    ///
    /// let mut x: Result<u32, &str> = Err("nothing!");
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    // blocked on Iterator
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut { inner: self.as_mut().ok() }
    }
    /////////////////////////////////////////////////////////////////////////
    // Extract a value
    /////////////////////////////////////////////////////////////////////////
    /// Returns the contained [`Ok`] value, consuming the `self` value.
    ///
    /// Because this function may panic, its use is generally discouraged.
    /// Instead, prefer to use pattern matching and handle the [`Err`]
    /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
    /// [`unwrap_or_default`].
    ///
    /// [`unwrap_or`]: Result::unwrap_or
    /// [`unwrap_or_else`]: Result::unwrap_or_else
    /// [`unwrap_or_default`]: Result::unwrap_or_default
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Err`], with a panic message including the
    /// passed message, and the content of the [`Err`].
    ///
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
    /// ```
    ///
    /// # Recommended Message Style
    ///
    /// We recommend that `expect` messages are used to describe the reason you
    /// _expect_ the `Result` should be `Ok`.
    ///
    /// ```should_panic
    /// let path = std::env::var("IMPORTANT_PATH")
    ///     .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
    /// ```
    ///
    /// **Hint**: If you're having trouble remembering how to phrase expect
    /// error messages remember to focus on the word "should" as in "env
    /// variable should be set by blah" or "the given binary should be available
    /// and executable by the current user".
    ///
    /// For more detail on expect message styles and the reasoning behind our recommendation please
    /// refer to the section on ["Common Message
    /// Styles"](../../std/error/index.html#common-message-styles) in the
    /// [`std::error`](../../std/error/index.html) module docs.
    #[inline]
    #[track_caller]
    #[stable(feature = "result_expect", since = "1.4.0")]
    // blocked on Debug
    #[cfg(not(feature = "ferrocene_certified"))]
    pub fn expect(self, msg: &str) -> T
    where
        E: fmt::Debug,
    {
        match self {
            Ok(t) => t,
            Err(e) => unwrap_failed(msg, &e),
        }
    }
    /// Returns the contained [`Ok`] value, consuming the `self` value.
    ///
    /// Because this function may panic, its use is generally discouraged.
    /// Panics are meant for unrecoverable errors, and
    /// [may abort the entire program][panic-abort].
    ///
    /// Instead, prefer to use [the `?` (try) operator][try-operator], or pattern matching
    /// to handle the [`Err`] case explicitly, or call [`unwrap_or`],
    /// [`unwrap_or_else`], or [`unwrap_or_default`].
    ///
    /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
    /// [try-operator]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
    /// [`unwrap_or`]: Result::unwrap_or
    /// [`unwrap_or_else`]: Result::unwrap_or_else
    /// [`unwrap_or_default`]: Result::unwrap_or_default
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Err`], with a panic message provided by the
    /// [`Err`]'s value.
    ///
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(2);
    /// assert_eq!(x.unwrap(), 2);
    /// ```
    ///
    /// ```should_panic
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// x.unwrap(); // panics with `emergency failure`
    /// ```
    #[inline(always)]
    #[track_caller]
    #[stable(feature = "rust1", since = "1.0.0")]
    // blocked on Debug
    #[cfg(not(feature = "ferrocene_certified"))]
    pub fn unwrap(self) -> T
    where
        E: fmt::Debug,
    {
        match self {
            Ok(t) => t,
            Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
        }
    }
    /// Returns the contained [`Ok`] value or a default
    ///
    /// Consumes the `self` argument then, if [`Ok`], returns the contained
    /// value, otherwise if [`Err`], returns the default value for that
    /// type.
    ///
    /// # Examples
    ///
    /// Converts a string to an integer, turning poorly-formed strings
    /// into 0 (the default value for integers). [`parse`] converts
    /// a string to any other type that implements [`FromStr`], returning an
    /// [`Err`] on error.
    ///
    /// ```
    /// let good_year_from_input = "1909";
    /// let bad_year_from_input = "190blarg";
    /// let good_year = good_year_from_input.parse().unwrap_or_default();
    /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
    ///
    /// assert_eq!(1909, good_year);
    /// assert_eq!(0, bad_year);
    /// ```
    ///
    /// [`parse`]: str::parse
    /// [`FromStr`]: crate::str::FromStr
    #[inline]
    #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    pub const fn unwrap_or_default(self) -> T
    where
        T: [const] Default + [const] Destruct,
        E: [const] Destruct,
    {
        match self {
            Ok(x) => x,
            Err(_) => Default::default(),
        }
    }
    /// Returns the contained [`Err`] value, consuming the `self` value.
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Ok`], with a panic message including the
    /// passed message, and the content of the [`Ok`].
    ///
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// let x: Result<u32, &str> = Ok(10);
    /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "result_expect_err", since = "1.17.0")]
    // blocked on Debug
    #[cfg(not(feature = "ferrocene_certified"))]
    pub fn expect_err(self, msg: &str) -> E
    where
        T: fmt::Debug,
    {
        match self {
            Ok(t) => unwrap_failed(msg, &t),
            Err(e) => e,
        }
    }
    /// Returns the contained [`Err`] value, consuming the `self` value.
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Ok`], with a custom panic message provided
    /// by the [`Ok`]'s value.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// let x: Result<u32, &str> = Ok(2);
    /// x.unwrap_err(); // panics with `2`
    /// ```
    ///
    /// ```
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// assert_eq!(x.unwrap_err(), "emergency failure");
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "rust1", since = "1.0.0")]
    // blocked on Debug
    #[cfg(not(feature = "ferrocene_certified"))]
    pub fn unwrap_err(self) -> E
    where
        T: fmt::Debug,
    {
        match self {
            Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
            Err(e) => e,
        }
    }
    /// Returns the contained [`Ok`] value, but never panics.
    ///
    /// Unlike [`unwrap`], this method is known to never panic on the
    /// result types it is implemented for. Therefore, it can be used
    /// instead of `unwrap` as a maintainability safeguard that will fail
    /// to compile if the error type of the `Result` is later changed
    /// to an error that can actually occur.
    ///
    /// [`unwrap`]: Result::unwrap
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(never_type)]
    /// # #![feature(unwrap_infallible)]
    ///
    /// fn only_good_news() -> Result<String, !> {
    ///     Ok("this is fine".into())
    /// }
    ///
    /// let s: String = only_good_news().into_ok();
    /// println!("{s}");
    /// ```
    #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
    #[inline]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
    // blocked on !
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn into_ok(self) -> T
    where
        E: [const] Into<!>,
    {
        match self {
            Ok(x) => x,
            Err(e) => e.into(),
        }
    }
    /// Returns the contained [`Err`] value, but never panics.
    ///
    /// Unlike [`unwrap_err`], this method is known to never panic on the
    /// result types it is implemented for. Therefore, it can be used
    /// instead of `unwrap_err` as a maintainability safeguard that will fail
    /// to compile if the ok type of the `Result` is later changed
    /// to a type that can actually occur.
    ///
    /// [`unwrap_err`]: Result::unwrap_err
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(never_type)]
    /// # #![feature(unwrap_infallible)]
    ///
    /// fn only_bad_news() -> Result<!, String> {
    ///     Err("Oops, it failed".into())
    /// }
    ///
    /// let error: String = only_bad_news().into_err();
    /// println!("{error}");
    /// ```
    #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
    #[inline]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
    // blocked on !
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn into_err(self) -> E
    where
        T: [const] Into<!>,
    {
        match self {
            Ok(x) => x.into(),
            Err(e) => e,
        }
    }
    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////
    /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
    ///
    /// Arguments passed to `and` are eagerly evaluated; if you are passing the
    /// result of a function call, it is recommended to use [`and_then`], which is
    /// lazily evaluated.
    ///
    /// [`and_then`]: Result::and_then
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("late error"));
    ///
    /// let x: Result<u32, &str> = Err("early error");
    /// let y: Result<&str, &str> = Ok("foo");
    /// assert_eq!(x.and(y), Err("early error"));
    ///
    /// let x: Result<u32, &str> = Err("not a 2");
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("not a 2"));
    ///
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<&str, &str> = Ok("different result type");
    /// assert_eq!(x.and(y), Ok("different result type"));
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    pub const fn and<U>(self, res: Result<U, E>) -> Result<U, E>
    where
        T: [const] Destruct,
        E: [const] Destruct,
        U: [const] Destruct,
    {
        match self {
            Ok(_) => res,
            Err(e) => Err(e),
        }
    }
    /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
    ///
    ///
    /// This function can be used for control flow based on `Result` values.
    ///
    /// # Examples
    ///
    /// ```
    /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
    ///     x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
    /// }
    ///
    /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
    /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
    /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
    /// ```
    ///
    /// Often used to chain fallible operations that may return [`Err`].
    ///
    /// ```
    /// use std::{io::ErrorKind, path::Path};
    ///
    /// // Note: on Windows "/" maps to "C:\"
    /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
    /// assert!(root_modified_time.is_ok());
    ///
    /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
    /// assert!(should_fail.is_err());
    /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    #[rustc_confusables("flat_map", "flatmap")]
2
    pub const fn and_then<U, F>(self, op: F) -> Result<U, E>
2
    where
2
        F: [const] FnOnce(T) -> Result<U, E> + [const] Destruct,
    {
2
        match self {
2
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
2
    }
    /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
    ///
    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
    /// result of a function call, it is recommended to use [`or_else`], which is
    /// lazily evaluated.
    ///
    /// [`or_else`]: Result::or_else
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Err("late error");
    /// assert_eq!(x.or(y), Ok(2));
    ///
    /// let x: Result<u32, &str> = Err("early error");
    /// let y: Result<u32, &str> = Ok(2);
    /// assert_eq!(x.or(y), Ok(2));
    ///
    /// let x: Result<u32, &str> = Err("not a 2");
    /// let y: Result<u32, &str> = Err("late error");
    /// assert_eq!(x.or(y), Err("late error"));
    ///
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Ok(100);
    /// assert_eq!(x.or(y), Ok(2));
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    pub const fn or<F>(self, res: Result<T, F>) -> Result<T, F>
    where
        T: [const] Destruct,
        E: [const] Destruct,
        F: [const] Destruct,
    {
        match self {
            Ok(v) => Ok(v),
            Err(_) => res,
        }
    }
    /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
    ///
    /// This function can be used for control flow based on result values.
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
    ///
    /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
    /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
    /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
    /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
    pub const fn or_else<F, O>(self, op: O) -> Result<T, F>
    where
        O: [const] FnOnce(E) -> Result<T, F> + [const] Destruct,
    {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }
    /// Returns the contained [`Ok`] value or a provided default.
    ///
    /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
    /// the result of a function call, it is recommended to use [`unwrap_or_else`],
    /// which is lazily evaluated.
    ///
    /// [`unwrap_or_else`]: Result::unwrap_or_else
    ///
    /// # Examples
    ///
    /// ```
    /// let default = 2;
    /// let x: Result<u32, &str> = Ok(9);
    /// assert_eq!(x.unwrap_or(default), 9);
    ///
    /// let x: Result<u32, &str> = Err("error");
    /// assert_eq!(x.unwrap_or(default), default);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1156
    pub const fn unwrap_or(self, default: T) -> T
1156
    where
1156
        T: [const] Destruct,
1156
        E: [const] Destruct,
    {
1156
        match self {
1156
            Ok(t) => t,
            Err(_) => default,
        }
1156
    }
    /// Returns the contained [`Ok`] value or computes it from a closure.
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// fn count(x: &str) -> usize { x.len() }
    ///
    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
4107
    pub const fn unwrap_or_else<F>(self, op: F) -> T
4107
    where
4107
        F: [const] FnOnce(E) -> T + [const] Destruct,
    {
4107
        match self {
4107
            Ok(t) => t,
            Err(e) => op(e),
        }
4107
    }
    /// Returns the contained [`Ok`] value, consuming the `self` value,
    /// without checking that the value is not an [`Err`].
    ///
    /// # Safety
    ///
    /// Calling this method on an [`Err`] is *[undefined behavior]*.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(2);
    /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
    /// ```
    ///
    /// ```no_run
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// unsafe { x.unwrap_unchecked() }; // Undefined behavior!
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
    // blocked on hint
    #[cfg(not(feature = "ferrocene_certified"))]
    pub unsafe fn unwrap_unchecked(self) -> T {
        match self {
            Ok(t) => t,
            // SAFETY: the safety contract must be upheld by the caller.
            Err(_) => unsafe { hint::unreachable_unchecked() },
        }
    }
    /// Returns the contained [`Err`] value, consuming the `self` value,
    /// without checking that the value is not an [`Ok`].
    ///
    /// # Safety
    ///
    /// Calling this method on an [`Ok`] is *[undefined behavior]*.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let x: Result<u32, &str> = Ok(2);
    /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
    /// ```
    ///
    /// ```
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
    // blocked on hint
    #[cfg(not(feature = "ferrocene_certified"))]
    pub unsafe fn unwrap_err_unchecked(self) -> E {
        match self {
            // SAFETY: the safety contract must be upheld by the caller.
            Ok(_) => unsafe { hint::unreachable_unchecked() },
            Err(e) => e,
        }
    }
}
impl<T, E> Result<&T, E> {
    /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
    /// `Ok` part.
    ///
    /// # Examples
    ///
    /// ```
    /// let val = 12;
    /// let x: Result<&i32, i32> = Ok(&val);
    /// assert_eq!(x, Ok(&12));
    /// let copied = x.copied();
    /// assert_eq!(copied, Ok(12));
    /// ```
    #[inline]
    #[stable(feature = "result_copied", since = "1.59.0")]
    #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
252
    pub const fn copied(self) -> Result<T, E>
252
    where
252
        T: Copy,
    {
        // FIXME(const-hack): this implementation, which sidesteps using `Result::map` since it's not const
        // ready yet, should be reverted when possible to avoid code repetition
252
        match self {
252
            Ok(&v) => Ok(v),
            Err(e) => Err(e),
        }
252
    }
    /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
    /// `Ok` part.
    ///
    /// # Examples
    ///
    /// ```
    /// let val = 12;
    /// let x: Result<&i32, i32> = Ok(&val);
    /// assert_eq!(x, Ok(&12));
    /// let cloned = x.cloned();
    /// assert_eq!(cloned, Ok(12));
    /// ```
    #[inline]
    #[stable(feature = "result_cloned", since = "1.59.0")]
    pub fn cloned(self) -> Result<T, E>
    where
        T: Clone,
    {
        self.map(|t| t.clone())
    }
}
impl<T, E> Result<&mut T, E> {
    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
    /// `Ok` part.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut val = 12;
    /// let x: Result<&mut i32, i32> = Ok(&mut val);
    /// assert_eq!(x, Ok(&mut 12));
    /// let copied = x.copied();
    /// assert_eq!(copied, Ok(12));
    /// ```
    #[inline]
    #[stable(feature = "result_copied", since = "1.59.0")]
    #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    pub const fn copied(self) -> Result<T, E>
    where
        T: Copy,
    {
        // FIXME(const-hack): this implementation, which sidesteps using `Result::map` since it's not const
        // ready yet, should be reverted when possible to avoid code repetition
        match self {
            Ok(&mut v) => Ok(v),
            Err(e) => Err(e),
        }
    }
    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
    /// `Ok` part.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut val = 12;
    /// let x: Result<&mut i32, i32> = Ok(&mut val);
    /// assert_eq!(x, Ok(&mut 12));
    /// let cloned = x.cloned();
    /// assert_eq!(cloned, Ok(12));
    /// ```
    #[inline]
    #[stable(feature = "result_cloned", since = "1.59.0")]
    pub fn cloned(self) -> Result<T, E>
    where
        T: Clone,
    {
        self.map(|t| t.clone())
    }
}
impl<T, E> Result<Option<T>, E> {
    /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
    ///
    /// `Ok(None)` will be mapped to `None`.
    /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
    ///
    /// # Examples
    ///
    /// ```
    /// #[derive(Debug, Eq, PartialEq)]
    /// struct SomeErr;
    ///
    /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
    /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
    /// assert_eq!(x.transpose(), y);
    /// ```
    #[inline]
    #[stable(feature = "transpose_result", since = "1.33.0")]
    #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    pub const fn transpose(self) -> Option<Result<T, E>> {
        match self {
            Ok(Some(x)) => Some(Ok(x)),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}
impl<T, E> Result<Result<T, E>, E> {
    /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
    /// assert_eq!(Ok("hello"), x.flatten());
    ///
    /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
    /// assert_eq!(Err(6), x.flatten());
    ///
    /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
    /// assert_eq!(Err(6), x.flatten());
    /// ```
    ///
    /// Flattening only removes one level of nesting at a time:
    ///
    /// ```
    /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
    /// assert_eq!(Ok(Ok("hello")), x.flatten());
    /// assert_eq!(Ok("hello"), x.flatten().flatten());
    /// ```
    #[inline]
    #[stable(feature = "result_flattening", since = "1.89.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_stable(feature = "result_flattening", since = "1.89.0")]
    // blocked on const impl Drop for Result<Result<T, E>>
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn flatten(self) -> Result<T, E> {
        // FIXME(const-hack): could be written with `and_then`
        match self {
            Ok(inner) => inner,
            Err(e) => Err(e),
        }
    }
}
// This is a separate function to reduce the code size of the methods
#[cfg(not(feature = "panic_immediate_abort"))]
#[inline(never)]
#[cold]
#[track_caller]
// blocked on Debug
#[cfg(not(feature = "ferrocene_certified"))]
fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
    panic!("{msg}: {error:?}");
}
// This is a separate function to avoid constructing a `dyn Debug`
// that gets immediately thrown away, since vtables don't get cleaned up
// by dead code elimination if a trait object is constructed even if it goes
// unused
#[cfg(feature = "panic_immediate_abort")]
#[inline]
#[cold]
#[track_caller]
// blocked on Debug
#[cfg(not(feature = "ferrocene_certified"))]
const fn unwrap_failed<T>(_msg: &str, _error: &T) -> ! {
    panic!()
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E> Clone for Result<T, E>
where
    T: Clone,
    E: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Ok(x) => Ok(x.clone()),
            Err(x) => Err(x.clone()),
        }
    }
    #[inline]
    fn clone_from(&mut self, source: &Self) {
        match (self, source) {
            (Ok(to), Ok(from)) => to.clone_from(from),
            (Err(to), Err(from)) => to.clone_from(from),
            (to, from) => *to = from.clone(),
        }
    }
}
#[unstable(feature = "ergonomic_clones", issue = "132290")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E> crate::clone::UseCloned for Result<T, E>
where
    T: crate::clone::UseCloned,
    E: crate::clone::UseCloned,
{
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E> IntoIterator for Result<T, E> {
    type Item = T;
    type IntoIter = IntoIter<T>;
    /// Returns a consuming iterator over the possibly contained value.
    ///
    /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Result<u32, &str> = Ok(5);
    /// let v: Vec<u32> = x.into_iter().collect();
    /// assert_eq!(v, [5]);
    ///
    /// let x: Result<u32, &str> = Err("nothing!");
    /// let v: Vec<u32> = x.into_iter().collect();
    /// assert_eq!(v, []);
    /// ```
    #[inline]
    fn into_iter(self) -> IntoIter<T> {
        IntoIter { inner: self.ok() }
    }
}
#[stable(since = "1.4.0", feature = "result_iter")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T, E> IntoIterator for &'a Result<T, E> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;
    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}
#[stable(since = "1.4.0", feature = "result_iter")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;
    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}
/////////////////////////////////////////////////////////////////////////////
// The Result Iterators
/////////////////////////////////////////////////////////////////////////////
/// An iterator over a reference to the [`Ok`] variant of a [`Result`].
///
/// The iterator yields one value if the result is [`Ok`], otherwise none.
///
/// Created by [`Result::iter`].
#[derive(Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub struct Iter<'a, T: 'a> {
    inner: Option<&'a T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    #[inline]
    fn next(&mut self) -> Option<&'a T> {
        self.inner.take()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let n = if self.inner.is_some() { 1 } else { 0 };
        (n, Some(n))
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> {
        self.inner.take()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> ExactSizeIterator for Iter<'_, T> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> FusedIterator for Iter<'_, T> {}
#[unstable(feature = "trusted_len", issue = "37572")]
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<A> TrustedLen for Iter<'_, A> {}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> Clone for Iter<'_, T> {
    #[inline]
    fn clone(&self) -> Self {
        Iter { inner: self.inner }
    }
}
/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
///
/// Created by [`Result::iter_mut`].
#[derive(Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub struct IterMut<'a, T: 'a> {
    inner: Option<&'a mut T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;
    #[inline]
    fn next(&mut self) -> Option<&'a mut T> {
        self.inner.take()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let n = if self.inner.is_some() { 1 } else { 0 };
        (n, Some(n))
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut T> {
        self.inner.take()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> ExactSizeIterator for IterMut<'_, T> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> FusedIterator for IterMut<'_, T> {}
#[unstable(feature = "trusted_len", issue = "37572")]
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<A> TrustedLen for IterMut<'_, A> {}
/// An iterator over the value in a [`Ok`] variant of a [`Result`].
///
/// The iterator yields one value if the result is [`Ok`], otherwise none.
///
/// This struct is created by the [`into_iter`] method on
/// [`Result`] (provided by the [`IntoIterator`] trait).
///
/// [`into_iter`]: IntoIterator::into_iter
#[derive(Clone, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub struct IntoIter<T> {
    inner: Option<T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> Iterator for IntoIter<T> {
    type Item = T;
    #[inline]
    fn next(&mut self) -> Option<T> {
        self.inner.take()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let n = if self.inner.is_some() { 1 } else { 0 };
        (n, Some(n))
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> DoubleEndedIterator for IntoIter<T> {
    #[inline]
    fn next_back(&mut self) -> Option<T> {
        self.inner.take()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> ExactSizeIterator for IntoIter<T> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> FusedIterator for IntoIter<T> {}
#[unstable(feature = "trusted_len", issue = "37572")]
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<A> TrustedLen for IntoIter<A> {}
/////////////////////////////////////////////////////////////////////////////
// FromIterator
/////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
    /// Takes each element in the `Iterator`: if it is an `Err`, no further
    /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
    /// container with the values of each `Result` is returned.
    ///
    /// Here is an example which increments every integer in a vector,
    /// checking for overflow:
    ///
    /// ```
    /// let v = vec![1, 2];
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    ///     x.checked_add(1).ok_or("Overflow!")
    /// ).collect();
    /// assert_eq!(res, Ok(vec![2, 3]));
    /// ```
    ///
    /// Here is another example that tries to subtract one from another list
    /// of integers, this time checking for underflow:
    ///
    /// ```
    /// let v = vec![1, 2, 0];
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    ///     x.checked_sub(1).ok_or("Underflow!")
    /// ).collect();
    /// assert_eq!(res, Err("Underflow!"));
    /// ```
    ///
    /// Here is a variation on the previous example, showing that no
    /// further elements are taken from `iter` after the first `Err`.
    ///
    /// ```
    /// let v = vec![3, 2, 1, 10];
    /// let mut shared = 0;
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
    ///     shared += x;
    ///     x.checked_sub(2).ok_or("Underflow!")
    /// }).collect();
    /// assert_eq!(res, Err("Underflow!"));
    /// assert_eq!(shared, 6);
    /// ```
    ///
    /// Since the third element caused an underflow, no further elements were taken,
    /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
    #[inline]
10
    fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
10
        iter::try_process(iter.into_iter(), |i| i.collect())
10
    }
}
#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E> const ops::Try for Result<T, E> {
    type Output = T;
    type Residual = Result<convert::Infallible, E>;
    #[inline]
14
    fn from_output(output: Self::Output) -> Self {
14
        Ok(output)
14
    }
    #[inline]
54973
    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
54973
        match self {
54973
            Ok(v) => ControlFlow::Continue(v),
            Err(e) => ControlFlow::Break(Err(e)),
        }
54973
    }
}
#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E, F: [const] From<E>> const ops::FromResidual<Result<convert::Infallible, E>>
    for Result<T, F>
{
    #[inline]
    #[track_caller]
    fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
        match residual {
            Err(e) => Err(From::from(e)),
        }
    }
}
#[diagnostic::do_not_recommend]
#[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E, F: [const] From<E>> const ops::FromResidual<ops::Yeet<E>> for Result<T, F> {
    #[inline]
    fn from_residual(ops::Yeet(e): ops::Yeet<E>) -> Self {
        Err(From::from(e))
    }
}
#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, E> const ops::Residual<T> for Result<convert::Infallible, E> {
    type TryType = Result<T, E>;
}