1
//! Optional values.
2
//!
3
//! Type [`Option`] represents an optional value: every [`Option`]
4
//! is either [`Some`] and contains a value, or [`None`], and
5
//! does not. [`Option`] types are very common in Rust code, as
6
//! they have a number of uses:
7
//!
8
//! * Initial values
9
//! * Return values for functions that are not defined
10
//!   over their entire input range (partial functions)
11
//! * Return value for otherwise reporting simple errors, where [`None`] is
12
//!   returned on error
13
//! * Optional struct fields
14
//! * Struct fields that can be loaned or "taken"
15
//! * Optional function arguments
16
//! * Nullable pointers
17
//! * Swapping things out of difficult situations
18
//!
19
//! [`Option`]s are commonly paired with pattern matching to query the presence
20
//! of a value and take action, always accounting for the [`None`] case.
21
//!
22
//! ```
23
//! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24
//!     if denominator == 0.0 {
25
//!         None
26
//!     } else {
27
//!         Some(numerator / denominator)
28
//!     }
29
//! }
30
//!
31
//! // The return value of the function is an option
32
//! let result = divide(2.0, 3.0);
33
//!
34
//! // Pattern match to retrieve the value
35
//! match result {
36
//!     // The division was valid
37
//!     Some(x) => println!("Result: {x}"),
38
//!     // The division was invalid
39
//!     None    => println!("Cannot divide by 0"),
40
//! }
41
//! ```
42
//!
43
//
44
// FIXME: Show how `Option` is used in practice, with lots of methods
45
//
46
//! # Options and pointers ("nullable" pointers)
47
//!
48
//! Rust's pointer types must always point to a valid location; there are
49
//! no "null" references. Instead, Rust has *optional* pointers, like
50
//! the optional owned box, <code>[Option]<[Box\<T>]></code>.
51
//!
52
//! [Box\<T>]: ../../std/boxed/struct.Box.html
53
//!
54
//! The following example uses [`Option`] to create an optional box of
55
//! [`i32`]. Notice that in order to use the inner [`i32`] value, the
56
//! `check_optional` function first needs to use pattern matching to
57
//! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
58
//! not ([`None`]).
59
//!
60
//! ```
61
//! let optional = None;
62
//! check_optional(optional);
63
//!
64
//! let optional = Some(Box::new(9000));
65
//! check_optional(optional);
66
//!
67
//! fn check_optional(optional: Option<Box<i32>>) {
68
//!     match optional {
69
//!         Some(p) => println!("has value {p}"),
70
//!         None => println!("has no value"),
71
//!     }
72
//! }
73
//! ```
74
//!
75
//! # The question mark operator, `?`
76
//!
77
//! Similar to the [`Result`] type, when writing code that calls many functions that return the
78
//! [`Option`] type, handling `Some`/`None` can be tedious. The question mark
79
//! operator, [`?`], hides some of the boilerplate of propagating values
80
//! up the call stack.
81
//!
82
//! It replaces this:
83
//!
84
//! ```
85
//! # #![allow(dead_code)]
86
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
87
//!     let a = stack.pop();
88
//!     let b = stack.pop();
89
//!
90
//!     match (a, b) {
91
//!         (Some(x), Some(y)) => Some(x + y),
92
//!         _ => None,
93
//!     }
94
//! }
95
//!
96
//! ```
97
//!
98
//! With this:
99
//!
100
//! ```
101
//! # #![allow(dead_code)]
102
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
103
//!     Some(stack.pop()? + stack.pop()?)
104
//! }
105
//! ```
106
//!
107
//! *It's much nicer!*
108
//!
109
//! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the
110
//! result is [`None`], in which case [`None`] is returned early from the enclosing function.
111
//!
112
//! [`?`] can be used in functions that return [`Option`] because of the
113
//! early return of [`None`] that it provides.
114
//!
115
//! [`?`]: crate::ops::Try
116
//! [`Some`]: Some
117
//! [`None`]: None
118
//!
119
//! # Representation
120
//!
121
//! Rust guarantees to optimize the following types `T` such that
122
//! [`Option<T>`] has the same size, alignment, and [function call ABI] as `T`. In some
123
//! of these cases, Rust further guarantees the following:
124
//! - `transmute::<_, Option<T>>([0u8; size_of::<T>()])` is sound and produces
125
//!   `Option::<T>::None`
126
//! - `transmute::<_, [u8; size_of::<T>()]>(Option::<T>::None)` is sound and produces
127
//!   `[0u8; size_of::<T>()]`
128
//!
129
//! These cases are identified by the second column:
130
//!
131
//! | `T`                                                                 | Transmuting between `[0u8; size_of::<T>()]` and `Option::<T>::None` sound? |
132
//! |---------------------------------------------------------------------|----------------------------------------------------------------------------|
133
//! | [`Box<U>`] (specifically, only `Box<U, Global>`)                    | when `U: Sized`                                                            |
134
//! | `&U`                                                                | when `U: Sized`                                                            |
135
//! | `&mut U`                                                            | when `U: Sized`                                                            |
136
//! | `fn`, `extern "C" fn`[^extern_fn]                                   | always                                                                     |
137
//! | [`num::NonZero*`]                                                   | always                                                                     |
138
//! | [`ptr::NonNull<U>`]                                                 | when `U: Sized`                                                            |
139
//! | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type                                           |
140
//!
141
//! [^extern_fn]: this remains true for `unsafe` variants, any argument/return types, and any other ABI: `[unsafe] extern "abi" fn` (_e.g._, `extern "system" fn`)
142
//!
143
//! Under some conditions the above types `T` are also null pointer optimized when wrapped in a [`Result`][result_repr].
144
//!
145
//! [`Box<U>`]: ../../std/boxed/struct.Box.html
146
//! [`num::NonZero*`]: crate::num
147
//! [`ptr::NonNull<U>`]: crate::ptr::NonNull
148
//! [function call ABI]: ../primitive.fn.html#abi-compatibility
149
//! [result_repr]: crate::result#representation
150
//!
151
//! This is called the "null pointer optimization" or NPO.
152
//!
153
//! It is further guaranteed that, for the cases above, one can
154
//! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
155
//! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
156
//! is undefined behavior).
157
//!
158
//! # Method overview
159
//!
160
//! In addition to working with pattern matching, [`Option`] provides a wide
161
//! variety of different methods.
162
//!
163
//! ## Querying the variant
164
//!
165
//! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
166
//! is [`Some`] or [`None`], respectively.
167
//!
168
//! The [`is_some_and`] and [`is_none_or`] methods apply the provided function
169
//! to the contents of the [`Option`] to produce a boolean value.
170
//! If this is [`None`] then a default result is returned instead without executing the function.
171
//!
172
//! [`is_none`]: Option::is_none
173
//! [`is_some`]: Option::is_some
174
//! [`is_some_and`]: Option::is_some_and
175
//! [`is_none_or`]: Option::is_none_or
176
//!
177
//! ## Adapters for working with references
178
//!
179
//! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
180
//! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
181
//! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
182
//!   <code>[Option]<[&]T::[Target]></code>
183
//! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
184
//!   <code>[Option]<[&mut] T::[Target]></code>
185
//! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
186
//!   <code>[Option]<[Pin]<[&]T>></code>
187
//! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
188
//!   <code>[Option]<[Pin]<[&mut] T>></code>
189
//! * [`as_slice`] returns a one-element slice of the contained value, if any.
190
//!   If this is [`None`], an empty slice is returned.
191
//! * [`as_mut_slice`] returns a mutable one-element slice of the contained value, if any.
192
//!   If this is [`None`], an empty slice is returned.
193
//!
194
//! [&]: reference "shared reference"
195
//! [&mut]: reference "mutable reference"
196
//! [Target]: Deref::Target "ops::Deref::Target"
197
//! [`as_deref`]: Option::as_deref
198
//! [`as_deref_mut`]: Option::as_deref_mut
199
//! [`as_mut`]: Option::as_mut
200
//! [`as_pin_mut`]: Option::as_pin_mut
201
//! [`as_pin_ref`]: Option::as_pin_ref
202
//! [`as_ref`]: Option::as_ref
203
//! [`as_slice`]: Option::as_slice
204
//! [`as_mut_slice`]: Option::as_mut_slice
205
//!
206
//! ## Extracting the contained value
207
//!
208
//! These methods extract the contained value in an [`Option<T>`] when it
209
//! is the [`Some`] variant. If the [`Option`] is [`None`]:
210
//!
211
//! * [`expect`] panics with a provided custom message
212
//! * [`unwrap`] panics with a generic message
213
//! * [`unwrap_or`] returns the provided default value
214
//! * [`unwrap_or_default`] returns the default value of the type `T`
215
//!   (which must implement the [`Default`] trait)
216
//! * [`unwrap_or_else`] returns the result of evaluating the provided
217
//!   function
218
//! * [`unwrap_unchecked`] produces *[undefined behavior]*
219
//!
220
//! [`expect`]: Option::expect
221
//! [`unwrap`]: Option::unwrap
222
//! [`unwrap_or`]: Option::unwrap_or
223
//! [`unwrap_or_default`]: Option::unwrap_or_default
224
//! [`unwrap_or_else`]: Option::unwrap_or_else
225
//! [`unwrap_unchecked`]: Option::unwrap_unchecked
226
//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
227
//!
228
//! ## Transforming contained values
229
//!
230
//! These methods transform [`Option`] to [`Result`]:
231
//!
232
//! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
233
//!   [`Err(err)`] using the provided default `err` value
234
//! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
235
//!   a value of [`Err`] using the provided function
236
//! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
237
//!   [`Result`] of an [`Option`]
238
//!
239
//! [`Err(err)`]: Err
240
//! [`Ok(v)`]: Ok
241
//! [`Some(v)`]: Some
242
//! [`ok_or`]: Option::ok_or
243
//! [`ok_or_else`]: Option::ok_or_else
244
//! [`transpose`]: Option::transpose
245
//!
246
//! These methods transform the [`Some`] variant:
247
//!
248
//! * [`filter`] calls the provided predicate function on the contained
249
//!   value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
250
//!   if the function returns `true`; otherwise, returns [`None`]
251
//! * [`flatten`] removes one level of nesting from an [`Option<Option<T>>`]
252
//! * [`inspect`] method takes ownership of the [`Option`] and applies
253
//!   the provided function to the contained value by reference if [`Some`]
254
//! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
255
//!   provided function to the contained value of [`Some`] and leaving
256
//!   [`None`] values unchanged
257
//!
258
//! [`Some(t)`]: Some
259
//! [`filter`]: Option::filter
260
//! [`flatten`]: Option::flatten
261
//! [`inspect`]: Option::inspect
262
//! [`map`]: Option::map
263
//!
264
//! These methods transform [`Option<T>`] to a value of a possibly
265
//! different type `U`:
266
//!
267
//! * [`map_or`] applies the provided function to the contained value of
268
//!   [`Some`], or returns the provided default value if the [`Option`] is
269
//!   [`None`]
270
//! * [`map_or_else`] applies the provided function to the contained value
271
//!   of [`Some`], or returns the result of evaluating the provided
272
//!   fallback function if the [`Option`] is [`None`]
273
//!
274
//! [`map_or`]: Option::map_or
275
//! [`map_or_else`]: Option::map_or_else
276
//!
277
//! These methods combine the [`Some`] variants of two [`Option`] values:
278
//!
279
//! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
280
//!   provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
281
//! * [`zip_with`] calls the provided function `f` and returns
282
//!   [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
283
//!   [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
284
//!
285
//! [`Some(f(s, o))`]: Some
286
//! [`Some(o)`]: Some
287
//! [`Some(s)`]: Some
288
//! [`Some((s, o))`]: Some
289
//! [`zip`]: Option::zip
290
//! [`zip_with`]: Option::zip_with
291
//!
292
//! ## Boolean operators
293
//!
294
//! These methods treat the [`Option`] as a boolean value, where [`Some`]
295
//! acts like [`true`] and [`None`] acts like [`false`]. There are two
296
//! categories of these methods: ones that take an [`Option`] as input, and
297
//! ones that take a function as input (to be lazily evaluated).
298
//!
299
//! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
300
//! input, and produce an [`Option`] as output. Only the [`and`] method can
301
//! produce an [`Option<U>`] value having a different inner type `U` than
302
//! [`Option<T>`].
303
//!
304
//! | method  | self      | input     | output    |
305
//! |---------|-----------|-----------|-----------|
306
//! | [`and`] | `None`    | (ignored) | `None`    |
307
//! | [`and`] | `Some(x)` | `None`    | `None`    |
308
//! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
309
//! | [`or`]  | `None`    | `None`    | `None`    |
310
//! | [`or`]  | `None`    | `Some(y)` | `Some(y)` |
311
//! | [`or`]  | `Some(x)` | (ignored) | `Some(x)` |
312
//! | [`xor`] | `None`    | `None`    | `None`    |
313
//! | [`xor`] | `None`    | `Some(y)` | `Some(y)` |
314
//! | [`xor`] | `Some(x)` | `None`    | `Some(x)` |
315
//! | [`xor`] | `Some(x)` | `Some(y)` | `None`    |
316
//!
317
//! [`and`]: Option::and
318
//! [`or`]: Option::or
319
//! [`xor`]: Option::xor
320
//!
321
//! The [`and_then`] and [`or_else`] methods take a function as input, and
322
//! only evaluate the function when they need to produce a new value. Only
323
//! the [`and_then`] method can produce an [`Option<U>`] value having a
324
//! different inner type `U` than [`Option<T>`].
325
//!
326
//! | method       | self      | function input | function result | output    |
327
//! |--------------|-----------|----------------|-----------------|-----------|
328
//! | [`and_then`] | `None`    | (not provided) | (not evaluated) | `None`    |
329
//! | [`and_then`] | `Some(x)` | `x`            | `None`          | `None`    |
330
//! | [`and_then`] | `Some(x)` | `x`            | `Some(y)`       | `Some(y)` |
331
//! | [`or_else`]  | `None`    | (not provided) | `None`          | `None`    |
332
//! | [`or_else`]  | `None`    | (not provided) | `Some(y)`       | `Some(y)` |
333
//! | [`or_else`]  | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
334
//!
335
//! [`and_then`]: Option::and_then
336
//! [`or_else`]: Option::or_else
337
//!
338
//! This is an example of using methods like [`and_then`] and [`or`] in a
339
//! pipeline of method calls. Early stages of the pipeline pass failure
340
//! values ([`None`]) through unchanged, and continue processing on
341
//! success values ([`Some`]). Toward the end, [`or`] substitutes an error
342
//! message if it receives [`None`].
343
//!
344
//! ```
345
//! # use std::collections::BTreeMap;
346
//! let mut bt = BTreeMap::new();
347
//! bt.insert(20u8, "foo");
348
//! bt.insert(42u8, "bar");
349
//! let res = [0u8, 1, 11, 200, 22]
350
//!     .into_iter()
351
//!     .map(|x| {
352
//!         // `checked_sub()` returns `None` on error
353
//!         x.checked_sub(1)
354
//!             // same with `checked_mul()`
355
//!             .and_then(|x| x.checked_mul(2))
356
//!             // `BTreeMap::get` returns `None` on error
357
//!             .and_then(|x| bt.get(&x))
358
//!             // Substitute an error message if we have `None` so far
359
//!             .or(Some(&"error!"))
360
//!             .copied()
361
//!             // Won't panic because we unconditionally used `Some` above
362
//!             .unwrap()
363
//!     })
364
//!     .collect::<Vec<_>>();
365
//! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
366
//! ```
367
//!
368
//! ## Comparison operators
369
//!
370
//! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
371
//! [`PartialOrd`] implementation.  With this order, [`None`] compares as
372
//! less than any [`Some`], and two [`Some`] compare the same way as their
373
//! contained values would in `T`.  If `T` also implements
374
//! [`Ord`], then so does [`Option<T>`].
375
//!
376
//! ```
377
//! assert!(None < Some(0));
378
//! assert!(Some(0) < Some(1));
379
//! ```
380
//!
381
//! ## Iterating over `Option`
382
//!
383
//! An [`Option`] can be iterated over. This can be helpful if you need an
384
//! iterator that is conditionally empty. The iterator will either produce
385
//! a single value (when the [`Option`] is [`Some`]), or produce no values
386
//! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
387
//! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
388
//! the [`Option`] is [`None`].
389
//!
390
//! [`Some(v)`]: Some
391
//! [`empty()`]: crate::iter::empty
392
//! [`once(v)`]: crate::iter::once
393
//!
394
//! Iterators over [`Option<T>`] come in three types:
395
//!
396
//! * [`into_iter`] consumes the [`Option`] and produces the contained
397
//!   value
398
//! * [`iter`] produces an immutable reference of type `&T` to the
399
//!   contained value
400
//! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
401
//!   contained value
402
//!
403
//! [`into_iter`]: Option::into_iter
404
//! [`iter`]: Option::iter
405
//! [`iter_mut`]: Option::iter_mut
406
//!
407
//! An iterator over [`Option`] can be useful when chaining iterators, for
408
//! example, to conditionally insert items. (It's not always necessary to
409
//! explicitly call an iterator constructor: many [`Iterator`] methods that
410
//! accept other iterators will also accept iterable types that implement
411
//! [`IntoIterator`], which includes [`Option`].)
412
//!
413
//! ```
414
//! let yep = Some(42);
415
//! let nope = None;
416
//! // chain() already calls into_iter(), so we don't have to do so
417
//! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
418
//! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
419
//! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
420
//! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
421
//! ```
422
//!
423
//! One reason to chain iterators in this way is that a function returning
424
//! `impl Iterator` must have all possible return values be of the same
425
//! concrete type. Chaining an iterated [`Option`] can help with that.
426
//!
427
//! ```
428
//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
429
//!     // Explicit returns to illustrate return types matching
430
//!     match do_insert {
431
//!         true => return (0..4).chain(Some(42)).chain(4..8),
432
//!         false => return (0..4).chain(None).chain(4..8),
433
//!     }
434
//! }
435
//! println!("{:?}", make_iter(true).collect::<Vec<_>>());
436
//! println!("{:?}", make_iter(false).collect::<Vec<_>>());
437
//! ```
438
//!
439
//! If we try to do the same thing, but using [`once()`] and [`empty()`],
440
//! we can't return `impl Iterator` anymore because the concrete types of
441
//! the return values differ.
442
//!
443
//! [`empty()`]: crate::iter::empty
444
//! [`once()`]: crate::iter::once
445
//!
446
//! ```compile_fail,E0308
447
//! # use std::iter::{empty, once};
448
//! // This won't compile because all possible returns from the function
449
//! // must have the same concrete type.
450
//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
451
//!     // Explicit returns to illustrate return types not matching
452
//!     match do_insert {
453
//!         true => return (0..4).chain(once(42)).chain(4..8),
454
//!         false => return (0..4).chain(empty()).chain(4..8),
455
//!     }
456
//! }
457
//! ```
458
//!
459
//! ## Collecting into `Option`
460
//!
461
//! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
462
//! which allows an iterator over [`Option`] values to be collected into an
463
//! [`Option`] of a collection of each contained value of the original
464
//! [`Option`] values, or [`None`] if any of the elements was [`None`].
465
//!
466
//! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E
467
//!
468
//! ```
469
//! let v = [Some(2), Some(4), None, Some(8)];
470
//! let res: Option<Vec<_>> = v.into_iter().collect();
471
//! assert_eq!(res, None);
472
//! let v = [Some(2), Some(4), Some(8)];
473
//! let res: Option<Vec<_>> = v.into_iter().collect();
474
//! assert_eq!(res, Some(vec![2, 4, 8]));
475
//! ```
476
//!
477
//! [`Option`] also implements the [`Product`][impl-Product] and
478
//! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
479
//! to provide the [`product`][Iterator::product] and
480
//! [`sum`][Iterator::sum] methods.
481
//!
482
//! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E
483
//! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E
484
//!
485
//! ```
486
//! let v = [None, Some(1), Some(2), Some(3)];
487
//! let res: Option<i32> = v.into_iter().sum();
488
//! assert_eq!(res, None);
489
//! let v = [Some(1), Some(2), Some(21)];
490
//! let res: Option<i32> = v.into_iter().product();
491
//! assert_eq!(res, Some(42));
492
//! ```
493
//!
494
//! ## Modifying an [`Option`] in-place
495
//!
496
//! These methods return a mutable reference to the contained value of an
497
//! [`Option<T>`]:
498
//!
499
//! * [`insert`] inserts a value, dropping any old contents
500
//! * [`get_or_insert`] gets the current value, inserting a provided
501
//!   default value if it is [`None`]
502
//! * [`get_or_insert_default`] gets the current value, inserting the
503
//!   default value of type `T` (which must implement [`Default`]) if it is
504
//!   [`None`]
505
//! * [`get_or_insert_with`] gets the current value, inserting a default
506
//!   computed by the provided function if it is [`None`]
507
//!
508
//! [`get_or_insert`]: Option::get_or_insert
509
//! [`get_or_insert_default`]: Option::get_or_insert_default
510
//! [`get_or_insert_with`]: Option::get_or_insert_with
511
//! [`insert`]: Option::insert
512
//!
513
//! These methods transfer ownership of the contained value of an
514
//! [`Option`]:
515
//!
516
//! * [`take`] takes ownership of the contained value of an [`Option`], if
517
//!   any, replacing the [`Option`] with [`None`]
518
//! * [`replace`] takes ownership of the contained value of an [`Option`],
519
//!   if any, replacing the [`Option`] with a [`Some`] containing the
520
//!   provided value
521
//!
522
//! [`replace`]: Option::replace
523
//! [`take`]: Option::take
524
//!
525
//! # Examples
526
//!
527
//! Basic pattern matching on [`Option`]:
528
//!
529
//! ```
530
//! let msg = Some("howdy");
531
//!
532
//! // Take a reference to the contained string
533
//! if let Some(m) = &msg {
534
//!     println!("{}", *m);
535
//! }
536
//!
537
//! // Remove the contained string, destroying the Option
538
//! let unwrapped_msg = msg.unwrap_or("default message");
539
//! ```
540
//!
541
//! Initialize a result to [`None`] before a loop:
542
//!
543
//! ```
544
//! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
545
//!
546
//! // A list of data to search through.
547
//! let all_the_big_things = [
548
//!     Kingdom::Plant(250, "redwood"),
549
//!     Kingdom::Plant(230, "noble fir"),
550
//!     Kingdom::Plant(229, "sugar pine"),
551
//!     Kingdom::Animal(25, "blue whale"),
552
//!     Kingdom::Animal(19, "fin whale"),
553
//!     Kingdom::Animal(15, "north pacific right whale"),
554
//! ];
555
//!
556
//! // We're going to search for the name of the biggest animal,
557
//! // but to start with we've just got `None`.
558
//! let mut name_of_biggest_animal = None;
559
//! let mut size_of_biggest_animal = 0;
560
//! for big_thing in &all_the_big_things {
561
//!     match *big_thing {
562
//!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
563
//!             // Now we've found the name of some big animal
564
//!             size_of_biggest_animal = size;
565
//!             name_of_biggest_animal = Some(name);
566
//!         }
567
//!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
568
//!     }
569
//! }
570
//!
571
//! match name_of_biggest_animal {
572
//!     Some(name) => println!("the biggest animal is {name}"),
573
//!     None => println!("there are no animals :("),
574
//! }
575
//! ```
576

            
577
#![stable(feature = "rust1", since = "1.0.0")]
578

            
579
#[cfg(not(feature = "ferrocene_certified"))]
580
use crate::iter::{self, FusedIterator, TrustedLen};
581
use crate::marker::Destruct;
582
#[cfg(not(feature = "ferrocene_certified"))]
583
use crate::ops::{self, ControlFlow, Deref, DerefMut};
584
#[cfg(feature = "ferrocene_certified")]
585
use crate::ops::{Deref, DerefMut};
586
#[cfg(not(feature = "ferrocene_certified"))]
587
use crate::panicking::{panic, panic_display};
588
#[cfg(not(feature = "ferrocene_certified"))]
589
use crate::pin::Pin;
590
#[cfg(not(feature = "ferrocene_certified"))]
591
use crate::{cmp, convert, hint, mem, slice};
592

            
593
/// The `Option` type. See [the module level documentation](self) for more.
594
#[doc(search_unbox)]
595
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Eq, Debug, Hash))]
596
#[rustc_diagnostic_item = "Option"]
597
#[lang = "Option"]
598
#[stable(feature = "rust1", since = "1.0.0")]
599
#[allow(clippy::derived_hash_with_manual_eq)] // PartialEq is manually implemented equivalently
600
pub enum Option<T> {
601
    /// No value.
602
    #[lang = "None"]
603
    #[stable(feature = "rust1", since = "1.0.0")]
604
    None,
605
    /// Some value of type `T`.
606
    #[lang = "Some"]
607
    #[stable(feature = "rust1", since = "1.0.0")]
608
    Some(#[stable(feature = "rust1", since = "1.0.0")] T),
609
}
610

            
611
/////////////////////////////////////////////////////////////////////////////
612
// Type implementation
613
/////////////////////////////////////////////////////////////////////////////
614

            
615
impl<T> Option<T> {
616
    /////////////////////////////////////////////////////////////////////////
617
    // Querying the contained values
618
    /////////////////////////////////////////////////////////////////////////
619

            
620
    /// Returns `true` if the option is a [`Some`] value.
621
    ///
622
    /// # Examples
623
    ///
624
    /// ```
625
    /// let x: Option<u32> = Some(2);
626
    /// assert_eq!(x.is_some(), true);
627
    ///
628
    /// let x: Option<u32> = None;
629
    /// assert_eq!(x.is_some(), false);
630
    /// ```
631
    #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
632
    #[inline]
633
    #[stable(feature = "rust1", since = "1.0.0")]
634
    #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
635
1241395
    pub const fn is_some(&self) -> bool {
636
1241395
        matches!(*self, Some(_))
637
1241395
    }
638

            
639
    /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
640
    ///
641
    /// # Examples
642
    ///
643
    /// ```
644
    /// let x: Option<u32> = Some(2);
645
    /// assert_eq!(x.is_some_and(|x| x > 1), true);
646
    ///
647
    /// let x: Option<u32> = Some(0);
648
    /// assert_eq!(x.is_some_and(|x| x > 1), false);
649
    ///
650
    /// let x: Option<u32> = None;
651
    /// assert_eq!(x.is_some_and(|x| x > 1), false);
652
    ///
653
    /// let x: Option<String> = Some("ownership".to_string());
654
    /// assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true);
655
    /// println!("still alive {:?}", x);
656
    /// ```
657
    #[must_use]
658
    #[inline]
659
    #[stable(feature = "is_some_and", since = "1.70.0")]
660
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
661
8288
    pub const fn is_some_and(self, f: impl [const] FnOnce(T) -> bool + [const] Destruct) -> bool {
662
8288
        match self {
663
            None => false,
664
8288
            Some(x) => f(x),
665
        }
666
8288
    }
667

            
668
    /// Returns `true` if the option is a [`None`] value.
669
    ///
670
    /// # Examples
671
    ///
672
    /// ```
673
    /// let x: Option<u32> = Some(2);
674
    /// assert_eq!(x.is_none(), false);
675
    ///
676
    /// let x: Option<u32> = None;
677
    /// assert_eq!(x.is_none(), true);
678
    /// ```
679
    #[must_use = "if you intended to assert that this doesn't have a value, consider \
680
                  wrapping this in an `assert!()` instead"]
681
    #[inline]
682
    #[stable(feature = "rust1", since = "1.0.0")]
683
    #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
684
    #[cfg(not(feature = "ferrocene_certified"))]
685
    pub const fn is_none(&self) -> bool {
686
        !self.is_some()
687
    }
688

            
689
    /// Returns `true` if the option is a [`None`] or the value inside of it matches a predicate.
690
    ///
691
    /// # Examples
692
    ///
693
    /// ```
694
    /// let x: Option<u32> = Some(2);
695
    /// assert_eq!(x.is_none_or(|x| x > 1), true);
696
    ///
697
    /// let x: Option<u32> = Some(0);
698
    /// assert_eq!(x.is_none_or(|x| x > 1), false);
699
    ///
700
    /// let x: Option<u32> = None;
701
    /// assert_eq!(x.is_none_or(|x| x > 1), true);
702
    ///
703
    /// let x: Option<String> = Some("ownership".to_string());
704
    /// assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true);
705
    /// println!("still alive {:?}", x);
706
    /// ```
707
    #[must_use]
708
    #[inline]
709
    #[stable(feature = "is_none_or", since = "1.82.0")]
710
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
711
193
    pub const fn is_none_or(self, f: impl [const] FnOnce(T) -> bool + [const] Destruct) -> bool {
712
193
        match self {
713
2
            None => true,
714
191
            Some(x) => f(x),
715
        }
716
193
    }
717

            
718
    /////////////////////////////////////////////////////////////////////////
719
    // Adapter for working with references
720
    /////////////////////////////////////////////////////////////////////////
721

            
722
    /// Converts from `&Option<T>` to `Option<&T>`.
723
    ///
724
    /// # Examples
725
    ///
726
    /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code>
727
    /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
728
    /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a
729
    /// reference to the value inside the original.
730
    ///
731
    /// [`map`]: Option::map
732
    /// [String]: ../../std/string/struct.String.html "String"
733
    /// [`String`]: ../../std/string/struct.String.html "String"
734
    ///
735
    /// ```
736
    /// let text: Option<String> = Some("Hello, world!".to_string());
737
    /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
738
    /// // then consume *that* with `map`, leaving `text` on the stack.
739
    /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
740
    /// println!("still can print text: {text:?}");
741
    /// ```
742
    #[inline]
743
    #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
744
    #[stable(feature = "rust1", since = "1.0.0")]
745
13795
    pub const fn as_ref(&self) -> Option<&T> {
746
13795
        match *self {
747
175
            Some(ref x) => Some(x),
748
13620
            None => None,
749
        }
750
13795
    }
751

            
752
    /// Converts from `&mut Option<T>` to `Option<&mut T>`.
753
    ///
754
    /// # Examples
755
    ///
756
    /// ```
757
    /// let mut x = Some(2);
758
    /// match x.as_mut() {
759
    ///     Some(v) => *v = 42,
760
    ///     None => {},
761
    /// }
762
    /// assert_eq!(x, Some(42));
763
    /// ```
764
    #[inline]
765
    #[stable(feature = "rust1", since = "1.0.0")]
766
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
767
4001004
    pub const fn as_mut(&mut self) -> Option<&mut T> {
768
4001004
        match *self {
769
3001004
            Some(ref mut x) => Some(x),
770
1000000
            None => None,
771
        }
772
4001004
    }
773

            
774
    /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
775
    ///
776
    /// [&]: reference "shared reference"
777
    #[inline]
778
    #[must_use]
779
    #[stable(feature = "pin", since = "1.33.0")]
780
    #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
781
    #[cfg(not(feature = "ferrocene_certified"))]
782
    pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
783
        // FIXME(const-hack): use `map` once that is possible
784
        match Pin::get_ref(self).as_ref() {
785
            // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
786
            // which is pinned.
787
            Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
788
            None => None,
789
        }
790
    }
791

            
792
    /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
793
    ///
794
    /// [&mut]: reference "mutable reference"
795
    #[inline]
796
    #[must_use]
797
    #[stable(feature = "pin", since = "1.33.0")]
798
    #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
799
    #[cfg(not(feature = "ferrocene_certified"))]
800
    pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
801
        // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
802
        // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
803
        unsafe {
804
            // FIXME(const-hack): use `map` once that is possible
805
            match Pin::get_unchecked_mut(self).as_mut() {
806
                Some(x) => Some(Pin::new_unchecked(x)),
807
                None => None,
808
            }
809
        }
810
    }
