core/option.rs
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 [`Option<T>`]
122//! has the same size, alignment, and [function call ABI] as `T`. It is
123//! therefore sound, when `T` is one of these types, to transmute a value `t` of
124//! type `T` to type `Option<T>` (producing the value `Some(t)`) and to
125//! transmute a value `Some(t)` of type `Option<T>` to type `T` (producing the
126//! value `t`).
127//!
128//! In some of these cases, Rust further guarantees the following:
129//! - `transmute::<_, Option<T>>([0u8; size_of::<T>()])` is sound and produces
130//! `Option::<T>::None`
131//! - `transmute::<_, [u8; size_of::<T>()]>(Option::<T>::None)` is sound and produces
132//! `[0u8; size_of::<T>()]`
133//!
134//! These cases are identified by the second column:
135//!
136//! | `T` | Transmuting between `[0u8; size_of::<T>()]` and `Option::<T>::None` sound? |
137//! |---------------------------------------------------------------------|----------------------------------------------------------------------------|
138//! | [`Box<U>`] (specifically, only `Box<U, Global>`) | when `U: Sized` |
139//! | `&U` | when `U: Sized` |
140//! | `&mut U` | when `U: Sized` |
141//! | `fn`, `extern "C" fn`[^extern_fn] | always |
142//! | [`num::NonZero*`] | always |
143//! | [`ptr::NonNull<U>`] | when `U: Sized` |
144//! | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type |
145//!
146//! [^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`)
147//!
148//! Under some conditions the above types `T` are also null pointer optimized when wrapped in a [`Result`][result_repr].
149//!
150//! [`Box<U>`]: ../../std/boxed/struct.Box.html
151//! [`num::NonZero*`]: crate::num
152//! [`ptr::NonNull<U>`]: crate::ptr::NonNull
153//! [function call ABI]: ../primitive.fn.html#abi-compatibility
154//! [result_repr]: crate::result#representation
155//!
156//! This is called the "null pointer optimization" or NPO.
157//!
158//! It is further guaranteed that, for the cases above, one can
159//! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
160//! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
161//! is undefined behavior).
162//!
163//! # Method overview
164//!
165//! In addition to working with pattern matching, [`Option`] provides a wide
166//! variety of different methods.
167//!
168//! ## Querying the variant
169//!
170//! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
171//! is [`Some`] or [`None`], respectively.
172//!
173//! The [`is_some_and`] and [`is_none_or`] methods apply the provided function
174//! to the contents of the [`Option`] to produce a boolean value.
175//! If this is [`None`] then a default result is returned instead without executing the function.
176//!
177//! [`is_none`]: Option::is_none
178//! [`is_some`]: Option::is_some
179//! [`is_some_and`]: Option::is_some_and
180//! [`is_none_or`]: Option::is_none_or
181//!
182//! ## Adapters for working with references
183//!
184//! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
185//! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
186//! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
187//! <code>[Option]<[&]T::[Target]></code>
188//! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
189//! <code>[Option]<[&mut] T::[Target]></code>
190//! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
191//! <code>[Option]<[Pin]<[&]T>></code>
192//! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
193//! <code>[Option]<[Pin]<[&mut] T>></code>
194//! * [`as_slice`] returns a one-element slice of the contained value, if any.
195//! If this is [`None`], an empty slice is returned.
196//! * [`as_mut_slice`] returns a mutable one-element slice of the contained value, if any.
197//! If this is [`None`], an empty slice is returned.
198//!
199//! [&]: reference "shared reference"
200//! [&mut]: reference "mutable reference"
201//! [Target]: Deref::Target "ops::Deref::Target"
202//! [`as_deref`]: Option::as_deref
203//! [`as_deref_mut`]: Option::as_deref_mut
204//! [`as_mut`]: Option::as_mut
205//! [`as_pin_mut`]: Option::as_pin_mut
206//! [`as_pin_ref`]: Option::as_pin_ref
207//! [`as_ref`]: Option::as_ref
208//! [`as_slice`]: Option::as_slice
209//! [`as_mut_slice`]: Option::as_mut_slice
210//!
211//! ## Extracting the contained value
212//!
213//! These methods extract the contained value in an [`Option<T>`] when it
214//! is the [`Some`] variant. If the [`Option`] is [`None`]:
215//!
216//! * [`expect`] panics with a provided custom message
217//! * [`unwrap`] panics with a generic message
218//! * [`unwrap_or`] returns the provided default value
219//! * [`unwrap_or_default`] returns the default value of the type `T`
220//! (which must implement the [`Default`] trait)
221//! * [`unwrap_or_else`] returns the result of evaluating the provided
222//! function
223//! * [`unwrap_unchecked`] produces *[undefined behavior]*
224//!
225//! [`expect`]: Option::expect
226//! [`unwrap`]: Option::unwrap
227//! [`unwrap_or`]: Option::unwrap_or
228//! [`unwrap_or_default`]: Option::unwrap_or_default
229//! [`unwrap_or_else`]: Option::unwrap_or_else
230//! [`unwrap_unchecked`]: Option::unwrap_unchecked
231//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
232//!
233//! ## Transforming contained values
234//!
235//! These methods transform [`Option`] to [`Result`]:
236//!
237//! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
238//! [`Err(err)`] using the provided default `err` value
239//! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
240//! a value of [`Err`] using the provided function
241//! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
242//! [`Result`] of an [`Option`]
243//!
244//! [`Err(err)`]: Err
245//! [`Ok(v)`]: Ok
246//! [`Some(v)`]: Some
247//! [`ok_or`]: Option::ok_or
248//! [`ok_or_else`]: Option::ok_or_else
249//! [`transpose`]: Option::transpose
250//!
251//! These methods transform the [`Some`] variant:
252//!
253//! * [`filter`] calls the provided predicate function on the contained
254//! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
255//! if the function returns `true`; otherwise, returns [`None`]
256//! * [`flatten`] removes one level of nesting from an [`Option<Option<T>>`]
257//! * [`inspect`] method takes ownership of the [`Option`] and applies
258//! the provided function to the contained value by reference if [`Some`]
259//! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
260//! provided function to the contained value of [`Some`] and leaving
261//! [`None`] values unchanged
262//!
263//! [`Some(t)`]: Some
264//! [`filter`]: Option::filter
265//! [`flatten`]: Option::flatten
266//! [`inspect`]: Option::inspect
267//! [`map`]: Option::map
268//!
269//! These methods transform [`Option<T>`] to a value of a possibly
270//! different type `U`:
271//!
272//! * [`map_or`] applies the provided function to the contained value of
273//! [`Some`], or returns the provided default value if the [`Option`] is
274//! [`None`]
275//! * [`map_or_else`] applies the provided function to the contained value
276//! of [`Some`], or returns the result of evaluating the provided
277//! fallback function if the [`Option`] is [`None`]
278//!
279//! [`map_or`]: Option::map_or
280//! [`map_or_else`]: Option::map_or_else
281//!
282//! These methods combine the [`Some`] variants of two [`Option`] values:
283//!
284//! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
285//! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
286//! * [`zip_with`] calls the provided function `f` and returns
287//! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
288//! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
289//!
290//! [`Some(f(s, o))`]: Some
291//! [`Some(o)`]: Some
292//! [`Some(s)`]: Some
293//! [`Some((s, o))`]: Some
294//! [`zip`]: Option::zip
295//! [`zip_with`]: Option::zip_with
296//!
297//! ## Boolean operators
298//!
299//! These methods treat the [`Option`] as a boolean value, where [`Some`]
300//! acts like [`true`] and [`None`] acts like [`false`]. There are two
301//! categories of these methods: ones that take an [`Option`] as input, and
302//! ones that take a function as input (to be lazily evaluated).
303//!
304//! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
305//! input, and produce an [`Option`] as output. Only the [`and`] method can
306//! produce an [`Option<U>`] value having a different inner type `U` than
307//! [`Option<T>`].
308//!
309//! | method | self | input | output |
310//! |---------|-----------|-----------|-----------|
311//! | [`and`] | `None` | (ignored) | `None` |
312//! | [`and`] | `Some(x)` | `None` | `None` |
313//! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
314//! | [`or`] | `None` | `None` | `None` |
315//! | [`or`] | `None` | `Some(y)` | `Some(y)` |
316//! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
317//! | [`xor`] | `None` | `None` | `None` |
318//! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
319//! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
320//! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
321//!
322//! [`and`]: Option::and
323//! [`or`]: Option::or
324//! [`xor`]: Option::xor
325//!
326//! The [`and_then`] and [`or_else`] methods take a function as input, and
327//! only evaluate the function when they need to produce a new value. Only
328//! the [`and_then`] method can produce an [`Option<U>`] value having a
329//! different inner type `U` than [`Option<T>`].
330//!
331//! | method | self | function input | function result | output |
332//! |--------------|-----------|----------------|-----------------|-----------|
333//! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
334//! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
335//! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
336//! | [`or_else`] | `None` | (not provided) | `None` | `None` |
337//! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
338//! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
339//!
340//! [`and_then`]: Option::and_then
341//! [`or_else`]: Option::or_else
342//!
343//! This is an example of using methods like [`and_then`] and [`or`] in a
344//! pipeline of method calls. Early stages of the pipeline pass failure
345//! values ([`None`]) through unchanged, and continue processing on
346//! success values ([`Some`]). Toward the end, [`or`] substitutes an error
347//! message if it receives [`None`].
348//!
349//! ```
350//! # use std::collections::BTreeMap;
351//! let mut bt = BTreeMap::new();
352//! bt.insert(20u8, "foo");
353//! bt.insert(42u8, "bar");
354//! let res = [0u8, 1, 11, 200, 22]
355//! .into_iter()
356//! .map(|x| {
357//! // `checked_sub()` returns `None` on error
358//! x.checked_sub(1)
359//! // same with `checked_mul()`
360//! .and_then(|x| x.checked_mul(2))
361//! // `BTreeMap::get` returns `None` on error
362//! .and_then(|x| bt.get(&x))
363//! // Substitute an error message if we have `None` so far
364//! .or(Some(&"error!"))
365//! .copied()
366//! // Won't panic because we unconditionally used `Some` above
367//! .unwrap()
368//! })
369//! .collect::<Vec<_>>();
370//! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
371//! ```
372//!
373//! ## Comparison operators
374//!
375//! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
376//! [`PartialOrd`] implementation. With this order, [`None`] compares as
377//! less than any [`Some`], and two [`Some`] compare the same way as their
378//! contained values would in `T`. If `T` also implements
379//! [`Ord`], then so does [`Option<T>`].
380//!
381//! ```
382//! assert!(None < Some(0));
383//! assert!(Some(0) < Some(1));
384//! ```
385//!
386//! ## Iterating over `Option`
387//!
388//! An [`Option`] can be iterated over. This can be helpful if you need an
389//! iterator that is conditionally empty. The iterator will either produce
390//! a single value (when the [`Option`] is [`Some`]), or produce no values
391//! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
392//! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
393//! the [`Option`] is [`None`].
394//!
395//! [`Some(v)`]: Some
396//! [`empty()`]: crate::iter::empty
397//! [`once(v)`]: crate::iter::once
398//!
399//! Iterators over [`Option<T>`] come in three types:
400//!
401//! * [`into_iter`] consumes the [`Option`] and produces the contained
402//! value
403//! * [`iter`] produces an immutable reference of type `&T` to the
404//! contained value
405//! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
406//! contained value
407//!
408//! [`into_iter`]: Option::into_iter
409//! [`iter`]: Option::iter
410//! [`iter_mut`]: Option::iter_mut
411//!
412//! An iterator over [`Option`] can be useful when chaining iterators, for
413//! example, to conditionally insert items. (It's not always necessary to
414//! explicitly call an iterator constructor: many [`Iterator`] methods that
415//! accept other iterators will also accept iterable types that implement
416//! [`IntoIterator`], which includes [`Option`].)
417//!
418//! ```
419//! let yep = Some(42);
420//! let nope = None;
421//! // chain() already calls into_iter(), so we don't have to do so
422//! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
423//! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
424//! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
425//! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
426//! ```
427//!
428//! One reason to chain iterators in this way is that a function returning
429//! `impl Iterator` must have all possible return values be of the same
430//! concrete type. Chaining an iterated [`Option`] can help with that.
431//!
432//! ```
433//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
434//! // Explicit returns to illustrate return types matching
435//! match do_insert {
436//! true => return (0..4).chain(Some(42)).chain(4..8),
437//! false => return (0..4).chain(None).chain(4..8),
438//! }
439//! }
440//! println!("{:?}", make_iter(true).collect::<Vec<_>>());
441//! println!("{:?}", make_iter(false).collect::<Vec<_>>());
442//! ```
443//!
444//! If we try to do the same thing, but using [`once()`] and [`empty()`],
445//! we can't return `impl Iterator` anymore because the concrete types of
446//! the return values differ.
447//!
448//! [`empty()`]: crate::iter::empty
449//! [`once()`]: crate::iter::once
450//!
451//! ```compile_fail,E0308
452//! # use std::iter::{empty, once};
453//! // This won't compile because all possible returns from the function
454//! // must have the same concrete type.
455//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
456//! // Explicit returns to illustrate return types not matching
457//! match do_insert {
458//! true => return (0..4).chain(once(42)).chain(4..8),
459//! false => return (0..4).chain(empty()).chain(4..8),
460//! }
461//! }
462//! ```
463//!
464//! ## Collecting into `Option`
465//!
466//! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
467//! which allows an iterator over [`Option`] values to be collected into an
468//! [`Option`] of a collection of each contained value of the original
469//! [`Option`] values, or [`None`] if any of the elements was [`None`].
470//!
471//! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E
472//!
473//! ```
474//! let v = [Some(2), Some(4), None, Some(8)];
475//! let res: Option<Vec<_>> = v.into_iter().collect();
476//! assert_eq!(res, None);
477//! let v = [Some(2), Some(4), Some(8)];
478//! let res: Option<Vec<_>> = v.into_iter().collect();
479//! assert_eq!(res, Some(vec![2, 4, 8]));
480//! ```
481//!
482//! [`Option`] also implements the [`Product`][impl-Product] and
483//! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
484//! to provide the [`product`][Iterator::product] and
485//! [`sum`][Iterator::sum] methods.
486//!
487//! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E
488//! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E
489//!
490//! ```
491//! let v = [None, Some(1), Some(2), Some(3)];
492//! let res: Option<i32> = v.into_iter().sum();
493//! assert_eq!(res, None);
494//! let v = [Some(1), Some(2), Some(21)];
495//! let res: Option<i32> = v.into_iter().product();
496//! assert_eq!(res, Some(42));
497//! ```
498//!
499//! ## Modifying an [`Option`] in-place
500//!
501//! These methods return a mutable reference to the contained value of an
502//! [`Option<T>`]:
503//!
504//! * [`insert`] inserts a value, dropping any old contents
505//! * [`get_or_insert`] gets the current value, inserting a provided
506//! default value if it is [`None`]
507//! * [`get_or_insert_default`] gets the current value, inserting the
508//! default value of type `T` (which must implement [`Default`]) if it is
509//! [`None`]
510//! * [`get_or_insert_with`] gets the current value, inserting a default
511//! computed by the provided function if it is [`None`]
512//!
513//! [`get_or_insert`]: Option::get_or_insert
514//! [`get_or_insert_default`]: Option::get_or_insert_default
515//! [`get_or_insert_with`]: Option::get_or_insert_with
516//! [`insert`]: Option::insert
517//!
518//! These methods transfer ownership of the contained value of an
519//! [`Option`]:
520//!
521//! * [`take`] takes ownership of the contained value of an [`Option`], if
522//! any, replacing the [`Option`] with [`None`]
523//! * [`replace`] takes ownership of the contained value of an [`Option`],
524//! if any, replacing the [`Option`] with a [`Some`] containing the
525//! provided value
526//!
527//! [`replace`]: Option::replace
528//! [`take`]: Option::take
529//!
530//! # Examples
531//!
532//! Basic pattern matching on [`Option`]:
533//!
534//! ```
535//! let msg = Some("howdy");
536//!
537//! // Take a reference to the contained string
538//! if let Some(m) = &msg {
539//! println!("{}", *m);
540//! }
541//!
542//! // Remove the contained string, destroying the Option
543//! let unwrapped_msg = msg.unwrap_or("default message");
544//! ```
545//!
546//! Initialize a result to [`None`] before a loop:
547//!
548//! ```
549//! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
550//!
551//! // A list of data to search through.
552//! let all_the_big_things = [
553//! Kingdom::Plant(250, "redwood"),
554//! Kingdom::Plant(230, "noble fir"),
555//! Kingdom::Plant(229, "sugar pine"),
556//! Kingdom::Animal(25, "blue whale"),
557//! Kingdom::Animal(19, "fin whale"),
558//! Kingdom::Animal(15, "north pacific right whale"),
559//! ];
560//!
561//! // We're going to search for the name of the biggest animal,
562//! // but to start with we've just got `None`.
563//! let mut name_of_biggest_animal = None;
564//! let mut size_of_biggest_animal = 0;
565//! for big_thing in &all_the_big_things {
566//! match *big_thing {
567//! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
568//! // Now we've found the name of some big animal
569//! size_of_biggest_animal = size;
570//! name_of_biggest_animal = Some(name);
571//! }
572//! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
573//! }
574//! }
575//!
576//! match name_of_biggest_animal {
577//! Some(name) => println!("the biggest animal is {name}"),
578//! None => println!("there are no animals :("),
579//! }
580//! ```
581
582#![stable(feature = "rust1", since = "1.0.0")]
583
584/// Ferrocene addition: Hidden module to test crate-internal functionality
585#[doc(hidden)]
586#[unstable(feature = "ferrocene_test", issue = "none")]
587pub mod ferrocene_test;
588
589use crate::clone::TrivialClone;
590use crate::iter::{self, FusedIterator, TrustedLen};
591use crate::marker::Destruct;
592use crate::ops::{self, ControlFlow, Deref, DerefMut, Residual, Try};
593use crate::panicking::{panic, panic_display};
594use crate::pin::Pin;
595use crate::{cmp, convert, hint, mem, slice};
596
597/// The `Option` type. See [the module level documentation](self) for more.
598#[doc(search_unbox)]
599#[derive(Copy, Debug, Hash)]
600#[derive_const(Eq)]
601#[rustc_diagnostic_item = "Option"]
602#[lang = "Option"]
603#[stable(feature = "rust1", since = "1.0.0")]
604#[allow(clippy::derived_hash_with_manual_eq)] // PartialEq is manually implemented equivalently
605#[ferrocene::prevalidated]
606pub enum Option<T> {
607 /// No value.
608 #[lang = "None"]
609 #[stable(feature = "rust1", since = "1.0.0")]
610 None,
611 /// Some value of type `T`.
612 #[lang = "Some"]
613 #[stable(feature = "rust1", since = "1.0.0")]
614 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
615}
616
617/////////////////////////////////////////////////////////////////////////////
618// Type implementation
619/////////////////////////////////////////////////////////////////////////////
620
621impl<T> Option<T> {
622 /////////////////////////////////////////////////////////////////////////
623 // Querying the contained values
624 /////////////////////////////////////////////////////////////////////////
625
626 /// Returns `true` if the option is a [`Some`] value.
627 ///
628 /// # Examples
629 ///
630 /// ```
631 /// let x: Option<u32> = Some(2);
632 /// assert_eq!(x.is_some(), true);
633 ///
634 /// let x: Option<u32> = None;
635 /// assert_eq!(x.is_some(), false);
636 /// ```
637 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
638 #[inline]
639 #[stable(feature = "rust1", since = "1.0.0")]
640 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
641 #[ferrocene::prevalidated]
642 pub const fn is_some(&self) -> bool {
643 matches!(*self, Some(_))
644 }
645
646 /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// let x: Option<u32> = Some(2);
652 /// assert_eq!(x.is_some_and(|x| x > 1), true);
653 ///
654 /// let x: Option<u32> = Some(0);
655 /// assert_eq!(x.is_some_and(|x| x > 1), false);
656 ///
657 /// let x: Option<u32> = None;
658 /// assert_eq!(x.is_some_and(|x| x > 1), false);
659 ///
660 /// let x: Option<String> = Some("ownership".to_string());
661 /// assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true);
662 /// println!("still alive {:?}", x);
663 /// ```
664 #[must_use]
665 #[inline]
666 #[stable(feature = "is_some_and", since = "1.70.0")]
667 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
668 #[ferrocene::prevalidated]
669 pub const fn is_some_and(self, f: impl [const] FnOnce(T) -> bool + [const] Destruct) -> bool {
670 match self {
671 None => false,
672 Some(x) => f(x),
673 }
674 }
675
676 /// Returns `true` if the option is a [`None`] value.
677 ///
678 /// # Examples
679 ///
680 /// ```
681 /// let x: Option<u32> = Some(2);
682 /// assert_eq!(x.is_none(), false);
683 ///
684 /// let x: Option<u32> = None;
685 /// assert_eq!(x.is_none(), true);
686 /// ```
687 #[must_use = "if you intended to assert that this doesn't have a value, consider \
688 wrapping this in an `assert!()` instead"]
689 #[inline]
690 #[stable(feature = "rust1", since = "1.0.0")]
691 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
692 #[ferrocene::prevalidated]
693 pub const fn is_none(&self) -> bool {
694 !self.is_some()
695 }
696
697 /// Returns `true` if the option is a [`None`] or the value inside of it matches a predicate.
698 ///
699 /// # Examples
700 ///
701 /// ```
702 /// let x: Option<u32> = Some(2);
703 /// assert_eq!(x.is_none_or(|x| x > 1), true);
704 ///
705 /// let x: Option<u32> = Some(0);
706 /// assert_eq!(x.is_none_or(|x| x > 1), false);
707 ///
708 /// let x: Option<u32> = None;
709 /// assert_eq!(x.is_none_or(|x| x > 1), true);
710 ///
711 /// let x: Option<String> = Some("ownership".to_string());
712 /// assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true);
713 /// println!("still alive {:?}", x);
714 /// ```
715 #[must_use]
716 #[inline]
717 #[stable(feature = "is_none_or", since = "1.82.0")]
718 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
719 #[ferrocene::prevalidated]
720 pub const fn is_none_or(self, f: impl [const] FnOnce(T) -> bool + [const] Destruct) -> bool {
721 match self {
722 None => true,
723 Some(x) => f(x),
724 }
725 }
726
727 /////////////////////////////////////////////////////////////////////////
728 // Adapter for working with references
729 /////////////////////////////////////////////////////////////////////////
730
731 /// Converts from `&Option<T>` to `Option<&T>`.
732 ///
733 /// # Examples
734 ///
735 /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code>
736 /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
737 /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a
738 /// reference to the value inside the original.
739 ///
740 /// [`map`]: Option::map
741 /// [String]: ../../std/string/struct.String.html "String"
742 /// [`String`]: ../../std/string/struct.String.html "String"
743 ///
744 /// ```
745 /// let text: Option<String> = Some("Hello, world!".to_string());
746 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
747 /// // then consume *that* with `map`, leaving `text` on the stack.
748 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
749 /// println!("still can print text: {text:?}");
750 /// ```
751 #[inline]
752 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
753 #[stable(feature = "rust1", since = "1.0.0")]
754 #[ferrocene::prevalidated]
755 pub const fn as_ref(&self) -> Option<&T> {
756 match *self {
757 Some(ref x) => Some(x),
758 None => None,
759 }
760 }
761
762 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// let mut x = Some(2);
768 /// match x.as_mut() {
769 /// Some(v) => *v = 42,
770 /// None => {},
771 /// }
772 /// assert_eq!(x, Some(42));
773 /// ```
774 #[inline]
775 #[stable(feature = "rust1", since = "1.0.0")]
776 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
777 #[ferrocene::prevalidated]
778 pub const fn as_mut(&mut self) -> Option<&mut T> {
779 match *self {
780 Some(ref mut x) => Some(x),
781 None => None,
782 }
783 }
784
785 /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
786 ///
787 /// [&]: reference "shared reference"
788 #[inline]
789 #[must_use]
790 #[stable(feature = "pin", since = "1.33.0")]
791 #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
792 pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
793 // FIXME(const-hack): use `map` once that is possible
794 match Pin::get_ref(self).as_ref() {
795 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
796 // which is pinned.
797 Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
798 None => None,
799 }
800 }
801
802 /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
803 ///
804 /// [&mut]: reference "mutable reference"
805 #[inline]
806 #[must_use]
807 #[stable(feature = "pin", since = "1.33.0")]
808 #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
809 pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
810 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
811 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
812 unsafe {
813 // FIXME(const-hack): use `map` once that is possible
814 match Pin::get_unchecked_mut(self).as_mut() {
815 Some(x) => Some(Pin::new_unchecked(x)),
816 None => None,
817 }
818 }
819 }
820
821 #[inline]
822 #[ferrocene::prevalidated]
823 const fn len(&self) -> usize {
824 // Using the intrinsic avoids emitting a branch to get the 0 or 1.
825 let discriminant: isize = crate::intrinsics::discriminant_value(self);
826 discriminant as usize
827 }
828
829 /// Returns a slice of the contained value, if any. If this is `None`, an
830 /// empty slice is returned. This can be useful to have a single type of
831 /// iterator over an `Option` or slice.
832 ///
833 /// Note: Should you have an `Option<&T>` and wish to get a slice of `T`,
834 /// you can unpack it via `opt.map_or(&[], std::slice::from_ref)`.
835 ///
836 /// # Examples
837 ///
838 /// ```rust
839 /// assert_eq!(
840 /// [Some(1234).as_slice(), None.as_slice()],
841 /// [&[1234][..], &[][..]],
842 /// );
843 /// ```
844 ///
845 /// The inverse of this function is (discounting
846 /// borrowing) [`[_]::first`](slice::first):
847 ///
848 /// ```rust
849 /// for i in [Some(1234_u16), None] {
850 /// assert_eq!(i.as_ref(), i.as_slice().first());
851 /// }
852 /// ```
853 #[inline]
854 #[must_use]
855 #[stable(feature = "option_as_slice", since = "1.75.0")]
856 #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
857 pub const fn as_slice(&self) -> &[T] {
858 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
859 // to the payload, with a length of 1, so this is equivalent to
860 // `slice::from_ref`, and thus is safe.
861 // When the `Option` is `None`, the length used is 0, so to be safe it
862 // just needs to be aligned, which it is because `&self` is aligned and
863 // the offset used is a multiple of alignment.
864 //
865 // Here we assume that `offset_of!` always returns an offset to an
866 // in-bounds and correctly aligned position for a `T` (even if in the
867 // `None` case it's just padding).
868 unsafe {
869 slice::from_raw_parts(
870 (self as *const Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
871 self.len(),
872 )
873 }
874 }
875
876 /// Returns a mutable slice of the contained value, if any. If this is
877 /// `None`, an empty slice is returned. This can be useful to have a
878 /// single type of iterator over an `Option` or slice.
879 ///
880 /// Note: Should you have an `Option<&mut T>` instead of a
881 /// `&mut Option<T>`, which this method takes, you can obtain a mutable
882 /// slice via `opt.map_or(&mut [], std::slice::from_mut)`.
883 ///
884 /// # Examples
885 ///
886 /// ```rust
887 /// assert_eq!(
888 /// [Some(1234).as_mut_slice(), None.as_mut_slice()],
889 /// [&mut [1234][..], &mut [][..]],
890 /// );
891 /// ```
892 ///
893 /// The result is a mutable slice of zero or one items that points into
894 /// our original `Option`:
895 ///
896 /// ```rust
897 /// let mut x = Some(1234);
898 /// x.as_mut_slice()[0] += 1;
899 /// assert_eq!(x, Some(1235));
900 /// ```
901 ///
902 /// The inverse of this method (discounting borrowing)
903 /// is [`[_]::first_mut`](slice::first_mut):
904 ///
905 /// ```rust
906 /// assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
907 /// ```
908 #[inline]
909 #[must_use]
910 #[stable(feature = "option_as_slice", since = "1.75.0")]
911 #[rustc_const_stable(feature = "const_option_ext", since = "1.84.0")]
912 pub const fn as_mut_slice(&mut self) -> &mut [T] {
913 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
914 // to the payload, with a length of 1, so this is equivalent to
915 // `slice::from_mut`, and thus is safe.
916 // When the `Option` is `None`, the length used is 0, so to be safe it
917 // just needs to be aligned, which it is because `&self` is aligned and
918 // the offset used is a multiple of alignment.
919 //
920 // In the new version, the intrinsic creates a `*const T` from a
921 // mutable reference so it is safe to cast back to a mutable pointer
922 // here. As with `as_slice`, the intrinsic always returns a pointer to
923 // an in-bounds and correctly aligned position for a `T` (even if in
924 // the `None` case it's just padding).
925 unsafe {
926 slice::from_raw_parts_mut(
927 (self as *mut Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
928 self.len(),
929 )
930 }
931 }
932
933 /////////////////////////////////////////////////////////////////////////
934 // Getting to contained values
935 /////////////////////////////////////////////////////////////////////////
936
937 /// Returns the contained [`Some`] value, consuming the `self` value.
938 ///
939 /// # Panics
940 ///
941 /// Panics if the value is a [`None`] with a custom panic message provided by
942 /// `msg`.
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// let x = Some("value");
948 /// assert_eq!(x.expect("fruits are healthy"), "value");
949 /// ```
950 ///
951 /// ```should_panic
952 /// let x: Option<&str> = None;
953 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
954 /// ```
955 ///
956 /// # Recommended Message Style
957 ///
958 /// We recommend that `expect` messages are used to describe the reason you
959 /// _expect_ the `Option` should be `Some`.
960 ///
961 /// ```should_panic
962 /// # let slice: &[u8] = &[];
963 /// let item = slice.get(0)
964 /// .expect("slice should not be empty");
965 /// ```
966 ///
967 /// **Hint**: If you're having trouble remembering how to phrase expect
968 /// error messages remember to focus on the word "should" as in "env
969 /// variable should be set by blah" or "the given binary should be available
970 /// and executable by the current user".
971 ///
972 /// For more detail on expect message styles and the reasoning behind our
973 /// recommendation please refer to the section on ["Common Message
974 /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
975 #[inline]
976 #[track_caller]
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[rustc_diagnostic_item = "option_expect"]
979 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
980 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
981 #[ferrocene::prevalidated]
982 pub const fn expect(self, msg: &str) -> T {
983 match self {
984 Some(val) => val,
985 None => expect_failed(msg),
986 }
987 }
988
989 /// Returns the contained [`Some`] value, consuming the `self` value.
990 ///
991 /// Because this function may panic, its use is generally discouraged.
992 /// Panics are meant for unrecoverable errors, and
993 /// [may abort the entire program][panic-abort].
994 ///
995 /// Instead, prefer to use pattern matching and handle the [`None`]
996 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
997 /// [`unwrap_or_default`]. In functions returning `Option`, you can use
998 /// [the `?` (try) operator][try-option].
999 ///
1000 /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
1001 /// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used
1002 /// [`unwrap_or`]: Option::unwrap_or
1003 /// [`unwrap_or_else`]: Option::unwrap_or_else
1004 /// [`unwrap_or_default`]: Option::unwrap_or_default
1005 ///
1006 /// # Panics
1007 ///
1008 /// Panics if the self value equals [`None`].
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// let x = Some("air");
1014 /// assert_eq!(x.unwrap(), "air");
1015 /// ```
1016 ///
1017 /// ```should_panic
1018 /// let x: Option<&str> = None;
1019 /// assert_eq!(x.unwrap(), "air"); // fails
1020 /// ```
1021 #[inline(always)]
1022 #[track_caller]
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 #[rustc_diagnostic_item = "option_unwrap"]
1025 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1026 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
1027 #[ferrocene::prevalidated]
1028 pub const fn unwrap(self) -> T {
1029 match self {
1030 Some(val) => val,
1031 None => unwrap_failed(),
1032 }
1033 }
1034
1035 /// Returns the contained [`Some`] value or a provided default.
1036 ///
1037 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1038 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1039 /// which is lazily evaluated.
1040 ///
1041 /// [`unwrap_or_else`]: Option::unwrap_or_else
1042 ///
1043 /// # Examples
1044 ///
1045 /// ```
1046 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
1047 /// assert_eq!(None.unwrap_or("bike"), "bike");
1048 /// ```
1049 #[inline]
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1052 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1053 #[ferrocene::prevalidated]
1054 pub const fn unwrap_or(self, default: T) -> T
1055 where
1056 T: [const] Destruct,
1057 {
1058 match self {
1059 Some(x) => x,
1060 None => default,
1061 }
1062 }
1063
1064 /// Returns the contained [`Some`] value or computes it from a closure.
1065 ///
1066 /// # Examples
1067 ///
1068 /// ```
1069 /// let k = 10;
1070 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
1071 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
1072 /// ```
1073 #[inline]
1074 #[track_caller]
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1077 #[ferrocene::prevalidated]
1078 pub const fn unwrap_or_else<F>(self, f: F) -> T
1079 where
1080 F: [const] FnOnce() -> T + [const] Destruct,
1081 {
1082 match self {
1083 Some(x) => x,
1084 None => f(),
1085 }
1086 }
1087
1088 /// Returns the contained [`Some`] value or a default.
1089 ///
1090 /// Consumes the `self` argument then, if [`Some`], returns the contained
1091 /// value, otherwise if [`None`], returns the [default value] for that
1092 /// type.
1093 ///
1094 /// # Examples
1095 ///
1096 /// ```
1097 /// let x: Option<u32> = None;
1098 /// let y: Option<u32> = Some(12);
1099 ///
1100 /// assert_eq!(x.unwrap_or_default(), 0);
1101 /// assert_eq!(y.unwrap_or_default(), 12);
1102 /// ```
1103 ///
1104 /// [default value]: Default::default
1105 /// [`parse`]: str::parse
1106 /// [`FromStr`]: crate::str::FromStr
1107 #[inline]
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1110 #[ferrocene::prevalidated]
1111 pub const fn unwrap_or_default(self) -> T
1112 where
1113 T: [const] Default,
1114 {
1115 match self {
1116 Some(x) => x,
1117 None => T::default(),
1118 }
1119 }
1120
1121 /// Returns the contained [`Some`] value, consuming the `self` value,
1122 /// without checking that the value is not [`None`].
1123 ///
1124 /// # Safety
1125 ///
1126 /// Calling this method on [`None`] is *[undefined behavior]*.
1127 ///
1128 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1129 ///
1130 /// # Examples
1131 ///
1132 /// ```
1133 /// let x = Some("air");
1134 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
1135 /// ```
1136 ///
1137 /// ```no_run
1138 /// let x: Option<&str> = None;
1139 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
1140 /// ```
1141 #[inline]
1142 #[track_caller]
1143 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1144 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1145 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
1146 #[ferrocene::prevalidated]
1147 pub const unsafe fn unwrap_unchecked(self) -> T {
1148 match self {
1149 Some(val) => val,
1150 #[ferrocene::annotation(
1151 "This line cannot be covered as reaching `unreachable_unchecked` is undefined behavior."
1152 )]
1153 // SAFETY: the safety contract must be upheld by the caller.
1154 None => unsafe { hint::unreachable_unchecked() },
1155 }
1156 }
1157
1158 /////////////////////////////////////////////////////////////////////////
1159 // Transforming contained values
1160 /////////////////////////////////////////////////////////////////////////
1161
1162 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`).
1163 ///
1164 /// # Examples
1165 ///
1166 /// Calculates the length of an <code>Option<[String]></code> as an
1167 /// <code>Option<[usize]></code>, consuming the original:
1168 ///
1169 /// [String]: ../../std/string/struct.String.html "String"
1170 /// ```
1171 /// let maybe_some_string = Some(String::from("Hello, World!"));
1172 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
1173 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
1174 /// assert_eq!(maybe_some_len, Some(13));
1175 ///
1176 /// let x: Option<&str> = None;
1177 /// assert_eq!(x.map(|s| s.len()), None);
1178 /// ```
1179 #[inline]
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1182 #[ferrocene::prevalidated]
1183 pub const fn map<U, F>(self, f: F) -> Option<U>
1184 where
1185 F: [const] FnOnce(T) -> U + [const] Destruct,
1186 {
1187 match self {
1188 Some(x) => Some(f(x)),
1189 None => None,
1190 }
1191 }
1192
1193 /// Calls a function with a reference to the contained value if [`Some`].
1194 ///
1195 /// Returns the original option.
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```
1200 /// let list = vec![1, 2, 3];
1201 ///
1202 /// // prints "got: 2"
1203 /// let x = list
1204 /// .get(1)
1205 /// .inspect(|x| println!("got: {x}"))
1206 /// .expect("list should be long enough");
1207 ///
1208 /// // prints nothing
1209 /// list.get(5).inspect(|x| println!("got: {x}"));
1210 /// ```
1211 #[inline]
1212 #[stable(feature = "result_option_inspect", since = "1.76.0")]
1213 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1214 #[ferrocene::prevalidated]
1215 pub const fn inspect<F>(self, f: F) -> Self
1216 where
1217 F: [const] FnOnce(&T) + [const] Destruct,
1218 {
1219 if let Some(ref x) = self {
1220 f(x);
1221 }
1222
1223 self
1224 }
1225
1226 /// Returns the provided default result (if none),
1227 /// or applies a function to the contained value (if any).
1228 ///
1229 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
1230 /// the result of a function call, it is recommended to use [`map_or_else`],
1231 /// which is lazily evaluated.
1232 ///
1233 /// [`map_or_else`]: Option::map_or_else
1234 ///
1235 /// # Examples
1236 ///
1237 /// ```
1238 /// let x = Some("foo");
1239 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
1240 ///
1241 /// let x: Option<&str> = None;
1242 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
1243 /// ```
1244 #[inline]
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 #[must_use = "if you don't need the returned value, use `if let` instead"]
1247 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1248 #[ferrocene::prevalidated]
1249 pub const fn map_or<U, F>(self, default: U, f: F) -> U
1250 where
1251 F: [const] FnOnce(T) -> U + [const] Destruct,
1252 U: [const] Destruct,
1253 {
1254 match self {
1255 Some(t) => f(t),
1256 None => default,
1257 }
1258 }
1259
1260 /// Computes a default function result (if none), or
1261 /// applies a different function to the contained value (if any).
1262 ///
1263 /// # Basic examples
1264 ///
1265 /// ```
1266 /// let k = 21;
1267 ///
1268 /// let x = Some("foo");
1269 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
1270 ///
1271 /// let x: Option<&str> = None;
1272 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
1273 /// ```
1274 ///
1275 /// # Handling a Result-based fallback
1276 ///
1277 /// A somewhat common occurrence when dealing with optional values
1278 /// in combination with [`Result<T, E>`] is the case where one wants to invoke
1279 /// a fallible fallback if the option is not present. This example
1280 /// parses a command line argument (if present), or the contents of a file to
1281 /// an integer. However, unlike accessing the command line argument, reading
1282 /// the file is fallible, so it must be wrapped with `Ok`.
1283 ///
1284 /// ```no_run
1285 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1286 /// let v: u64 = std::env::args()
1287 /// .nth(1)
1288 /// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
1289 /// .parse()?;
1290 /// # Ok(())
1291 /// # }
1292 /// ```
1293 #[inline]
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1296 #[ferrocene::prevalidated]
1297 pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
1298 where
1299 D: [const] FnOnce() -> U + [const] Destruct,
1300 F: [const] FnOnce(T) -> U + [const] Destruct,
1301 {
1302 match self {
1303 Some(t) => f(t),
1304 None => default(),
1305 }
1306 }
1307
1308 /// Maps an `Option<T>` to a `U` by applying function `f` to the contained
1309 /// value if the option is [`Some`], otherwise if [`None`], returns the
1310 /// [default value] for the type `U`.
1311 ///
1312 /// # Examples
1313 ///
1314 /// ```
1315 /// #![feature(result_option_map_or_default)]
1316 ///
1317 /// let x: Option<&str> = Some("hi");
1318 /// let y: Option<&str> = None;
1319 ///
1320 /// assert_eq!(x.map_or_default(|x| x.len()), 2);
1321 /// assert_eq!(y.map_or_default(|y| y.len()), 0);
1322 /// ```
1323 ///
1324 /// [default value]: Default::default
1325 #[inline]
1326 #[unstable(feature = "result_option_map_or_default", issue = "138099")]
1327 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1328 #[ferrocene::prevalidated]
1329 pub const fn map_or_default<U, F>(self, f: F) -> U
1330 where
1331 U: [const] Default,
1332 F: [const] FnOnce(T) -> U + [const] Destruct,
1333 {
1334 match self {
1335 Some(t) => f(t),
1336 None => U::default(),
1337 }
1338 }
1339
1340 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1341 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
1342 ///
1343 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
1344 /// result of a function call, it is recommended to use [`ok_or_else`], which is
1345 /// lazily evaluated.
1346 ///
1347 /// [`Ok(v)`]: Ok
1348 /// [`Err(err)`]: Err
1349 /// [`Some(v)`]: Some
1350 /// [`ok_or_else`]: Option::ok_or_else
1351 ///
1352 /// # Examples
1353 ///
1354 /// ```
1355 /// let x = Some("foo");
1356 /// assert_eq!(x.ok_or(0), Ok("foo"));
1357 ///
1358 /// let x: Option<&str> = None;
1359 /// assert_eq!(x.ok_or(0), Err(0));
1360 /// ```
1361 #[inline]
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1364 #[ferrocene::prevalidated]
1365 pub const fn ok_or<E: [const] Destruct>(self, err: E) -> Result<T, E> {
1366 match self {
1367 Some(v) => Ok(v),
1368 None => Err(err),
1369 }
1370 }
1371
1372 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1373 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1374 ///
1375 /// [`Ok(v)`]: Ok
1376 /// [`Err(err())`]: Err
1377 /// [`Some(v)`]: Some
1378 ///
1379 /// # Examples
1380 ///
1381 /// ```
1382 /// let x = Some("foo");
1383 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1384 ///
1385 /// let x: Option<&str> = None;
1386 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1387 /// ```
1388 #[inline]
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1391 #[ferrocene::prevalidated]
1392 pub const fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1393 where
1394 F: [const] FnOnce() -> E + [const] Destruct,
1395 {
1396 match self {
1397 Some(v) => Ok(v),
1398 None => Err(err()),
1399 }
1400 }
1401
1402 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1403 ///
1404 /// Leaves the original Option in-place, creating a new one with a reference
1405 /// to the original one, additionally coercing the contents via [`Deref`].
1406 ///
1407 /// # Examples
1408 ///
1409 /// ```
1410 /// let x: Option<String> = Some("hey".to_owned());
1411 /// assert_eq!(x.as_deref(), Some("hey"));
1412 ///
1413 /// let x: Option<String> = None;
1414 /// assert_eq!(x.as_deref(), None);
1415 /// ```
1416 #[inline]
1417 #[stable(feature = "option_deref", since = "1.40.0")]
1418 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1419 #[ferrocene::prevalidated]
1420 pub const fn as_deref(&self) -> Option<&T::Target>
1421 where
1422 T: [const] Deref,
1423 {
1424 self.as_ref().map(Deref::deref)
1425 }
1426
1427 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1428 ///
1429 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1430 /// the inner type's [`Deref::Target`] type.
1431 ///
1432 /// # Examples
1433 ///
1434 /// ```
1435 /// let mut x: Option<String> = Some("hey".to_owned());
1436 /// assert_eq!(x.as_deref_mut().map(|x| {
1437 /// x.make_ascii_uppercase();
1438 /// x
1439 /// }), Some("HEY".to_owned().as_mut_str()));
1440 /// ```
1441 #[inline]
1442 #[stable(feature = "option_deref", since = "1.40.0")]
1443 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1444 #[ferrocene::prevalidated]
1445 pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1446 where
1447 T: [const] DerefMut,
1448 {
1449 self.as_mut().map(DerefMut::deref_mut)
1450 }
1451
1452 /////////////////////////////////////////////////////////////////////////
1453 // Iterator constructors
1454 /////////////////////////////////////////////////////////////////////////
1455
1456 /// Returns an iterator over the possibly contained value.
1457 ///
1458 /// # Examples
1459 ///
1460 /// ```
1461 /// let x = Some(4);
1462 /// assert_eq!(x.iter().next(), Some(&4));
1463 ///
1464 /// let x: Option<u32> = None;
1465 /// assert_eq!(x.iter().next(), None);
1466 /// ```
1467 #[inline]
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 #[ferrocene::prevalidated]
1470 pub fn iter(&self) -> Iter<'_, T> {
1471 Iter { inner: Item { opt: self.as_ref() } }
1472 }
1473
1474 /// Returns a mutable iterator over the possibly contained value.
1475 ///
1476 /// # Examples
1477 ///
1478 /// ```
1479 /// let mut x = Some(4);
1480 /// match x.iter_mut().next() {
1481 /// Some(v) => *v = 42,
1482 /// None => {},
1483 /// }
1484 /// assert_eq!(x, Some(42));
1485 ///
1486 /// let mut x: Option<u32> = None;
1487 /// assert_eq!(x.iter_mut().next(), None);
1488 /// ```
1489 #[inline]
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 #[ferrocene::prevalidated]
1492 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1493 IterMut { inner: Item { opt: self.as_mut() } }
1494 }
1495
1496 /////////////////////////////////////////////////////////////////////////
1497 // Boolean operations on the values, eager and lazy
1498 /////////////////////////////////////////////////////////////////////////
1499
1500 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1501 ///
1502 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1503 /// result of a function call, it is recommended to use [`and_then`], which is
1504 /// lazily evaluated.
1505 ///
1506 /// [`and_then`]: Option::and_then
1507 ///
1508 /// # Examples
1509 ///
1510 /// ```
1511 /// let x = Some(2);
1512 /// let y: Option<&str> = None;
1513 /// assert_eq!(x.and(y), None);
1514 ///
1515 /// let x: Option<u32> = None;
1516 /// let y = Some("foo");
1517 /// assert_eq!(x.and(y), None);
1518 ///
1519 /// let x = Some(2);
1520 /// let y = Some("foo");
1521 /// assert_eq!(x.and(y), Some("foo"));
1522 ///
1523 /// let x: Option<u32> = None;
1524 /// let y: Option<&str> = None;
1525 /// assert_eq!(x.and(y), None);
1526 /// ```
1527 #[inline]
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1530 #[ferrocene::prevalidated]
1531 pub const fn and<U>(self, optb: Option<U>) -> Option<U>
1532 where
1533 T: [const] Destruct,
1534 U: [const] Destruct,
1535 {
1536 match self {
1537 Some(_) => optb,
1538 None => None,
1539 }
1540 }
1541
1542 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1543 /// wrapped value and returns the result.
1544 ///
1545 /// Some languages call this operation flatmap.
1546 ///
1547 /// # Examples
1548 ///
1549 /// ```
1550 /// fn sq_then_to_string(x: u32) -> Option<String> {
1551 /// x.checked_mul(x).map(|sq| sq.to_string())
1552 /// }
1553 ///
1554 /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
1555 /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
1556 /// assert_eq!(None.and_then(sq_then_to_string), None);
1557 /// ```
1558 ///
1559 /// Often used to chain fallible operations that may return [`None`].
1560 ///
1561 /// ```
1562 /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
1563 ///
1564 /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1565 /// assert_eq!(item_0_1, Some(&"A1"));
1566 ///
1567 /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1568 /// assert_eq!(item_2_0, None);
1569 /// ```
1570 #[doc(alias = "flatmap")]
1571 #[inline]
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 #[rustc_confusables("flat_map", "flatmap")]
1574 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1575 #[ferrocene::prevalidated]
1576 pub const fn and_then<U, F>(self, f: F) -> Option<U>
1577 where
1578 F: [const] FnOnce(T) -> Option<U> + [const] Destruct,
1579 {
1580 match self {
1581 Some(x) => f(x),
1582 None => None,
1583 }
1584 }
1585
1586 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1587 /// with the wrapped value and returns:
1588 ///
1589 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1590 /// value), and
1591 /// - [`None`] if `predicate` returns `false`.
1592 ///
1593 /// This function works similar to [`Iterator::filter()`]. You can imagine
1594 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1595 /// lets you decide which elements to keep.
1596 ///
1597 /// # Examples
1598 ///
1599 /// ```rust
1600 /// fn is_even(n: &i32) -> bool {
1601 /// n % 2 == 0
1602 /// }
1603 ///
1604 /// assert_eq!(None.filter(is_even), None);
1605 /// assert_eq!(Some(3).filter(is_even), None);
1606 /// assert_eq!(Some(4).filter(is_even), Some(4));
1607 /// ```
1608 ///
1609 /// [`Some(t)`]: Some
1610 #[inline]
1611 #[stable(feature = "option_filter", since = "1.27.0")]
1612 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1613 #[ferrocene::prevalidated]
1614 pub const fn filter<P>(self, predicate: P) -> Self
1615 where
1616 P: [const] FnOnce(&T) -> bool + [const] Destruct,
1617 T: [const] Destruct,
1618 {
1619 if let Some(x) = self {
1620 if predicate(&x) {
1621 return Some(x);
1622 }
1623 }
1624 None
1625 }
1626
1627 /// Returns the option if it contains a value, otherwise returns `optb`.
1628 ///
1629 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1630 /// result of a function call, it is recommended to use [`or_else`], which is
1631 /// lazily evaluated.
1632 ///
1633 /// [`or_else`]: Option::or_else
1634 ///
1635 /// # Examples
1636 ///
1637 /// ```
1638 /// let x = Some(2);
1639 /// let y = None;
1640 /// assert_eq!(x.or(y), Some(2));
1641 ///
1642 /// let x = None;
1643 /// let y = Some(100);
1644 /// assert_eq!(x.or(y), Some(100));
1645 ///
1646 /// let x = Some(2);
1647 /// let y = Some(100);
1648 /// assert_eq!(x.or(y), Some(2));
1649 ///
1650 /// let x: Option<u32> = None;
1651 /// let y = None;
1652 /// assert_eq!(x.or(y), None);
1653 /// ```
1654 #[inline]
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1657 #[ferrocene::prevalidated]
1658 pub const fn or(self, optb: Option<T>) -> Option<T>
1659 where
1660 T: [const] Destruct,
1661 {
1662 match self {
1663 x @ Some(_) => x,
1664 None => optb,
1665 }
1666 }
1667
1668 /// Returns the option if it contains a value, otherwise calls `f` and
1669 /// returns the result.
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674 /// fn nobody() -> Option<&'static str> { None }
1675 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1676 ///
1677 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1678 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1679 /// assert_eq!(None.or_else(nobody), None);
1680 /// ```
1681 #[inline]
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1684 #[ferrocene::prevalidated]
1685 pub const fn or_else<F>(self, f: F) -> Option<T>
1686 where
1687 F: [const] FnOnce() -> Option<T> + [const] Destruct,
1688 //FIXME(const_hack): this `T: [const] Destruct` is unnecessary, but even precise live drops can't tell
1689 // no value of type `T` gets dropped here
1690 T: [const] Destruct,
1691 {
1692 match self {
1693 x @ Some(_) => x,
1694 None => f(),
1695 }
1696 }
1697
1698 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1699 ///
1700 /// # Examples
1701 ///
1702 /// ```
1703 /// let x = Some(2);
1704 /// let y: Option<u32> = None;
1705 /// assert_eq!(x.xor(y), Some(2));
1706 ///
1707 /// let x: Option<u32> = None;
1708 /// let y = Some(2);
1709 /// assert_eq!(x.xor(y), Some(2));
1710 ///
1711 /// let x = Some(2);
1712 /// let y = Some(2);
1713 /// assert_eq!(x.xor(y), None);
1714 ///
1715 /// let x: Option<u32> = None;
1716 /// let y: Option<u32> = None;
1717 /// assert_eq!(x.xor(y), None);
1718 /// ```
1719 #[inline]
1720 #[stable(feature = "option_xor", since = "1.37.0")]
1721 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1722 #[ferrocene::prevalidated]
1723 pub const fn xor(self, optb: Option<T>) -> Option<T>
1724 where
1725 T: [const] Destruct,
1726 {
1727 match (self, optb) {
1728 (a @ Some(_), None) => a,
1729 (None, b @ Some(_)) => b,
1730 _ => None,
1731 }
1732 }
1733
1734 /////////////////////////////////////////////////////////////////////////
1735 // Entry-like operations to insert a value and return a reference
1736 /////////////////////////////////////////////////////////////////////////
1737
1738 /// Inserts `value` into the option, then returns a mutable reference to it.
1739 ///
1740 /// If the option already contains a value, the old value is dropped.
1741 ///
1742 /// See also [`Option::get_or_insert`], which doesn't update the value if
1743 /// the option already contains [`Some`].
1744 ///
1745 /// # Example
1746 ///
1747 /// ```
1748 /// let mut opt = None;
1749 /// let val = opt.insert(1);
1750 /// assert_eq!(*val, 1);
1751 /// assert_eq!(opt.unwrap(), 1);
1752 /// let val = opt.insert(2);
1753 /// assert_eq!(*val, 2);
1754 /// *val = 3;
1755 /// assert_eq!(opt.unwrap(), 3);
1756 /// ```
1757 #[must_use = "if you intended to set a value, consider assignment instead"]
1758 #[inline]
1759 #[stable(feature = "option_insert", since = "1.53.0")]
1760 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1761 #[ferrocene::prevalidated]
1762 pub const fn insert(&mut self, value: T) -> &mut T
1763 where
1764 T: [const] Destruct,
1765 {
1766 *self = Some(value);
1767
1768 // SAFETY: the code above just filled the option
1769 unsafe { self.as_mut().unwrap_unchecked() }
1770 }
1771
1772 /// Inserts `value` into the option if it is [`None`], then
1773 /// returns a mutable reference to the contained value.
1774 ///
1775 /// See also [`Option::insert`], which updates the value even if
1776 /// the option already contains [`Some`].
1777 ///
1778 /// # Examples
1779 ///
1780 /// ```
1781 /// let mut x = None;
1782 ///
1783 /// {
1784 /// let y: &mut u32 = x.get_or_insert(5);
1785 /// assert_eq!(y, &5);
1786 ///
1787 /// *y = 7;
1788 /// }
1789 ///
1790 /// assert_eq!(x, Some(7));
1791 /// ```
1792 #[inline]
1793 #[stable(feature = "option_entry", since = "1.20.0")]
1794 pub fn get_or_insert(&mut self, value: T) -> &mut T {
1795 self.get_or_insert_with(|| value)
1796 }
1797
1798 /// Inserts the default value into the option if it is [`None`], then
1799 /// returns a mutable reference to the contained value.
1800 ///
1801 /// # Examples
1802 ///
1803 /// ```
1804 /// let mut x = None;
1805 ///
1806 /// {
1807 /// let y: &mut u32 = x.get_or_insert_default();
1808 /// assert_eq!(y, &0);
1809 ///
1810 /// *y = 7;
1811 /// }
1812 ///
1813 /// assert_eq!(x, Some(7));
1814 /// ```
1815 #[inline]
1816 #[stable(feature = "option_get_or_insert_default", since = "1.83.0")]
1817 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1818 pub const fn get_or_insert_default(&mut self) -> &mut T
1819 where
1820 T: [const] Default,
1821 {
1822 self.get_or_insert_with(T::default)
1823 }
1824
1825 /// Inserts a value computed from `f` into the option if it is [`None`],
1826 /// then returns a mutable reference to the contained value.
1827 ///
1828 /// # Examples
1829 ///
1830 /// ```
1831 /// let mut x = None;
1832 ///
1833 /// {
1834 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1835 /// assert_eq!(y, &5);
1836 ///
1837 /// *y = 7;
1838 /// }
1839 ///
1840 /// assert_eq!(x, Some(7));
1841 /// ```
1842 #[inline]
1843 #[stable(feature = "option_entry", since = "1.20.0")]
1844 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1845 pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1846 where
1847 F: [const] FnOnce() -> T + [const] Destruct,
1848 {
1849 if let None = self {
1850 // The effect of the following statement is identical to
1851 // *self = Some(f());
1852 // except that it does not drop the old value of `*self`. This is not a leak, because
1853 // we just checked that the old value is `None`, which contains no fields to drop.
1854 // This implementation strategy
1855 //
1856 // * avoids needing a `T: [const] Destruct` bound, to the benefit of `const` callers,
1857 // * and avoids possibly compiling needless drop code (as would sometimes happen in the
1858 // previous implementation), to the benefit of non-`const` callers.
1859 //
1860 // FIXME(const-hack): It would be nice if this weird trick were made obsolete
1861 // (though that is likely to be hard/wontfix).
1862 //
1863 // It could also be expressed as `unsafe { core::ptr::write(self, Some(f())) }`, but
1864 // no reason is currently known to use additional unsafe code here.
1865
1866 mem::forget(mem::replace(self, Some(f())));
1867 }
1868
1869 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1870 // variant in the code above.
1871 unsafe { self.as_mut().unwrap_unchecked() }
1872 }
1873
1874 /// If the option is `None`, calls the closure and inserts its output if successful.
1875 ///
1876 /// If the closure returns a residual value such as `Err` or `None`,
1877 /// that residual value is returned and nothing is inserted.
1878 ///
1879 /// If the option is `Some`, nothing is inserted.
1880 ///
1881 /// Unless a residual is returned, a mutable reference to the value
1882 /// of the option will be output.
1883 ///
1884 /// # Examples
1885 ///
1886 /// ```
1887 /// #![feature(option_get_or_try_insert_with)]
1888 /// let mut o1: Option<u32> = None;
1889 /// let mut o2: Option<u8> = None;
1890 ///
1891 /// let number = "12345";
1892 ///
1893 /// assert_eq!(o1.get_or_try_insert_with(|| number.parse()).copied(), Ok(12345));
1894 /// assert!(o2.get_or_try_insert_with(|| number.parse()).is_err());
1895 /// assert_eq!(o1, Some(12345));
1896 /// assert_eq!(o2, None);
1897 /// ```
1898 #[inline]
1899 #[unstable(feature = "option_get_or_try_insert_with", issue = "143648")]
1900 pub fn get_or_try_insert_with<'a, R, F>(
1901 &'a mut self,
1902 f: F,
1903 ) -> <R::Residual as Residual<&'a mut T>>::TryType
1904 where
1905 F: FnOnce() -> R,
1906 R: Try<Output = T, Residual: Residual<&'a mut T>>,
1907 {
1908 if let None = self {
1909 *self = Some(f()?);
1910 }
1911 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1912 // variant in the code above.
1913
1914 Try::from_output(unsafe { self.as_mut().unwrap_unchecked() })
1915 }
1916
1917 /////////////////////////////////////////////////////////////////////////
1918 // Misc
1919 /////////////////////////////////////////////////////////////////////////
1920
1921 /// Takes the value out of the option, leaving a [`None`] in its place.
1922 ///
1923 /// # Examples
1924 ///
1925 /// ```
1926 /// let mut x = Some(2);
1927 /// let y = x.take();
1928 /// assert_eq!(x, None);
1929 /// assert_eq!(y, Some(2));
1930 ///
1931 /// let mut x: Option<u32> = None;
1932 /// let y = x.take();
1933 /// assert_eq!(x, None);
1934 /// assert_eq!(y, None);
1935 /// ```
1936 #[inline]
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
1939 #[ferrocene::prevalidated]
1940 pub const fn take(&mut self) -> Option<T> {
1941 // FIXME(const-hack) replace `mem::replace` by `mem::take` when the latter is const ready
1942 mem::replace(self, None)
1943 }
1944
1945 /// Takes the value out of the option, but only if the predicate evaluates to
1946 /// `true` on a mutable reference to the value.
1947 ///
1948 /// In other words, replaces `self` with `None` if the predicate returns `true`.
1949 /// This method operates similar to [`Option::take`] but conditional.
1950 ///
1951 /// # Examples
1952 ///
1953 /// ```
1954 /// let mut x = Some(42);
1955 ///
1956 /// let prev = x.take_if(|v| if *v == 42 {
1957 /// *v += 1;
1958 /// false
1959 /// } else {
1960 /// false
1961 /// });
1962 /// assert_eq!(x, Some(43));
1963 /// assert_eq!(prev, None);
1964 ///
1965 /// let prev = x.take_if(|v| *v == 43);
1966 /// assert_eq!(x, None);
1967 /// assert_eq!(prev, Some(43));
1968 /// ```
1969 #[inline]
1970 #[stable(feature = "option_take_if", since = "1.80.0")]
1971 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
1972 pub const fn take_if<P>(&mut self, predicate: P) -> Option<T>
1973 where
1974 P: [const] FnOnce(&mut T) -> bool + [const] Destruct,
1975 {
1976 if self.as_mut().map_or(false, predicate) { self.take() } else { None }
1977 }
1978
1979 /// Replaces the actual value in the option by the value given in parameter,
1980 /// returning the old value if present,
1981 /// leaving a [`Some`] in its place without deinitializing either one.
1982 ///
1983 /// # Examples
1984 ///
1985 /// ```
1986 /// let mut x = Some(2);
1987 /// let old = x.replace(5);
1988 /// assert_eq!(x, Some(5));
1989 /// assert_eq!(old, Some(2));
1990 ///
1991 /// let mut x = None;
1992 /// let old = x.replace(3);
1993 /// assert_eq!(x, Some(3));
1994 /// assert_eq!(old, None);
1995 /// ```
1996 #[inline]
1997 #[stable(feature = "option_replace", since = "1.31.0")]
1998 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
1999 #[ferrocene::prevalidated]
2000 pub const fn replace(&mut self, value: T) -> Option<T> {
2001 mem::replace(self, Some(value))
2002 }
2003
2004 /// Zips `self` with another `Option`.
2005 ///
2006 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
2007 /// Otherwise, `None` is returned.
2008 ///
2009 /// # Examples
2010 ///
2011 /// ```
2012 /// let x = Some(1);
2013 /// let y = Some("hi");
2014 /// let z = None::<u8>;
2015 ///
2016 /// assert_eq!(x.zip(y), Some((1, "hi")));
2017 /// assert_eq!(x.zip(z), None);
2018 /// ```
2019 #[stable(feature = "option_zip_option", since = "1.46.0")]
2020 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
2021 #[ferrocene::prevalidated]
2022 pub const fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
2023 where
2024 T: [const] Destruct,
2025 U: [const] Destruct,
2026 {
2027 match (self, other) {
2028 (Some(a), Some(b)) => Some((a, b)),
2029 _ => None,
2030 }
2031 }
2032
2033 /// Zips `self` and another `Option` with function `f`.
2034 ///
2035 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
2036 /// Otherwise, `None` is returned.
2037 ///
2038 /// # Examples
2039 ///
2040 /// ```
2041 /// #![feature(option_zip)]
2042 ///
2043 /// #[derive(Debug, PartialEq)]
2044 /// struct Point {
2045 /// x: f64,
2046 /// y: f64,
2047 /// }
2048 ///
2049 /// impl Point {
2050 /// fn new(x: f64, y: f64) -> Self {
2051 /// Self { x, y }
2052 /// }
2053 /// }
2054 ///
2055 /// let x = Some(17.5);
2056 /// let y = Some(42.7);
2057 ///
2058 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
2059 /// assert_eq!(x.zip_with(None, Point::new), None);
2060 /// ```
2061 #[unstable(feature = "option_zip", issue = "70086")]
2062 #[rustc_const_unstable(feature = "const_option_ops", issue = "143956")]
2063 pub const fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
2064 where
2065 F: [const] FnOnce(T, U) -> R + [const] Destruct,
2066 T: [const] Destruct,
2067 U: [const] Destruct,
2068 {
2069 match (self, other) {
2070 (Some(a), Some(b)) => Some(f(a, b)),
2071 _ => None,
2072 }
2073 }
2074
2075 /// Reduces two options into one, using the provided function if both are `Some`.
2076 ///
2077 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
2078 /// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
2079 /// If both `self` and `other` are `None`, `None` is returned.
2080 ///
2081 /// # Examples
2082 ///
2083 /// ```
2084 /// #![feature(option_reduce)]
2085 ///
2086 /// let s12 = Some(12);
2087 /// let s17 = Some(17);
2088 /// let n = None;
2089 /// let f = |a, b| a + b;
2090 ///
2091 /// assert_eq!(s12.reduce(s17, f), Some(29));
2092 /// assert_eq!(s12.reduce(n, f), Some(12));
2093 /// assert_eq!(n.reduce(s17, f), Some(17));
2094 /// assert_eq!(n.reduce(n, f), None);
2095 /// ```
2096 #[unstable(feature = "option_reduce", issue = "144273")]
2097 #[ferrocene::prevalidated]
2098 pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
2099 where
2100 T: Into<R>,
2101 U: Into<R>,
2102 F: FnOnce(T, U) -> R,
2103 {
2104 match (self, other) {
2105 (Some(a), Some(b)) => Some(f(a, b)),
2106 (Some(a), _) => Some(a.into()),
2107 (_, Some(b)) => Some(b.into()),
2108 _ => None,
2109 }
2110 }
2111}
2112
2113impl<T: IntoIterator> Option<T> {
2114 /// Transforms an optional iterator into an iterator.
2115 ///
2116 /// If `self` is `None`, the resulting iterator is empty.
2117 /// Otherwise, an iterator is made from the `Some` value and returned.
2118 /// # Examples
2119 /// ```
2120 /// #![feature(option_into_flat_iter)]
2121 ///
2122 /// let o1 = Some([1, 2]);
2123 /// let o2 = None::<&[usize]>;
2124 ///
2125 /// assert_eq!(o1.into_flat_iter().collect::<Vec<_>>(), [1, 2]);
2126 /// assert_eq!(o2.into_flat_iter().collect::<Vec<_>>(), Vec::<&usize>::new());
2127 /// ```
2128 #[unstable(feature = "option_into_flat_iter", issue = "148441")]
2129 pub fn into_flat_iter<A>(self) -> OptionFlatten<A>
2130 where
2131 T: IntoIterator<IntoIter = A>,
2132 {
2133 OptionFlatten { iter: self.map(IntoIterator::into_iter) }
2134 }
2135}
2136
2137impl<T, U> Option<(T, U)> {
2138 /// Unzips an option containing a tuple of two options.
2139 ///
2140 /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
2141 /// Otherwise, `(None, None)` is returned.
2142 ///
2143 /// # Examples
2144 ///
2145 /// ```
2146 /// let x = Some((1, "hi"));
2147 /// let y = None::<(u8, u32)>;
2148 ///
2149 /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
2150 /// assert_eq!(y.unzip(), (None, None));
2151 /// ```
2152 #[inline]
2153 #[stable(feature = "unzip_option", since = "1.66.0")]
2154 #[ferrocene::prevalidated]
2155 pub fn unzip(self) -> (Option<T>, Option<U>) {
2156 match self {
2157 Some((a, b)) => (Some(a), Some(b)),
2158 None => (None, None),
2159 }
2160 }
2161}
2162
2163impl<T> Option<&T> {
2164 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
2165 /// option.
2166 ///
2167 /// # Examples
2168 ///
2169 /// ```
2170 /// let x = 12;
2171 /// let opt_x = Some(&x);
2172 /// assert_eq!(opt_x, Some(&12));
2173 /// let copied = opt_x.copied();
2174 /// assert_eq!(copied, Some(12));
2175 /// ```
2176 #[must_use = "`self` will be dropped if the result is not used"]
2177 #[stable(feature = "copied", since = "1.35.0")]
2178 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
2179 #[ferrocene::prevalidated]
2180 pub const fn copied(self) -> Option<T>
2181 where
2182 T: Copy,
2183 {
2184 // FIXME(const-hack): this implementation, which sidesteps using `Option::map` since it's not const
2185 // ready yet, should be reverted when possible to avoid code repetition
2186 match self {
2187 Some(&v) => Some(v),
2188 None => None,
2189 }
2190 }
2191
2192 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
2193 /// option.
2194 ///
2195 /// # Examples
2196 ///
2197 /// ```
2198 /// let x = 12;
2199 /// let opt_x = Some(&x);
2200 /// assert_eq!(opt_x, Some(&12));
2201 /// let cloned = opt_x.cloned();
2202 /// assert_eq!(cloned, Some(12));
2203 /// ```
2204 #[must_use = "`self` will be dropped if the result is not used"]
2205 #[stable(feature = "rust1", since = "1.0.0")]
2206 #[ferrocene::prevalidated]
2207 pub fn cloned(self) -> Option<T>
2208 where
2209 T: Clone,
2210 {
2211 self.map(T::clone)
2212 }
2213}
2214
2215impl<T> Option<&mut T> {
2216 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
2217 /// option.
2218 ///
2219 /// # Examples
2220 ///
2221 /// ```
2222 /// let mut x = 12;
2223 /// let opt_x = Some(&mut x);
2224 /// assert_eq!(opt_x, Some(&mut 12));
2225 /// let copied = opt_x.copied();
2226 /// assert_eq!(copied, Some(12));
2227 /// ```
2228 #[must_use = "`self` will be dropped if the result is not used"]
2229 #[stable(feature = "copied", since = "1.35.0")]
2230 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
2231 #[ferrocene::prevalidated]
2232 pub const fn copied(self) -> Option<T>
2233 where
2234 T: Copy,
2235 {
2236 match self {
2237 Some(&mut t) => Some(t),
2238 None => None,
2239 }
2240 }
2241
2242 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
2243 /// option.
2244 ///
2245 /// # Examples
2246 ///
2247 /// ```
2248 /// let mut x = 12;
2249 /// let opt_x = Some(&mut x);
2250 /// assert_eq!(opt_x, Some(&mut 12));
2251 /// let cloned = opt_x.cloned();
2252 /// assert_eq!(cloned, Some(12));
2253 /// ```
2254 #[must_use = "`self` will be dropped if the result is not used"]
2255 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
2256 #[ferrocene::prevalidated]
2257 pub fn cloned(self) -> Option<T>
2258 where
2259 T: Clone,
2260 {
2261 self.as_deref().map(T::clone)
2262 }
2263}
2264
2265impl<T, E> Option<Result<T, E>> {
2266 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
2267 ///
2268 /// <code>[Some]\([Ok]\(\_))</code> is mapped to <code>[Ok]\([Some]\(\_))</code>,
2269 /// <code>[Some]\([Err]\(\_))</code> is mapped to <code>[Err]\(\_)</code>,
2270 /// and [`None`] will be mapped to <code>[Ok]\([None])</code>.
2271 ///
2272 /// # Examples
2273 ///
2274 /// ```
2275 /// #[derive(Debug, Eq, PartialEq)]
2276 /// struct SomeErr;
2277 ///
2278 /// let x: Option<Result<i32, SomeErr>> = Some(Ok(5));
2279 /// let y: Result<Option<i32>, SomeErr> = Ok(Some(5));
2280 /// assert_eq!(x.transpose(), y);
2281 /// ```
2282 #[inline]
2283 #[stable(feature = "transpose_result", since = "1.33.0")]
2284 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
2285 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
2286 #[ferrocene::prevalidated]
2287 pub const fn transpose(self) -> Result<Option<T>, E> {
2288 match self {
2289 Some(Ok(x)) => Ok(Some(x)),
2290 Some(Err(e)) => Err(e),
2291 None => Ok(None),
2292 }
2293 }
2294}
2295
2296#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2297#[cfg_attr(panic = "immediate-abort", inline)]
2298#[cold]
2299#[track_caller]
2300#[ferrocene::prevalidated]
2301const fn unwrap_failed() -> ! {
2302 panic("called `Option::unwrap()` on a `None` value")
2303}
2304
2305// This is a separate function to reduce the code size of .expect() itself.
2306#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2307#[cfg_attr(panic = "immediate-abort", inline)]
2308#[cold]
2309#[track_caller]
2310#[ferrocene::prevalidated]
2311const fn expect_failed(msg: &str) -> ! {
2312 panic_display(&msg)
2313}
2314
2315/////////////////////////////////////////////////////////////////////////////
2316// Trait implementations
2317/////////////////////////////////////////////////////////////////////////////
2318
2319#[stable(feature = "rust1", since = "1.0.0")]
2320#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
2321impl<T> const Clone for Option<T>
2322where
2323 // FIXME(const_hack): the T: [const] Destruct should be inferred from the Self: [const] Destruct in clone_from.
2324 // See https://github.com/rust-lang/rust/issues/144207
2325 T: [const] Clone + [const] Destruct,
2326{
2327 #[inline]
2328 #[ferrocene::prevalidated]
2329 fn clone(&self) -> Self {
2330 match self {
2331 Some(x) => Some(x.clone()),
2332 None => None,
2333 }
2334 }
2335
2336 #[inline]
2337 #[ferrocene::prevalidated]
2338 fn clone_from(&mut self, source: &Self) {
2339 match (self, source) {
2340 (Some(to), Some(from)) => to.clone_from(from),
2341 (to, from) => *to = from.clone(),
2342 }
2343 }
2344}
2345
2346#[unstable(feature = "ergonomic_clones", issue = "132290")]
2347impl<T> crate::clone::UseCloned for Option<T> where T: crate::clone::UseCloned {}
2348
2349#[doc(hidden)]
2350#[unstable(feature = "trivial_clone", issue = "none")]
2351#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
2352unsafe impl<T> const TrivialClone for Option<T> where T: [const] TrivialClone + [const] Destruct {}
2353
2354#[stable(feature = "rust1", since = "1.0.0")]
2355#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2356impl<T> const Default for Option<T> {
2357 /// Returns [`None`][Option::None].
2358 ///
2359 /// # Examples
2360 ///
2361 /// ```
2362 /// let opt: Option<u32> = Option::default();
2363 /// assert!(opt.is_none());
2364 /// ```
2365 #[inline]
2366 #[ferrocene::prevalidated]
2367 fn default() -> Option<T> {
2368 None
2369 }
2370}
2371
2372#[stable(feature = "rust1", since = "1.0.0")]
2373#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
2374impl<T> const IntoIterator for Option<T> {
2375 type Item = T;
2376 type IntoIter = IntoIter<T>;
2377
2378 /// Returns a consuming iterator over the possibly contained value.
2379 ///
2380 /// # Examples
2381 ///
2382 /// ```
2383 /// let x = Some("string");
2384 /// let v: Vec<&str> = x.into_iter().collect();
2385 /// assert_eq!(v, ["string"]);
2386 ///
2387 /// let x = None;
2388 /// let v: Vec<&str> = x.into_iter().collect();
2389 /// assert!(v.is_empty());
2390 /// ```
2391 #[inline]
2392 #[ferrocene::prevalidated]
2393 fn into_iter(self) -> IntoIter<T> {
2394 IntoIter { inner: Item { opt: self } }
2395 }
2396}
2397
2398#[stable(since = "1.4.0", feature = "option_iter")]
2399impl<'a, T> IntoIterator for &'a Option<T> {
2400 type Item = &'a T;
2401 type IntoIter = Iter<'a, T>;
2402
2403 fn into_iter(self) -> Iter<'a, T> {
2404 self.iter()
2405 }
2406}
2407
2408#[stable(since = "1.4.0", feature = "option_iter")]
2409impl<'a, T> IntoIterator for &'a mut Option<T> {
2410 type Item = &'a mut T;
2411 type IntoIter = IterMut<'a, T>;
2412
2413 fn into_iter(self) -> IterMut<'a, T> {
2414 self.iter_mut()
2415 }
2416}
2417
2418#[stable(since = "1.12.0", feature = "option_from")]
2419#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2420impl<T> const From<T> for Option<T> {
2421 /// Moves `val` into a new [`Some`].
2422 ///
2423 /// # Examples
2424 ///
2425 /// ```
2426 /// let o: Option<u8> = Option::from(67);
2427 ///
2428 /// assert_eq!(Some(67), o);
2429 /// ```
2430 #[ferrocene::prevalidated]
2431 fn from(val: T) -> Option<T> {
2432 Some(val)
2433 }
2434}
2435
2436#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2437#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2438impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
2439 /// Converts from `&Option<T>` to `Option<&T>`.
2440 ///
2441 /// # Examples
2442 ///
2443 /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
2444 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
2445 /// so this technique uses `from` to first take an [`Option`] to a reference
2446 /// to the value inside the original.
2447 ///
2448 /// [`map`]: Option::map
2449 /// [String]: ../../std/string/struct.String.html "String"
2450 ///
2451 /// ```
2452 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
2453 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
2454 ///
2455 /// println!("Can still print s: {s:?}");
2456 ///
2457 /// assert_eq!(o, Some(18));
2458 /// ```
2459 #[ferrocene::prevalidated]
2460 fn from(o: &'a Option<T>) -> Option<&'a T> {
2461 o.as_ref()
2462 }
2463}
2464
2465#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2466#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2467impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> {
2468 /// Converts from `&mut Option<T>` to `Option<&mut T>`
2469 ///
2470 /// # Examples
2471 ///
2472 /// ```
2473 /// let mut s = Some(String::from("Hello"));
2474 /// let o: Option<&mut String> = Option::from(&mut s);
2475 ///
2476 /// match o {
2477 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
2478 /// None => (),
2479 /// }
2480 ///
2481 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
2482 /// ```
2483 #[ferrocene::prevalidated]
2484 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
2485 o.as_mut()
2486 }
2487}
2488
2489// Ideally, LLVM should be able to optimize our derive code to this.
2490// Once https://github.com/llvm/llvm-project/issues/52622 is fixed, we can
2491// go back to deriving `PartialEq`.
2492#[stable(feature = "rust1", since = "1.0.0")]
2493impl<T> crate::marker::StructuralPartialEq for Option<T> {}
2494#[stable(feature = "rust1", since = "1.0.0")]
2495#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2496impl<T: [const] PartialEq> const PartialEq for Option<T> {
2497 #[inline]
2498 #[ferrocene::prevalidated]
2499 fn eq(&self, other: &Self) -> bool {
2500 // Spelling out the cases explicitly optimizes better than
2501 // `_ => false`
2502 match (self, other) {
2503 (Some(l), Some(r)) => *l == *r,
2504 (Some(_), None) => false,
2505 (None, Some(_)) => false,
2506 (None, None) => true,
2507 }
2508 }
2509}
2510
2511// Manually implementing here somewhat improves codegen for
2512// https://github.com/rust-lang/rust/issues/49892, although still
2513// not optimal.
2514#[stable(feature = "rust1", since = "1.0.0")]
2515#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2516impl<T: [const] PartialOrd> const PartialOrd for Option<T> {
2517 #[inline]
2518 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2519 match (self, other) {
2520 (Some(l), Some(r)) => l.partial_cmp(r),
2521 (Some(_), None) => Some(cmp::Ordering::Greater),
2522 (None, Some(_)) => Some(cmp::Ordering::Less),
2523 (None, None) => Some(cmp::Ordering::Equal),
2524 }
2525 }
2526}
2527
2528#[stable(feature = "rust1", since = "1.0.0")]
2529#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2530impl<T: [const] Ord> const Ord for Option<T> {
2531 #[inline]
2532 fn cmp(&self, other: &Self) -> cmp::Ordering {
2533 match (self, other) {
2534 (Some(l), Some(r)) => l.cmp(r),
2535 (Some(_), None) => cmp::Ordering::Greater,
2536 (None, Some(_)) => cmp::Ordering::Less,
2537 (None, None) => cmp::Ordering::Equal,
2538 }
2539 }
2540}
2541
2542/////////////////////////////////////////////////////////////////////////////
2543// The Option Iterators
2544/////////////////////////////////////////////////////////////////////////////
2545
2546#[derive(Clone, Debug)]
2547#[ferrocene::prevalidated]
2548struct Item<A> {
2549 opt: Option<A>,
2550}
2551
2552#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
2553impl<A> const Iterator for Item<A> {
2554 type Item = A;
2555
2556 #[inline]
2557 #[ferrocene::prevalidated]
2558 fn next(&mut self) -> Option<A> {
2559 self.opt.take()
2560 }
2561
2562 #[inline]
2563 #[ferrocene::prevalidated]
2564 fn size_hint(&self) -> (usize, Option<usize>) {
2565 let len = self.opt.len();
2566 (len, Some(len))
2567 }
2568}
2569
2570impl<A> DoubleEndedIterator for Item<A> {
2571 #[inline]
2572 fn next_back(&mut self) -> Option<A> {
2573 self.opt.take()
2574 }
2575}
2576
2577impl<A> ExactSizeIterator for Item<A> {
2578 #[inline]
2579 #[ferrocene::prevalidated]
2580 fn len(&self) -> usize {
2581 self.opt.len()
2582 }
2583}
2584impl<A> FusedIterator for Item<A> {}
2585unsafe impl<A> TrustedLen for Item<A> {}
2586
2587/// An iterator over a reference to the [`Some`] variant of an [`Option`].
2588///
2589/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2590///
2591/// This `struct` is created by the [`Option::iter`] function.
2592#[stable(feature = "rust1", since = "1.0.0")]
2593#[derive(Debug)]
2594#[ferrocene::prevalidated]
2595pub struct Iter<'a, A: 'a> {
2596 inner: Item<&'a A>,
2597}
2598
2599#[stable(feature = "rust1", since = "1.0.0")]
2600impl<'a, A> Iterator for Iter<'a, A> {
2601 type Item = &'a A;
2602
2603 #[inline]
2604 fn next(&mut self) -> Option<&'a A> {
2605 self.inner.next()
2606 }
2607 #[inline]
2608 fn size_hint(&self) -> (usize, Option<usize>) {
2609 self.inner.size_hint()
2610 }
2611}
2612
2613#[stable(feature = "rust1", since = "1.0.0")]
2614impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2615 #[inline]
2616 fn next_back(&mut self) -> Option<&'a A> {
2617 self.inner.next_back()
2618 }
2619}
2620
2621#[stable(feature = "rust1", since = "1.0.0")]
2622impl<A> ExactSizeIterator for Iter<'_, A> {}
2623
2624#[stable(feature = "fused", since = "1.26.0")]
2625impl<A> FusedIterator for Iter<'_, A> {}
2626
2627#[unstable(feature = "trusted_len", issue = "37572")]
2628unsafe impl<A> TrustedLen for Iter<'_, A> {}
2629
2630#[stable(feature = "rust1", since = "1.0.0")]
2631impl<A> Clone for Iter<'_, A> {
2632 #[inline]
2633 fn clone(&self) -> Self {
2634 Iter { inner: self.inner.clone() }
2635 }
2636}
2637
2638/// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2639///
2640/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2641///
2642/// This `struct` is created by the [`Option::iter_mut`] function.
2643#[stable(feature = "rust1", since = "1.0.0")]
2644#[derive(Debug)]
2645#[ferrocene::prevalidated]
2646pub struct IterMut<'a, A: 'a> {
2647 inner: Item<&'a mut A>,
2648}
2649
2650#[stable(feature = "rust1", since = "1.0.0")]
2651impl<'a, A> Iterator for IterMut<'a, A> {
2652 type Item = &'a mut A;
2653
2654 #[inline]
2655 fn next(&mut self) -> Option<&'a mut A> {
2656 self.inner.next()
2657 }
2658 #[inline]
2659 fn size_hint(&self) -> (usize, Option<usize>) {
2660 self.inner.size_hint()
2661 }
2662}
2663
2664#[stable(feature = "rust1", since = "1.0.0")]
2665impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2666 #[inline]
2667 fn next_back(&mut self) -> Option<&'a mut A> {
2668 self.inner.next_back()
2669 }
2670}
2671
2672#[stable(feature = "rust1", since = "1.0.0")]
2673impl<A> ExactSizeIterator for IterMut<'_, A> {}
2674
2675#[stable(feature = "fused", since = "1.26.0")]
2676impl<A> FusedIterator for IterMut<'_, A> {}
2677#[unstable(feature = "trusted_len", issue = "37572")]
2678unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2679
2680/// An iterator over the value in [`Some`] variant of an [`Option`].
2681///
2682/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2683///
2684/// This `struct` is created by the [`Option::into_iter`] function.
2685#[derive(Clone, Debug)]
2686#[stable(feature = "rust1", since = "1.0.0")]
2687#[ferrocene::prevalidated]
2688pub struct IntoIter<A> {
2689 inner: Item<A>,
2690}
2691
2692#[stable(feature = "rust1", since = "1.0.0")]
2693#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
2694impl<A> const Iterator for IntoIter<A> {
2695 type Item = A;
2696
2697 #[inline]
2698 #[ferrocene::prevalidated]
2699 fn next(&mut self) -> Option<A> {
2700 self.inner.next()
2701 }
2702 #[inline]
2703 #[ferrocene::prevalidated]
2704 fn size_hint(&self) -> (usize, Option<usize>) {
2705 self.inner.size_hint()
2706 }
2707}
2708
2709#[stable(feature = "rust1", since = "1.0.0")]
2710impl<A> DoubleEndedIterator for IntoIter<A> {
2711 #[inline]
2712 fn next_back(&mut self) -> Option<A> {
2713 self.inner.next_back()
2714 }
2715}
2716
2717#[stable(feature = "rust1", since = "1.0.0")]
2718impl<A> ExactSizeIterator for IntoIter<A> {}
2719
2720#[stable(feature = "fused", since = "1.26.0")]
2721impl<A> FusedIterator for IntoIter<A> {}
2722
2723#[unstable(feature = "trusted_len", issue = "37572")]
2724unsafe impl<A> TrustedLen for IntoIter<A> {}
2725
2726/// The iterator produced by [`Option::into_flat_iter`]. See its documentation for more.
2727#[derive(Clone, Debug)]
2728#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2729pub struct OptionFlatten<A> {
2730 iter: Option<A>,
2731}
2732
2733#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2734impl<A: Iterator> Iterator for OptionFlatten<A> {
2735 type Item = A::Item;
2736
2737 fn next(&mut self) -> Option<Self::Item> {
2738 self.iter.as_mut()?.next()
2739 }
2740
2741 fn size_hint(&self) -> (usize, Option<usize>) {
2742 self.iter.as_ref().map(|i| i.size_hint()).unwrap_or((0, Some(0)))
2743 }
2744}
2745
2746#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2747impl<A: DoubleEndedIterator> DoubleEndedIterator for OptionFlatten<A> {
2748 fn next_back(&mut self) -> Option<Self::Item> {
2749 self.iter.as_mut()?.next_back()
2750 }
2751}
2752
2753#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2754impl<A: ExactSizeIterator> ExactSizeIterator for OptionFlatten<A> {}
2755
2756#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2757impl<A: FusedIterator> FusedIterator for OptionFlatten<A> {}
2758
2759#[unstable(feature = "option_into_flat_iter", issue = "148441")]
2760unsafe impl<A: TrustedLen> TrustedLen for OptionFlatten<A> {}
2761
2762/////////////////////////////////////////////////////////////////////////////
2763// FromIterator
2764/////////////////////////////////////////////////////////////////////////////
2765
2766#[stable(feature = "rust1", since = "1.0.0")]
2767impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2768 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2769 /// no further elements are taken, and the [`None`][Option::None] is
2770 /// returned. Should no [`None`][Option::None] occur, a container of type
2771 /// `V` containing the values of each [`Option`] is returned.
2772 ///
2773 /// # Examples
2774 ///
2775 /// Here is an example which increments every integer in a vector.
2776 /// We use the checked variant of `add` that returns `None` when the
2777 /// calculation would result in an overflow.
2778 ///
2779 /// ```
2780 /// let items = vec![0_u16, 1, 2];
2781 ///
2782 /// let res: Option<Vec<u16>> = items
2783 /// .iter()
2784 /// .map(|x| x.checked_add(1))
2785 /// .collect();
2786 ///
2787 /// assert_eq!(res, Some(vec![1, 2, 3]));
2788 /// ```
2789 ///
2790 /// As you can see, this will return the expected, valid items.
2791 ///
2792 /// Here is another example that tries to subtract one from another list
2793 /// of integers, this time checking for underflow:
2794 ///
2795 /// ```
2796 /// let items = vec![2_u16, 1, 0];
2797 ///
2798 /// let res: Option<Vec<u16>> = items
2799 /// .iter()
2800 /// .map(|x| x.checked_sub(1))
2801 /// .collect();
2802 ///
2803 /// assert_eq!(res, None);
2804 /// ```
2805 ///
2806 /// Since the last element is zero, it would underflow. Thus, the resulting
2807 /// value is `None`.
2808 ///
2809 /// Here is a variation on the previous example, showing that no
2810 /// further elements are taken from `iter` after the first `None`.
2811 ///
2812 /// ```
2813 /// let items = vec![3_u16, 2, 1, 10];
2814 ///
2815 /// let mut shared = 0;
2816 ///
2817 /// let res: Option<Vec<u16>> = items
2818 /// .iter()
2819 /// .map(|x| { shared += x; x.checked_sub(2) })
2820 /// .collect();
2821 ///
2822 /// assert_eq!(res, None);
2823 /// assert_eq!(shared, 6);
2824 /// ```
2825 ///
2826 /// Since the third element caused an underflow, no further elements were taken,
2827 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2828 #[inline]
2829 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2830 iter::try_process(iter.into_iter(), |i| i.collect())
2831 }
2832}
2833
2834#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
2835#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2836impl<T> const ops::Try for Option<T> {
2837 type Output = T;
2838 type Residual = Option<convert::Infallible>;
2839
2840 #[inline]
2841 #[ferrocene::prevalidated]
2842 fn from_output(output: Self::Output) -> Self {
2843 Some(output)
2844 }
2845
2846 #[inline]
2847 #[ferrocene::prevalidated]
2848 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2849 match self {
2850 Some(v) => ControlFlow::Continue(v),
2851 None => ControlFlow::Break(None),
2852 }
2853 }
2854}
2855
2856#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
2857#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2858// Note: manually specifying the residual type instead of using the default to work around
2859// https://github.com/rust-lang/rust/issues/99940
2860impl<T> const ops::FromResidual<Option<convert::Infallible>> for Option<T> {
2861 #[inline]
2862 #[ferrocene::prevalidated]
2863 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2864 match residual {
2865 None => None,
2866 }
2867 }
2868}
2869
2870#[diagnostic::do_not_recommend]
2871#[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2872#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2873impl<T> const ops::FromResidual<ops::Yeet<()>> for Option<T> {
2874 #[inline]
2875 fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self {
2876 None
2877 }
2878}
2879
2880#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2881#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2882impl<T> const ops::Residual<T> for Option<convert::Infallible> {
2883 type TryType = Option<T>;
2884}
2885
2886impl<T> Option<Option<T>> {
2887 /// Converts from `Option<Option<T>>` to `Option<T>`.
2888 ///
2889 /// # Examples
2890 ///
2891 /// Basic usage:
2892 ///
2893 /// ```
2894 /// let x: Option<Option<u32>> = Some(Some(6));
2895 /// assert_eq!(Some(6), x.flatten());
2896 ///
2897 /// let x: Option<Option<u32>> = Some(None);
2898 /// assert_eq!(None, x.flatten());
2899 ///
2900 /// let x: Option<Option<u32>> = None;
2901 /// assert_eq!(None, x.flatten());
2902 /// ```
2903 ///
2904 /// Flattening only removes one level of nesting at a time:
2905 ///
2906 /// ```
2907 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2908 /// assert_eq!(Some(Some(6)), x.flatten());
2909 /// assert_eq!(Some(6), x.flatten().flatten());
2910 /// ```
2911 #[inline]
2912 #[stable(feature = "option_flattening", since = "1.40.0")]
2913 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
2914 #[rustc_const_stable(feature = "const_option", since = "1.83.0")]
2915 #[ferrocene::prevalidated]
2916 pub const fn flatten(self) -> Option<T> {
2917 // FIXME(const-hack): could be written with `and_then`
2918 match self {
2919 Some(inner) => inner,
2920 None => None,
2921 }
2922 }
2923}
2924
2925impl<'a, T> Option<&'a Option<T>> {
2926 /// Converts from `Option<&Option<T>>` to `Option<&T>`.
2927 ///
2928 /// # Examples
2929 ///
2930 /// Basic usage:
2931 ///
2932 /// ```
2933 /// #![feature(option_reference_flattening)]
2934 ///
2935 /// let x: Option<&Option<u32>> = Some(&Some(6));
2936 /// assert_eq!(Some(&6), x.flatten_ref());
2937 ///
2938 /// let x: Option<&Option<u32>> = Some(&None);
2939 /// assert_eq!(None, x.flatten_ref());
2940 ///
2941 /// let x: Option<&Option<u32>> = None;
2942 /// assert_eq!(None, x.flatten_ref());
2943 /// ```
2944 #[inline]
2945 #[unstable(feature = "option_reference_flattening", issue = "149221")]
2946 pub const fn flatten_ref(self) -> Option<&'a T> {
2947 match self {
2948 Some(inner) => inner.as_ref(),
2949 None => None,
2950 }
2951 }
2952}
2953
2954impl<'a, T> Option<&'a mut Option<T>> {
2955 /// Converts from `Option<&mut Option<T>>` to `&Option<T>`.
2956 ///
2957 /// # Examples
2958 ///
2959 /// Basic usage:
2960 ///
2961 /// ```
2962 /// #![feature(option_reference_flattening)]
2963 ///
2964 /// let y = &mut Some(6);
2965 /// let x: Option<&mut Option<u32>> = Some(y);
2966 /// assert_eq!(Some(&6), x.flatten_ref());
2967 ///
2968 /// let y: &mut Option<u32> = &mut None;
2969 /// let x: Option<&mut Option<u32>> = Some(y);
2970 /// assert_eq!(None, x.flatten_ref());
2971 ///
2972 /// let x: Option<&mut Option<u32>> = None;
2973 /// assert_eq!(None, x.flatten_ref());
2974 /// ```
2975 #[inline]
2976 #[unstable(feature = "option_reference_flattening", issue = "149221")]
2977 pub const fn flatten_ref(self) -> Option<&'a T> {
2978 match self {
2979 Some(inner) => inner.as_ref(),
2980 None => None,
2981 }
2982 }
2983
2984 /// Converts from `Option<&mut Option<T>>` to `Option<&mut T>`.
2985 ///
2986 /// # Examples
2987 ///
2988 /// Basic usage:
2989 ///
2990 /// ```
2991 /// #![feature(option_reference_flattening)]
2992 ///
2993 /// let y: &mut Option<u32> = &mut Some(6);
2994 /// let x: Option<&mut Option<u32>> = Some(y);
2995 /// assert_eq!(Some(&mut 6), x.flatten_mut());
2996 ///
2997 /// let y: &mut Option<u32> = &mut None;
2998 /// let x: Option<&mut Option<u32>> = Some(y);
2999 /// assert_eq!(None, x.flatten_mut());
3000 ///
3001 /// let x: Option<&mut Option<u32>> = None;
3002 /// assert_eq!(None, x.flatten_mut());
3003 /// ```
3004 #[inline]
3005 #[unstable(feature = "option_reference_flattening", issue = "149221")]
3006 pub const fn flatten_mut(self) -> Option<&'a mut T> {
3007 match self {
3008 Some(inner) => inner.as_mut(),
3009 None => None,
3010 }
3011 }
3012}
3013
3014impl<T, const N: usize> [Option<T>; N] {
3015 /// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`.
3016 ///
3017 /// # Examples
3018 ///
3019 /// ```
3020 /// #![feature(option_array_transpose)]
3021 /// # use std::option::Option;
3022 ///
3023 /// let data = [Some(0); 1000];
3024 /// let data: Option<[u8; 1000]> = data.transpose();
3025 /// assert_eq!(data, Some([0; 1000]));
3026 ///
3027 /// let data = [Some(0), None];
3028 /// let data: Option<[u8; 2]> = data.transpose();
3029 /// assert_eq!(data, None);
3030 /// ```
3031 #[inline]
3032 #[unstable(feature = "option_array_transpose", issue = "130828")]
3033 pub fn transpose(self) -> Option<[T; N]> {
3034 self.try_map(core::convert::identity)
3035 }
3036}