811

            
812
    #[inline]
813
    #[cfg(not(feature = "ferrocene_certified"))]
814
    const fn len(&self) -> usize {
815
        // Using the intrinsic avoids emitting a branch to get the 0 or 1.
816
        let discriminant: isize = crate::intrinsics::discriminant_value(self);
817
        discriminant as usize
818
    }
819

            
820
    /// Returns a slice of the contained value, if any. If this is `None`, an
821
    /// empty slice is returned. This can be useful to have a single type of
822
    /// iterator over an `Option` or slice.
823
    ///
824
    /// Note: Should you have an `Option<&T>` and wish to get a slice of `T`,
825
    /// you can unpack it via `opt.map_or(&[], std::slice::from_ref)`.
826
    ///
827
    /// # Examples
828
    ///
829
    /// ```rust
830
    /// assert_eq!(
831
    ///     [Some(1234).as_slice(), None.as_slice()],
832
    ///     [&[1234][..], &[][..]],
833
    /// );
834
    /// ```
835
    ///
836
    /// The inverse of this function is (discounting
837
    /// borrowing) [`[_]::first`](slice::first):
838
    ///
839
    /// ```rust
840
    /// for i in [Some(1234_u16), None] {
841
    ///     assert_eq!(i.as_ref(), i.as_slice().first());
842
    /// }
843
    /// ```
844
    #[inline]
845
    #[must_use]
846
    #[stable(feature = "option_as_slice", since = "1.75.0")]
847
    #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
848
    #[cfg(not(feature = "ferrocene_certified"))]
849
    pub const fn as_slice(&self) -> &[T] {
850
        // SAFETY: When the `Option` is `Some`, we're using the actual pointer
851
        // to the payload, with a length of 1, so this is equivalent to
852
        // `slice::from_ref`, and thus is safe.
853
        // When the `Option` is `None`, the length used is 0, so to be safe it
854
        // just needs to be aligned, which it is because `&self` is aligned and
855
        // the offset used is a multiple of alignment.
856
        //
857
        // Here we assume that `offset_of!` always returns an offset to an
858
        // in-bounds and correctly aligned position for a `T` (even if in the
859
        // `None` case it's just padding).
860
        unsafe {
861
            slice::from_raw_parts(
862
                (self as *const Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
863
                self.len(),
864
            )
865
        }
866
    }
867

            
868
    /// Returns a mutable slice of the contained value, if any. If this is
869
    /// `None`, an empty slice is returned. This can be useful to have a
870
    /// single type of iterator over an `Option` or slice.
871
    ///
872
    /// Note: Should you have an `Option<&mut T>` instead of a
873
    /// `&mut Option<T>`, which this method takes, you can obtain a mutable
874
    /// slice via `opt.map_or(&mut [], std::slice::from_mut)`.
875
    ///
876
    /// # Examples
877
    ///
878
    /// ```rust
879
    /// assert_eq!(
880
    ///     [Some(1234).as_mut_slice(), None.as_mut_slice()],
881
    ///     [&mut [1234][..], &mut [][..]],
882
    /// );
883
    /// ```
884
    ///
885
    /// The result is a mutable slice of zero or one items that points into
886
    /// our original `Option`:
887
    ///
888
    /// ```rust
889
    /// let mut x = Some(1234);
890
    /// x.as_mut_slice()[0] += 1;
891
    /// assert_eq!(x, Some(1235));
892
    /// ```
893
    ///
894
    /// The inverse of this method (discounting borrowing)
895
    /// is [`[_]::first_mut`](slice::first_mut):
896
    ///
897
    /// ```rust
898
    /// assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
899
    /// ```
900
    #[inline]
901
    #[must_use]
902
    #[stable(feature = "option_as_slice", since = "1.75.0")]
903
    #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
904
    #[cfg(not(feature = "ferrocene_certified"))]
905
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
906
        // SAFETY: When the `Option` is `Some`, we're using the actual pointer
907
        // to the payload, with a length of 1, so this is equivalent to
908
        // `slice::from_mut`, and thus is safe.
909
        // When the `Option` is `None`, the length used is 0, so to be safe it
910
        // just needs to be aligned, which it is because `&self` is aligned and
911
        // the offset used is a multiple of alignment.
912
        //
913
        // In the new version, the intrinsic creates a `*const T` from a
914
        // mutable reference  so it is safe to cast back to a mutable pointer
915
        // here. As with `as_slice`, the intrinsic always returns a pointer to
916
        // an in-bounds and correctly aligned position for a `T` (even if in
917
        // the `None` case it's just padding).
918
        unsafe {
919
            slice::from_raw_parts_mut(
920
                (self as *mut Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
921
                self.len(),
922
            )
923
        }
924
    }
925

            
926
    /////////////////////////////////////////////////////////////////////////
927
    // Getting to contained values
928
    /////////////////////////////////////////////////////////////////////////
929

            
930
    /// Returns the contained [`Some`] value, consuming the `self` value.
931
    ///
932
    /// # Panics
933
    ///
934
    /// Panics if the value is a [`None`] with a custom panic message provided by
935
    /// `msg`.
936
    ///
937
    /// # Examples
938
    ///
939
    /// ```
940
    /// let x = Some("value");
941
    /// assert_eq!(x.expect("fruits are healthy"), "value");
942
    /// ```
943
    ///
944
    /// ```should_panic
945
    /// let x: Option<&str> = None;
946
    /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
947
    /// ```
948
    ///
949
    /// # Recommended Message Style
950
    ///
951
    /// We recommend that `expect` messages are used to describe the reason you
952
    /// _expect_ the `Option` should be `Some`.
953
    ///
954
    /// ```should_panic
955
    /// # let slice: &[u8] = &[];
956
    /// let item = slice.get(0)
957
    ///     .expect("slice should not be empty");
958
    /// ```
959
    ///
960
    /// **Hint**: If you're having trouble remembering how to phrase expect
961
    /// error messages remember to focus on the word "should" as in "env
962
    /// variable should be set by blah" or "the given binary should be available
963
    /// and executable by the current user".
964
    ///
965
    /// For more detail on expect message styles and the reasoning behind our
966
    /// recommendation please refer to the section on ["Common Message
967
    /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
968
    #[inline]
969
    #[track_caller]
970
    #[stable(feature = "rust1", since = "1.0.0")]
971
    #[rustc_diagnostic_item = "option_expect"]
972
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
973
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
974
    #[cfg(not(feature = "ferrocene_certified"))]
975
    pub const fn expect(self, msg: &str) -> T {
976
        match self {
977
            Some(val) => val,
978
            None => expect_failed(msg),
979
        }
980
    }
981

            
982
    /// Returns the contained [`Some`] value, consuming the `self` value.
983
    ///
984
    /// Because this function may panic, its use is generally discouraged.
985
    /// Panics are meant for unrecoverable errors, and
986
    /// [may abort the entire program][panic-abort].
987
    ///
988
    /// Instead, prefer to use pattern matching and handle the [`None`]
989
    /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
990
    /// [`unwrap_or_default`]. In functions returning `Option`, you can use
991
    /// [the `?` (try) operator][try-option].
992
    ///
993
    /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
994
    /// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used
995
    /// [`unwrap_or`]: Option::unwrap_or
996
    /// [`unwrap_or_else`]: Option::unwrap_or_else
997
    /// [`unwrap_or_default`]: Option::unwrap_or_default
998
    ///
999
    /// # Panics
    ///
    /// Panics if the self value equals [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("air");
    /// assert_eq!(x.unwrap(), "air");
    /// ```
    ///
    /// ```should_panic
    /// let x: Option<&str> = None;
    /// assert_eq!(x.unwrap(), "air"); // fails
    /// ```
    #[inline(always)]
    #[track_caller]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_diagnostic_item = "option_unwrap"]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn unwrap(self) -> T {
        match self {
            Some(val) => val,
            None => unwrap_failed(),
        }
    }
    /// Returns the contained [`Some`] 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`]: Option::unwrap_or_else
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(Some("car").unwrap_or("bike"), "car");
    /// assert_eq!(None.unwrap_or("bike"), "bike");
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
123
    pub const fn unwrap_or(self, default: T) -> T
123
    where
123
        T: [const] Destruct,
    {
123
        match self {
115
            Some(x) => x,
8
            None => default,
        }
123
    }
    /// Returns the contained [`Some`] value or computes it from a closure.
    ///
    /// # Examples
    ///
    /// ```
    /// let k = 10;
    /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
    /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
2744
    pub const fn unwrap_or_else<F>(self, f: F) -> T
2744
    where
2744
        F: [const] FnOnce() -> T + [const] Destruct,
    {
2744
        match self {
            Some(x) => x,
2744
            None => f(),
        }
2744
    }
    /// Returns the contained [`Some`] value or a default.
    ///
    /// Consumes the `self` argument then, if [`Some`], returns the contained
    /// value, otherwise if [`None`], returns the [default value] for that
    /// type.
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Option<u32> = None;
    /// let y: Option<u32> = Some(12);
    ///
    /// assert_eq!(x.unwrap_or_default(), 0);
    /// assert_eq!(y.unwrap_or_default(), 12);
    /// ```
    ///
    /// [default value]: Default::default
    /// [`parse`]: str::parse
    /// [`FromStr`]: crate::str::FromStr
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn unwrap_or_default(self) -> T
    where
        T: [const] Default,
    {
        match self {
            Some(x) => x,
            None => T::default(),
        }
    }
    /// Returns the contained [`Some`] value, consuming the `self` value,
    /// without checking that the value is not [`None`].
    ///
    /// # Safety
    ///
    /// Calling this method on [`None`] is *[undefined behavior]*.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("air");
    /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
    /// ```
    ///
    /// ```no_run
    /// let x: Option<&str> = None;
    /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
    /// ```
    #[inline]
    #[track_caller]
    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const unsafe fn unwrap_unchecked(self) -> T {
        match self {
            Some(val) => val,
            // SAFETY: the safety contract must be upheld by the caller.
            None => unsafe { hint::unreachable_unchecked() },
        }
    }
    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////
    /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`).
    ///
    /// # Examples
    ///
    /// Calculates the length of an <code>Option<[String]></code> as an
    /// <code>Option<[usize]></code>, consuming the original:
    ///
    /// [String]: ../../std/string/struct.String.html "String"
    /// ```
    /// let maybe_some_string = Some(String::from("Hello, World!"));
    /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
    /// let maybe_some_len = maybe_some_string.map(|s| s.len());
    /// assert_eq!(maybe_some_len, Some(13));
    ///
    /// let x: Option<&str> = None;
    /// assert_eq!(x.map(|s| s.len()), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
3180302
    pub const fn map<U, F>(self, f: F) -> Option<U>
3180302
    where
3180302
        F: [const] FnOnce(T) -> U + [const] Destruct,
    {
3180302
        match self {
3173525
            Some(x) => Some(f(x)),
6777
            None => None,
        }
3180302
    }
    /// Calls a function with a reference to the contained value if [`Some`].
    ///
    /// Returns the original option.
    ///
    /// # Examples
    ///
    /// ```
    /// let list = vec![1, 2, 3];
    ///
    /// // prints "got: 2"
    /// let x = list
    ///     .get(1)
    ///     .inspect(|x| println!("got: {x}"))
    ///     .expect("list should be long enough");
    ///
    /// // prints nothing
    /// list.get(5).inspect(|x| println!("got: {x}"));
    /// ```
    #[inline]
    #[stable(feature = "result_option_inspect", since = "1.76.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn inspect<F>(self, f: F) -> Self
    where
        F: [const] FnOnce(&T) + [const] Destruct,
    {
        if let Some(ref x) = self {
            f(x);
        }
        self
    }
    /// Returns the provided default result (if none),
    /// or applies a function to the contained value (if any).
    ///
    /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
    /// the result of a function call, it is recommended to use [`map_or_else`],
    /// which is lazily evaluated.
    ///
    /// [`map_or_else`]: Option::map_or_else
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("foo");
    /// assert_eq!(x.map_or(42, |v| v.len()), 3);
    ///
    /// let x: Option<&str> = None;
    /// assert_eq!(x.map_or(42, |v| v.len()), 42);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[must_use = "if you don't need the returned value, use `if let` instead"]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
192
    pub const fn map_or<U, F>(self, default: U, f: F) -> U
192
    where
192
        F: [const] FnOnce(T) -> U + [const] Destruct,
192
        U: [const] Destruct,
    {
192
        match self {
20
            Some(t) => f(t),
172
            None => default,
        }
192
    }
    /// Computes a default function result (if none), or
    /// applies a different function to the contained value (if any).
    ///
    /// # Basic examples
    ///
    /// ```
    /// let k = 21;
    ///
    /// let x = Some("foo");
    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
    ///
    /// let x: Option<&str> = None;
    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
    /// ```
    ///
    /// # Handling a Result-based fallback
    ///
    /// A somewhat common occurrence when dealing with optional values
    /// in combination with [`Result<T, E>`] is the case where one wants to invoke
    /// a fallible fallback if the option is not present.  This example
    /// parses a command line argument (if present), or the contents of a file to
    /// an integer.  However, unlike accessing the command line argument, reading
    /// the file is fallible, so it must be wrapped with `Ok`.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let v: u64 = std::env::args()
    ///    .nth(1)
    ///    .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
    ///    .parse()?;
    /// #   Ok(())
    /// # }
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
5639
    pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
5639
    where
5639
        D: [const] FnOnce() -> U + [const] Destruct,
5639
        F: [const] FnOnce(T) -> U + [const] Destruct,
    {
5639
        match self {
            Some(t) => f(t),
5639
            None => default(),
        }
5639
    }
    /// Maps an `Option<T>` to a `U` by applying function `f` to the contained
    /// value if the option is [`Some`], otherwise if [`None`], returns the
    /// [default value] for the type `U`.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(result_option_map_or_default)]
    ///
    /// let x: Option<&str> = Some("hi");
    /// let y: Option<&str> = None;
    ///
    /// assert_eq!(x.map_or_default(|x| x.len()), 2);
    /// assert_eq!(y.map_or_default(|y| y.len()), 0);
    /// ```
    ///
    /// [default value]: Default::default
    #[inline]
    #[unstable(feature = "result_option_map_or_default", issue = "138099")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn map_or_default<U, F>(self, f: F) -> U
    where
        U: [const] Default,
        F: [const] FnOnce(T) -> U + [const] Destruct,
    {
        match self {
            Some(t) => f(t),
            None => U::default(),
        }
    }
    /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
    /// [`Ok(v)`] and [`None`] to [`Err(err)`].
    ///
    /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
    /// result of a function call, it is recommended to use [`ok_or_else`], which is
    /// lazily evaluated.
    ///
    /// [`Ok(v)`]: Ok
    /// [`Err(err)`]: Err
    /// [`Some(v)`]: Some
    /// [`ok_or_else`]: Option::ok_or_else
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("foo");
    /// assert_eq!(x.ok_or(0), Ok("foo"));
    ///
    /// let x: Option<&str> = None;
    /// assert_eq!(x.ok_or(0), Err(0));
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
21686
    pub const fn ok_or<E: [const] Destruct>(self, err: E) -> Result<T, E> {
21686
        match self {
21686
            Some(v) => Ok(v),
            None => Err(err),
        }
21686
    }
    /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
    /// [`Ok(v)`] and [`None`] to [`Err(err())`].
    ///
    /// [`Ok(v)`]: Ok
    /// [`Err(err())`]: Err
    /// [`Some(v)`]: Some
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("foo");
    /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
    ///
    /// let x: Option<&str> = None;
    /// assert_eq!(x.ok_or_else(|| 0), Err(0));
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
38
    pub const fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
38
    where
38
        F: [const] FnOnce() -> E + [const] Destruct,
    {
38
        match self {
38
            Some(v) => Ok(v),
            None => Err(err()),
        }
38
    }
    /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
    ///
    /// Leaves the original Option in-place, creating a new one with a reference
    /// to the original one, additionally coercing the contents via [`Deref`].
    ///
    /// # Examples
    ///
    /// ```
    /// let x: Option<String> = Some("hey".to_owned());
    /// assert_eq!(x.as_deref(), Some("hey"));
    ///
    /// let x: Option<String> = None;
    /// assert_eq!(x.as_deref(), None);
    /// ```
    #[inline]
    #[stable(feature = "option_deref", since = "1.40.0")]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2777
    pub const fn as_deref(&self) -> Option<&T::Target>
2777
    where
2777
        T: [const] Deref,
    {
2777
        self.as_ref().map(Deref::deref)
2777
    }
    /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
    ///
    /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
    /// the inner type's [`Deref::Target`] type.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x: Option<String> = Some("hey".to_owned());
    /// assert_eq!(x.as_deref_mut().map(|x| {
    ///     x.make_ascii_uppercase();
    ///     x
    /// }), Some("HEY".to_owned().as_mut_str()));
    /// ```
    #[inline]
    #[stable(feature = "option_deref", since = "1.40.0")]
    #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
    pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
    where
        T: [const] DerefMut,
    {
        self.as_mut().map(DerefMut::deref_mut)
    }
    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////
    /// Returns an iterator over the possibly contained value.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some(4);
    /// assert_eq!(x.iter().next(), Some(&4));
    ///
    /// let x: Option<u32> = None;
    /// assert_eq!(x.iter().next(), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn iter(&self) -> Iter<'_, T> {
        Iter { inner: Item { opt: self.as_ref() } }
    }
    /// Returns a mutable iterator over the possibly contained value.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = Some(4);
    /// match x.iter_mut().next() {
    ///     Some(v) => *v = 42,
    ///     None => {},
    /// }
    /// assert_eq!(x, Some(42));
    ///
    /// let mut x: Option<u32> = None;
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut { inner: Item { opt: self.as_mut() } }
    }
    /////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////
    /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
    ///
    /// 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`]: Option::and_then
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some(2);
    /// let y: Option<&str> = None;
    /// assert_eq!(x.and(y), None);
    ///
    /// let x: Option<u32> = None;
    /// let y = Some("foo");
    /// assert_eq!(x.and(y), None);
    ///
    /// let x = Some(2);
    /// let y = Some("foo");
    /// assert_eq!(x.and(y), Some("foo"));
    ///
    /// let x: Option<u32> = None;
    /// let y: Option<&str> = None;
    /// assert_eq!(x.and(y), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn and<U>(self, optb: Option<U>) -> Option<U>
    where
        T: [const] Destruct,
        U: [const] Destruct,
    {
        match self {
            Some(_) => optb,
            None => None,
        }
    }
    /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
    /// wrapped value and returns the result.
    ///
    /// Some languages call this operation flatmap.
    ///
    /// # Examples
    ///
    /// ```
    /// fn sq_then_to_string(x: u32) -> Option<String> {
    ///     x.checked_mul(x).map(|sq| sq.to_string())
    /// }
    ///
    /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
    /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
    /// assert_eq!(None.and_then(sq_then_to_string), None);
    /// ```
    ///
    /// Often used to chain fallible operations that may return [`None`].
    ///
    /// ```
    /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
    ///
    /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
    /// assert_eq!(item_0_1, Some(&"A1"));
    ///
    /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
    /// assert_eq!(item_2_0, None);
    /// ```
    #[doc(alias = "flatmap")]
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_confusables("flat_map", "flatmap")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
250
    pub const fn and_then<U, F>(self, f: F) -> Option<U>
250
    where
250
        F: [const] FnOnce(T) -> Option<U> + [const] Destruct,
    {
250
        match self {
240
            Some(x) => f(x),
10
            None => None,
        }
250
    }
    /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
    /// with the wrapped value and returns:
    ///
    /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
    ///   value), and
    /// - [`None`] if `predicate` returns `false`.
    ///
    /// This function works similar to [`Iterator::filter()`]. You can imagine
    /// the `Option<T>` being an iterator over one or zero elements. `filter()`
    /// lets you decide which elements to keep.
    ///
    /// # Examples
    ///
    /// ```rust
    /// fn is_even(n: &i32) -> bool {
    ///     n % 2 == 0
    /// }
    ///
    /// assert_eq!(None.filter(is_even), None);
    /// assert_eq!(Some(3).filter(is_even), None);
    /// assert_eq!(Some(4).filter(is_even), Some(4));
    /// ```
    ///
    /// [`Some(t)`]: Some
    #[inline]
    #[stable(feature = "option_filter", since = "1.27.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
2
    pub const fn filter<P>(self, predicate: P) -> Self
2
    where
2
        P: [const] FnOnce(&T) -> bool + [const] Destruct,
2
        T: [const] Destruct,
    {
2
        if let Some(x) = self {
            if predicate(&x) {
                return Some(x);
            }
2
        }
2
        None
2
    }
    /// Returns the option if it contains a value, otherwise returns `optb`.
    ///
    /// 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`]: Option::or_else
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some(2);
    /// let y = None;
    /// assert_eq!(x.or(y), Some(2));
    ///
    /// let x = None;
    /// let y = Some(100);
    /// assert_eq!(x.or(y), Some(100));
    ///
    /// let x = Some(2);
    /// let y = Some(100);
    /// assert_eq!(x.or(y), Some(2));
    ///
    /// let x: Option<u32> = None;
    /// let y = None;
    /// assert_eq!(x.or(y), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn or(self, optb: Option<T>) -> Option<T>
    where
        T: [const] Destruct,
    {
        match self {
            x @ Some(_) => x,
            None => optb,
        }
    }
    /// Returns the option if it contains a value, otherwise calls `f` and
    /// returns the result.
    ///
    /// # Examples
    ///
    /// ```
    /// fn nobody() -> Option<&'static str> { None }
    /// fn vikings() -> Option<&'static str> { Some("vikings") }
    ///
    /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
    /// assert_eq!(None.or_else(vikings), Some("vikings"));
    /// assert_eq!(None.or_else(nobody), None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
2000086
    pub const fn or_else<F>(self, f: F) -> Option<T>
2000086
    where
2000086
        F: [const] FnOnce() -> Option<T> + [const] Destruct,
2000086
        //FIXME(const_hack): this `T: ~const Destruct` is unnecessary, but even precise live drops can't tell
2000086
        // no value of type `T` gets dropped here
2000086
        T: [const] Destruct,
    {
2000086
        match self {
1000053
            x @ Some(_) => x,
1000033
            None => f(),
        }
2000086
    }
    /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some(2);
    /// let y: Option<u32> = None;
    /// assert_eq!(x.xor(y), Some(2));
    ///
    /// let x: Option<u32> = None;
    /// let y = Some(2);
    /// assert_eq!(x.xor(y), Some(2));
    ///
    /// let x = Some(2);
    /// let y = Some(2);
    /// assert_eq!(x.xor(y), None);
    ///
    /// let x: Option<u32> = None;
    /// let y: Option<u32> = None;
    /// assert_eq!(x.xor(y), None);
    /// ```
    #[inline]
    #[stable(feature = "option_xor", since = "1.37.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn xor(self, optb: Option<T>) -> Option<T>
    where
        T: [const] Destruct,
    {
        match (self, optb) {
            (a @ Some(_), None) => a,
            (None, b @ Some(_)) => b,
            _ => None,
        }
    }
    /////////////////////////////////////////////////////////////////////////
    // Entry-like operations to insert a value and return a reference
    /////////////////////////////////////////////////////////////////////////
    /// Inserts `value` into the option, then returns a mutable reference to it.
    ///
    /// If the option already contains a value, the old value is dropped.
    ///
    /// See also [`Option::get_or_insert`], which doesn't update the value if
    /// the option already contains [`Some`].
    ///
    /// # Example
    ///
    /// ```
    /// let mut opt = None;
    /// let val = opt.insert(1);
    /// assert_eq!(*val, 1);
    /// assert_eq!(opt.unwrap(), 1);
    /// let val = opt.insert(2);
    /// assert_eq!(*val, 2);
    /// *val = 3;
    /// assert_eq!(opt.unwrap(), 3);
    /// ```
    #[must_use = "if you intended to set a value, consider assignment instead"]
    #[inline]
    #[stable(feature = "option_insert", since = "1.53.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn insert(&mut self, value: T) -> &mut T
    where
        T: [const] Destruct,
    {
        *self = Some(value);
        // SAFETY: the code above just filled the option
        unsafe { self.as_mut().unwrap_unchecked() }
    }
    /// Inserts `value` into the option if it is [`None`], then
    /// returns a mutable reference to the contained value.
    ///
    /// See also [`Option::insert`], which updates the value even if
    /// the option already contains [`Some`].
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = None;
    ///
    /// {
    ///     let y: &mut u32 = x.get_or_insert(5);
    ///     assert_eq!(y, &5);
    ///
    ///     *y = 7;
    /// }
    ///
    /// assert_eq!(x, Some(7));
    /// ```
    #[inline]
    #[stable(feature = "option_entry", since = "1.20.0")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub fn get_or_insert(&mut self, value: T) -> &mut T {
        self.get_or_insert_with(|| value)
    }
    /// Inserts the default value into the option if it is [`None`], then
    /// returns a mutable reference to the contained value.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = None;
    ///
    /// {
    ///     let y: &mut u32 = x.get_or_insert_default();
    ///     assert_eq!(y, &0);
    ///
    ///     *y = 7;
    /// }
    ///
    /// assert_eq!(x, Some(7));
    /// ```
    #[inline]
    #[stable(feature = "option_get_or_insert_default", since = "1.83.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn get_or_insert_default(&mut self) -> &mut T
    where
        T: [const] Default + [const] Destruct,
    {
        self.get_or_insert_with(T::default)
    }
    /// Inserts a value computed from `f` into the option if it is [`None`],
    /// then returns a mutable reference to the contained value.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = None;
    ///
    /// {
    ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
    ///     assert_eq!(y, &5);
    ///
    ///     *y = 7;
    /// }
    ///
    /// assert_eq!(x, Some(7));
    /// ```
    #[inline]
    #[stable(feature = "option_entry", since = "1.20.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
    where
        F: [const] FnOnce() -> T + [const] Destruct,
        T: [const] Destruct,
    {
        if let None = self {
            *self = Some(f());
        }
        // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
        // variant in the code above.
        unsafe { self.as_mut().unwrap_unchecked() }
    }
    /////////////////////////////////////////////////////////////////////////
    // Misc
    /////////////////////////////////////////////////////////////////////////
    /// Takes the value out of the option, leaving a [`None`] in its place.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = Some(2);
    /// let y = x.take();
    /// assert_eq!(x, None);
    /// assert_eq!(y, Some(2));
    ///
    /// let mut x: Option<u32> = None;
    /// let y = x.take();
    /// assert_eq!(x, None);
    /// assert_eq!(y, None);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn take(&mut self) -> Option<T> {
        // FIXME(const-hack) replace `mem::replace` by `mem::take` when the latter is const ready
        mem::replace(self, None)
    }
    /// Takes the value out of the option, but only if the predicate evaluates to
    /// `true` on a mutable reference to the value.
    ///
    /// In other words, replaces `self` with `None` if the predicate returns `true`.
    /// This method operates similar to [`Option::take`] but conditional.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = Some(42);
    ///
    /// let prev = x.take_if(|v| if *v == 42 {
    ///     *v += 1;
    ///     false
    /// } else {
    ///     false
    /// });
    /// assert_eq!(x, Some(43));
    /// assert_eq!(prev, None);
    ///
    /// let prev = x.take_if(|v| *v == 43);
    /// assert_eq!(x, None);
    /// assert_eq!(prev, Some(43));
    /// ```
    #[inline]
    #[stable(feature = "option_take_if", since = "1.80.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn take_if<P>(&mut self, predicate: P) -> Option<T>
    where
        P: [const] FnOnce(&mut T) -> bool + [const] Destruct,
    {
        if self.as_mut().map_or(false, predicate) { self.take() } else { None }
    }
    /// Replaces the actual value in the option by the value given in parameter,
    /// returning the old value if present,
    /// leaving a [`Some`] in its place without deinitializing either one.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = Some(2);
    /// let old = x.replace(5);
    /// assert_eq!(x, Some(5));
    /// assert_eq!(old, Some(2));
    ///
    /// let mut x = None;
    /// let old = x.replace(3);
    /// assert_eq!(x, Some(3));
    /// assert_eq!(old, None);
    /// ```
    #[inline]
    #[stable(feature = "option_replace", since = "1.31.0")]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn replace(&mut self, value: T) -> Option<T> {
        mem::replace(self, Some(value))
    }
    /// Zips `self` with another `Option`.
    ///
    /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
    /// Otherwise, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some(1);
    /// let y = Some("hi");
    /// let z = None::<u8>;
    ///
    /// assert_eq!(x.zip(y), Some((1, "hi")));
    /// assert_eq!(x.zip(z), None);
    /// ```
    #[stable(feature = "option_zip_option", since = "1.46.0")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    pub const fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
    where
        T: [const] Destruct,
        U: [const] Destruct,
    {
        match (self, other) {
            (Some(a), Some(b)) => Some((a, b)),
            _ => None,
        }
    }
    /// Zips `self` and another `Option` with function `f`.
    ///
    /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
    /// Otherwise, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(option_zip)]
    ///
    /// #[derive(Debug, PartialEq)]
    /// struct Point {
    ///     x: f64,
    ///     y: f64,
    /// }
    ///
    /// impl Point {
    ///     fn new(x: f64, y: f64) -> Self {
    ///         Self { x, y }
    ///     }
    /// }
    ///
    /// let x = Some(17.5);
    /// let y = Some(42.7);
    ///
    /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
    /// assert_eq!(x.zip_with(None, Point::new), None);
    /// ```
    #[unstable(feature = "option_zip", issue = "70086")]
    #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
    #[cfg(not(feature = "ferrocene_certified"))]
    pub const fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
    where
        F: [const] FnOnce(T, U) -> R + [const] Destruct,
        T: [const] Destruct,
        U: [const] Destruct,
    {
        match (self, other) {
            (Some(a), Some(b)) => Some(f(a, b)),
            _ => None,
        }
    }
    /// Reduces two options into one, using the provided function if both are `Some`.
    ///
    /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
    /// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
    /// If both `self` and `other` are `None`, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(option_reduce)]
    ///
    /// let s12 = Some(12);
    /// let s17 = Some(17);
    /// let n = None;
    /// let f = |a, b| a + b;
    ///
    /// assert_eq!(s12.reduce(s17, f), Some(29));
    /// assert_eq!(s12.reduce(n, f), Some(12));
    /// assert_eq!(n.reduce(s17, f), Some(17));
    /// assert_eq!(n.reduce(n, f), None);
    /// ```
    #[unstable(feature = "option_reduce", issue = "144273")]
    pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
    where
        T: Into<R>,
        U: Into<R>,
        F: FnOnce(T, U) -> R,
    {
        match (self, other) {
            (Some(a), Some(b)) => Some(f(a, b)),
            (Some(a), _) => Some(a.into()),
            (_, Some(b)) => Some(b.into()),
            _ => None,
        }
    }
}
impl<T, U> Option<(T, U)> {
    /// Unzips an option containing a tuple of two options.
    ///
    /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
    /// Otherwise, `(None, None)` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some((1, "hi"));
    /// let y = None::<(u8, u32)>;
    ///
    /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
    /// assert_eq!(y.unzip(), (None, None));
    /// ```
    #[inline]
    #[stable(feature = "unzip_option", since = "1.66.0")]
    pub fn unzip(self) -> (Option<T>, Option<U>) {
        match self {
            Some((a, b)) => (Some(a), Some(b)),
            None => (None, None),
        }
    }
}
impl<T> Option<&T> {
    /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
    /// option.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = 12;
    /// let opt_x = Some(&x);
    /// assert_eq!(opt_x, Some(&12));
    /// let copied = opt_x.copied();
    /// assert_eq!(copied, Some(12));
    /// ```
    #[must_use = "`self` will be dropped if the result is not used"]
    #[stable(feature = "copied", since = "1.35.0")]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
183720
    pub const fn copied(self) -> Option<T>
183720
    where
183720
        T: Copy,
    {
        // FIXME(const-hack): this implementation, which sidesteps using `Option::map` since it's not const
        // ready yet, should be reverted when possible to avoid code repetition
183720
        match self {
178137
            Some(&v) => Some(v),
5583
            None => None,
        }
183720
    }
    /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
    /// option.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = 12;
    /// let opt_x = Some(&x);
    /// assert_eq!(opt_x, Some(&12));
    /// let cloned = opt_x.cloned();
    /// assert_eq!(cloned, Some(12));
    /// ```
    #[must_use = "`self` will be dropped if the result is not used"]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn cloned(self) -> Option<T>
    where
        T: Clone,
    {
        match self {
            Some(t) => Some(t.clone()),
            None => None,
        }
    }
}
impl<T> Option<&mut T> {
    /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
    /// option.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = 12;
    /// let opt_x = Some(&mut x);
    /// assert_eq!(opt_x, Some(&mut 12));
    /// let copied = opt_x.copied();
    /// assert_eq!(copied, Some(12));
    /// ```
    #[must_use = "`self` will be dropped if the result is not used"]
    #[stable(feature = "copied", since = "1.35.0")]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    pub const fn copied(self) -> Option<T>
    where
        T: Copy,
    {
        match self {
            Some(&mut t) => Some(t),
            None => None,
        }
    }
    /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
    /// option.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut x = 12;
    /// let opt_x = Some(&mut x);
    /// assert_eq!(opt_x, Some(&mut 12));
    /// let cloned = opt_x.cloned();
    /// assert_eq!(cloned, Some(12));
    /// ```
    #[must_use = "`self` will be dropped if the result is not used"]
    #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
    pub fn cloned(self) -> Option<T>
    where
        T: Clone,
    {
        match self {
            Some(t) => Some(t.clone()),
            None => None,
        }
    }
}
impl<T, E> Option<Result<T, E>> {
    /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
    ///
    /// <code>[Some]\([Ok]\(\_))</code> is mapped to <code>[Ok]\([Some]\(\_))</code>,
    /// <code>[Some]\([Err]\(\_))</code> is mapped to <code>[Err]\(\_)</code>,
    /// and [`None`] will be mapped to <code>[Ok]\([None])</code>.
    ///
    /// # Examples
    ///
    /// ```
    /// #[derive(Debug, Eq, PartialEq)]
    /// struct SomeErr;
    ///
    /// let x: Option<Result<i32, SomeErr>> = Some(Ok(5));
    /// let y: Result<Option<i32>, SomeErr> = Ok(Some(5));
    /// assert_eq!(x.transpose(), y);
    /// ```
    #[inline]
    #[stable(feature = "transpose_result", since = "1.33.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    pub const fn transpose(self) -> Result<Option<T>, E> {
        match self {
            Some(Ok(x)) => Ok(Some(x)),
            Some(Err(e)) => Err(e),
            None => Ok(None),
        }
    }
}
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
#[cfg_attr(feature = "panic_immediate_abort", inline)]
#[cold]
#[track_caller]
#[cfg(not(feature = "ferrocene_certified"))]
const fn unwrap_failed() -> ! {
    panic("called `Option::unwrap()` on a `None` value")
}
// This is a separate function to reduce the code size of .expect() itself.
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
#[cfg_attr(feature = "panic_immediate_abort", inline)]
#[cold]
#[track_caller]
#[cfg(not(feature = "ferrocene_certified"))]
const fn expect_failed(msg: &str) -> ! {
    panic_display(&msg)
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
impl<T> const Clone for Option<T>
where
    // FIXME(const_hack): the T: ~const Destruct should be inferred from the Self: ~const Destruct in clone_from.
    // See https://github.com/rust-lang/rust/issues/144207
    T: [const] Clone + [const] Destruct,
{
    #[inline]
19376
    fn clone(&self) -> Self {
19376
        match self {
185
            Some(x) => Some(x.clone()),
19191
            None => None,
        }
19376
    }
    #[inline]
    fn clone_from(&mut self, source: &Self) {
        match (self, source) {
            (Some(to), Some(from)) => to.clone_from(from),
            (to, from) => *to = from.clone(),
        }
    }
}
#[unstable(feature = "ergonomic_clones", issue = "132290")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> crate::clone::UseCloned for Option<T> where T: crate::clone::UseCloned {}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_default", issue = "143894")]
impl<T> const Default for Option<T> {
    /// Returns [`None`][Option::None].
    ///
    /// # Examples
    ///
    /// ```
    /// let opt: Option<u32> = Option::default();
    /// assert!(opt.is_none());
    /// ```
    #[inline]
1373
    fn default() -> Option<T> {
1373
        None
1373
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> IntoIterator for Option<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;
    /// Returns a consuming iterator over the possibly contained value.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Some("string");
    /// let v: Vec<&str> = x.into_iter().collect();
    /// assert_eq!(v, ["string"]);
    ///
    /// let x = None;
    /// let v: Vec<&str> = x.into_iter().collect();
    /// assert!(v.is_empty());
    /// ```
    #[inline]
4000000
    fn into_iter(self) -> IntoIter<T> {
4000000
        IntoIter { inner: Item { opt: self } }
4000000
    }
}
#[stable(since = "1.4.0", feature = "option_iter")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> IntoIterator for &'a Option<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;
    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}
#[stable(since = "1.4.0", feature = "option_iter")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T> IntoIterator for &'a mut Option<T> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;
    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}
#[stable(since = "1.12.0", feature = "option_from")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl<T> const From<T> for Option<T> {
    /// Moves `val` into a new [`Some`].
    ///
    /// # Examples
    ///
    /// ```
    /// let o: Option<u8> = Option::from(67);
    ///
    /// assert_eq!(Some(67), o);
    /// ```
    fn from(val: T) -> Option<T> {
        Some(val)
    }
}
#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
    /// Converts from `&Option<T>` to `Option<&T>`.
    ///
    /// # Examples
    ///
    /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
    /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
    /// so this technique uses `from` to first take an [`Option`] to a reference
    /// to the value inside the original.
    ///
    /// [`map`]: Option::map
    /// [String]: ../../std/string/struct.String.html "String"
    ///
    /// ```
    /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
    /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
    ///
    /// println!("Can still print s: {s:?}");
    ///
    /// assert_eq!(o, Some(18));
    /// ```
    fn from(o: &'a Option<T>) -> Option<&'a T> {
        o.as_ref()
    }
}
#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> {
    /// Converts from `&mut Option<T>` to `Option<&mut T>`
    ///
    /// # Examples
    ///
    /// ```
    /// let mut s = Some(String::from("Hello"));
    /// let o: Option<&mut String> = Option::from(&mut s);
    ///
    /// match o {
    ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
    ///     None => (),
    /// }
    ///
    /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
    /// ```
    fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
        o.as_mut()
    }
}
// Ideally, LLVM should be able to optimize our derive code to this.
// Once https://github.com/llvm/llvm-project/issues/52622 is fixed, we can
// go back to deriving `PartialEq`.
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> crate::marker::StructuralPartialEq for Option<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: [const] PartialEq> const PartialEq for Option<T> {
    #[inline]
8359
    fn eq(&self, other: &Self) -> bool {
        // Spelling out the cases explicitly optimizes better than
        // `_ => false`
8359
        match (self, other) {
8358
            (Some(l), Some(r)) => *l == *r,
            (Some(_), None) => false,
1
            (None, Some(_)) => false,
            (None, None) => true,
        }
8359
    }
}
// Manually implementing here somewhat improves codegen for
// https://github.com/rust-lang/rust/issues/49892, although still
// not optimal.
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PartialOrd> PartialOrd for Option<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        match (self, other) {
            (Some(l), Some(r)) => l.partial_cmp(r),
            (Some(_), None) => Some(cmp::Ordering::Greater),
            (None, Some(_)) => Some(cmp::Ordering::Less),
            (None, None) => Some(cmp::Ordering::Equal),
        }
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: Ord> Ord for Option<T> {
    #[inline]
49995
    fn cmp(&self, other: &Self) -> cmp::Ordering {
49995
        match (self, other) {
9999
            (Some(l), Some(r)) => l.cmp(r),
4
            (Some(_), None) => cmp::Ordering::Greater,
22666
            (None, Some(_)) => cmp::Ordering::Less,
17326
            (None, None) => cmp::Ordering::Equal,
        }
49995
    }
}
/////////////////////////////////////////////////////////////////////////////
// The Option Iterators
/////////////////////////////////////////////////////////////////////////////
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, Debug))]
struct Item<A> {
    #[allow(dead_code)]
    opt: Option<A>,
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> Iterator for Item<A> {
    type Item = A;
    #[inline]
8000000
    fn next(&mut self) -> Option<A> {
8000000
        self.opt.take()
8000000
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> DoubleEndedIterator for Item<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        self.opt.take()
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> ExactSizeIterator for Item<A> {
    #[inline]
    fn len(&self) -> usize {
        self.opt.len()
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> FusedIterator for Item<A> {}
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<A> TrustedLen for Item<A> {}
/// An iterator over a reference to the [`Some`] variant of an [`Option`].
///
/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
///
/// This `struct` is created by the [`Option::iter`] function.
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Debug))]
pub struct Iter<'a, A: 'a> {
    #[cfg_attr(feature = "ferrocene_certified", allow(dead_code))]
    inner: Item<&'a A>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, A> Iterator for Iter<'a, A> {
    type Item = &'a A;
    #[inline]
    fn next(&mut self) -> Option<&'a A> {
        self.inner.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a A> {
        self.inner.next_back()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> ExactSizeIterator for Iter<'_, A> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> FusedIterator for Iter<'_, A> {}
#[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<A> Clone for Iter<'_, A> {
    #[inline]
    fn clone(&self) -> Self {
        Iter { inner: self.inner.clone() }
    }
}
/// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
///
/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
///
/// This `struct` is created by the [`Option::iter_mut`] function.
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Debug))]
pub struct IterMut<'a, A: 'a> {
    #[cfg_attr(feature = "ferrocene_certified", allow(dead_code))]
    inner: Item<&'a mut A>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, A> Iterator for IterMut<'a, A> {
    type Item = &'a mut A;
    #[inline]
    fn next(&mut self) -> Option<&'a mut A> {
        self.inner.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut A> {
        self.inner.next_back()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> ExactSizeIterator for IterMut<'_, A> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> FusedIterator for IterMut<'_, A> {}
#[unstable(feature = "trusted_len", issue = "37572")]
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<A> TrustedLen for IterMut<'_, A> {}
/// An iterator over the value in [`Some`] variant of an [`Option`].
///
/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
///
/// This `struct` is created by the [`Option::into_iter`] function.
#[derive(Clone, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub struct IntoIter<A> {
    inner: Item<A>,
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> Iterator for IntoIter<A> {
    type Item = A;
    #[inline]
8000000
    fn next(&mut self) -> Option<A> {
8000000
        self.inner.next()
8000000
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> DoubleEndedIterator for IntoIter<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        self.inner.next_back()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> ExactSizeIterator for IntoIter<A> {}
#[stable(feature = "fused", since = "1.26.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<A> FusedIterator for IntoIter<A> {}
#[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, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
    /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
    /// no further elements are taken, and the [`None`][Option::None] is
    /// returned. Should no [`None`][Option::None] occur, a container of type
    /// `V` containing the values of each [`Option`] is returned.
    ///
    /// # Examples
    ///
    /// Here is an example which increments every integer in a vector.
    /// We use the checked variant of `add` that returns `None` when the
    /// calculation would result in an overflow.
    ///
    /// ```
    /// let items = vec![0_u16, 1, 2];
    ///
    /// let res: Option<Vec<u16>> = items
    ///     .iter()
    ///     .map(|x| x.checked_add(1))
    ///     .collect();
    ///
    /// assert_eq!(res, Some(vec![1, 2, 3]));
    /// ```
    ///
    /// As you can see, this will return the expected, valid items.
    ///
    /// Here is another example that tries to subtract one from another list
    /// of integers, this time checking for underflow:
    ///
    /// ```
    /// let items = vec![2_u16, 1, 0];
    ///
    /// let res: Option<Vec<u16>> = items
    ///     .iter()
    ///     .map(|x| x.checked_sub(1))
    ///     .collect();
    ///
    /// assert_eq!(res, None);
    /// ```
    ///
    /// Since the last element is zero, it would underflow. Thus, the resulting
    /// value is `None`.
    ///
    /// Here is a variation on the previous example, showing that no
    /// further elements are taken from `iter` after the first `None`.
    ///
    /// ```
    /// let items = vec![3_u16, 2, 1, 10];
    ///
    /// let mut shared = 0;
    ///
    /// let res: Option<Vec<u16>> = items
    ///     .iter()
    ///     .map(|x| { shared += x; x.checked_sub(2) })
    ///     .collect();
    ///
    /// assert_eq!(res, None);
    /// 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]
    fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.
        iter::try_process(iter.into_iter(), |i| i.collect())
    }
}
#[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> const ops::Try for Option<T> {
    type Output = T;
    type Residual = Option<convert::Infallible>;
    #[inline]
    fn from_output(output: Self::Output) -> Self {
        Some(output)
    }
    #[inline]
8560051
    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
8560051
        match self {
7551223
            Some(v) => ControlFlow::Continue(v),
1008828
            None => ControlFlow::Break(None),
        }
8560051
    }
}
#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
// Note: manually specifying the residual type instead of using the default to work around
// https://github.com/rust-lang/rust/issues/99940
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> const ops::FromResidual<Option<convert::Infallible>> for Option<T> {
    #[inline]
1008828
    fn from_residual(residual: Option<convert::Infallible>) -> Self {
1008828
        match residual {
1008828
            None => None,
        }
1008828
    }
}
#[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> const ops::FromResidual<ops::Yeet<()>> for Option<T> {
    #[inline]
    fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self {
        None
    }
}
#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
#[rustc_const_unstable(feature = "const_try", issue = "74935")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> const ops::Residual<T> for Option<convert::Infallible> {
    type TryType = Option<T>;
}
impl<T> Option<Option<T>> {
    /// Converts from `Option<Option<T>>` to `Option<T>`.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let x: Option<Option<u32>> = Some(Some(6));
    /// assert_eq!(Some(6), x.flatten());
    ///
    /// let x: Option<Option<u32>> = Some(None);
    /// assert_eq!(None, x.flatten());
    ///
    /// let x: Option<Option<u32>> = None;
    /// assert_eq!(None, x.flatten());
    /// ```
    ///
    /// Flattening only removes one level of nesting at a time:
    ///
    /// ```
    /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
    /// assert_eq!(Some(Some(6)), x.flatten());
    /// assert_eq!(Some(6), x.flatten().flatten());
    /// ```
    #[inline]
    #[stable(feature = "option_flattening", since = "1.40.0")]
    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
    #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
    pub const fn flatten(self) -> Option<T> {
        // FIXME(const-hack): could be written with `and_then`
        match self {
            Some(inner) => inner,
            None => None,
        }
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<T, const N: usize> [Option<T>; N] {
    /// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(option_array_transpose)]
    /// # use std::option::Option;
    ///
    /// let data = [Some(0); 1000];
    /// let data: Option<[u8; 1000]> = data.transpose();
    /// assert_eq!(data, Some([0; 1000]));
    ///
    /// let data = [Some(0), None];
    /// let data: Option<[u8; 2]> = data.transpose();
    /// assert_eq!(data, None);
    /// ```
    #[inline]
    #[unstable(feature = "option_array_transpose", issue = "130828")]
    pub fn transpose(self) -> Option<[T; N]> {
        self.try_map(core::convert::identity)
    }
}