]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
54a0048b | 11 | //! Optional values. |
1a4d82fc | 12 | //! |
9e0c209e SL |
13 | //! Type [`Option`] represents an optional value: every [`Option`] |
14 | //! is either [`Some`] and contains a value, or [`None`], and | |
15 | //! does not. [`Option`] types are very common in Rust code, as | |
1a4d82fc JJ |
16 | //! they have a number of uses: |
17 | //! | |
18 | //! * Initial values | |
19 | //! * Return values for functions that are not defined | |
20 | //! over their entire input range (partial functions) | |
21 | //! * Return value for otherwise reporting simple errors, where `None` is | |
22 | //! returned on error | |
23 | //! * Optional struct fields | |
24 | //! * Struct fields that can be loaned or "taken" | |
25 | //! * Optional function arguments | |
26 | //! * Nullable pointers | |
27 | //! * Swapping things out of difficult situations | |
28 | //! | |
9e0c209e SL |
29 | //! [`Option`]s are commonly paired with pattern matching to query the presence |
30 | //! of a value and take action, always accounting for the [`None`] case. | |
1a4d82fc JJ |
31 | //! |
32 | //! ``` | |
33 | //! fn divide(numerator: f64, denominator: f64) -> Option<f64> { | |
34 | //! if denominator == 0.0 { | |
35 | //! None | |
36 | //! } else { | |
37 | //! Some(numerator / denominator) | |
38 | //! } | |
39 | //! } | |
40 | //! | |
41 | //! // The return value of the function is an option | |
42 | //! let result = divide(2.0, 3.0); | |
43 | //! | |
44 | //! // Pattern match to retrieve the value | |
45 | //! match result { | |
46 | //! // The division was valid | |
47 | //! Some(x) => println!("Result: {}", x), | |
48 | //! // The division was invalid | |
c1a9b12d | 49 | //! None => println!("Cannot divide by 0"), |
1a4d82fc JJ |
50 | //! } |
51 | //! ``` | |
52 | //! | |
53 | // | |
54 | // FIXME: Show how `Option` is used in practice, with lots of methods | |
55 | // | |
56 | //! # Options and pointers ("nullable" pointers) | |
57 | //! | |
58 | //! Rust's pointer types must always point to a valid location; there are | |
59 | //! no "null" pointers. Instead, Rust has *optional* pointers, like | |
9e0c209e | 60 | //! the optional owned box, [`Option`]`<`[`Box<T>`]`>`. |
1a4d82fc | 61 | //! |
9e0c209e | 62 | //! The following example uses [`Option`] to create an optional box of |
32a655c1 | 63 | //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the |
1a4d82fc | 64 | //! `check_optional` function needs to use pattern matching to |
9e0c209e SL |
65 | //! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or |
66 | //! not ([`None`]). | |
1a4d82fc JJ |
67 | //! |
68 | //! ``` | |
7cac9316 XL |
69 | //! let optional = None; |
70 | //! check_optional(optional); | |
1a4d82fc | 71 | //! |
7cac9316 XL |
72 | //! let optional = Some(Box::new(9000)); |
73 | //! check_optional(optional); | |
1a4d82fc | 74 | //! |
7cac9316 XL |
75 | //! fn check_optional(optional: Option<Box<i32>>) { |
76 | //! match optional { | |
32a655c1 SL |
77 | //! Some(ref p) => println!("has value {}", p), |
78 | //! None => println!("has no value"), | |
1a4d82fc JJ |
79 | //! } |
80 | //! } | |
81 | //! ``` | |
82 | //! | |
9e0c209e | 83 | //! This usage of [`Option`] to create safe nullable pointers is so |
1a4d82fc | 84 | //! common that Rust does special optimizations to make the |
9e0c209e | 85 | //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers |
1a4d82fc JJ |
86 | //! in Rust are stored as efficiently as any other pointer type. |
87 | //! | |
88 | //! # Examples | |
89 | //! | |
9e0c209e | 90 | //! Basic pattern matching on [`Option`]: |
1a4d82fc JJ |
91 | //! |
92 | //! ``` | |
93 | //! let msg = Some("howdy"); | |
94 | //! | |
95 | //! // Take a reference to the contained string | |
54a0048b SL |
96 | //! if let Some(ref m) = msg { |
97 | //! println!("{}", *m); | |
1a4d82fc JJ |
98 | //! } |
99 | //! | |
100 | //! // Remove the contained string, destroying the Option | |
54a0048b | 101 | //! let unwrapped_msg = msg.unwrap_or("default message"); |
1a4d82fc JJ |
102 | //! ``` |
103 | //! | |
9e0c209e | 104 | //! Initialize a result to [`None`] before a loop: |
1a4d82fc JJ |
105 | //! |
106 | //! ``` | |
85aaf69f | 107 | //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } |
1a4d82fc JJ |
108 | //! |
109 | //! // A list of data to search through. | |
110 | //! let all_the_big_things = [ | |
111 | //! Kingdom::Plant(250, "redwood"), | |
112 | //! Kingdom::Plant(230, "noble fir"), | |
113 | //! Kingdom::Plant(229, "sugar pine"), | |
114 | //! Kingdom::Animal(25, "blue whale"), | |
115 | //! Kingdom::Animal(19, "fin whale"), | |
116 | //! Kingdom::Animal(15, "north pacific right whale"), | |
117 | //! ]; | |
118 | //! | |
119 | //! // We're going to search for the name of the biggest animal, | |
120 | //! // but to start with we've just got `None`. | |
121 | //! let mut name_of_biggest_animal = None; | |
122 | //! let mut size_of_biggest_animal = 0; | |
62682a34 | 123 | //! for big_thing in &all_the_big_things { |
1a4d82fc JJ |
124 | //! match *big_thing { |
125 | //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => { | |
126 | //! // Now we've found the name of some big animal | |
127 | //! size_of_biggest_animal = size; | |
128 | //! name_of_biggest_animal = Some(name); | |
129 | //! } | |
130 | //! Kingdom::Animal(..) | Kingdom::Plant(..) => () | |
131 | //! } | |
132 | //! } | |
133 | //! | |
134 | //! match name_of_biggest_animal { | |
135 | //! Some(name) => println!("the biggest animal is {}", name), | |
c1a9b12d | 136 | //! None => println!("there are no animals :("), |
1a4d82fc JJ |
137 | //! } |
138 | //! ``` | |
9e0c209e SL |
139 | //! |
140 | //! [`Option`]: enum.Option.html | |
141 | //! [`Some`]: enum.Option.html#variant.Some | |
142 | //! [`None`]: enum.Option.html#variant.None | |
143 | //! [`Box<T>`]: ../../std/boxed/struct.Box.html | |
144 | //! [`i32`]: ../../std/primitive.i32.html | |
1a4d82fc | 145 | |
85aaf69f | 146 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 147 | |
c30ab7b3 | 148 | use iter::{FromIterator, FusedIterator, TrustedLen}; |
ea8adc8c | 149 | use {mem, ops}; |
1a4d82fc JJ |
150 | |
151 | // Note that this is not a lang item per se, but it has a hidden dependency on | |
152 | // `Iterator`, which is one. The compiler assumes that the `next` method of | |
153 | // `Iterator` is an enumeration with one type parameter and two variants, | |
154 | // which basically means it must be `Option`. | |
155 | ||
d9579d0f | 156 | /// The `Option` type. See [the module level documentation](index.html) for more. |
85aaf69f SL |
157 | #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] |
158 | #[stable(feature = "rust1", since = "1.0.0")] | |
1a4d82fc JJ |
159 | pub enum Option<T> { |
160 | /// No value | |
85aaf69f | 161 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
162 | None, |
163 | /// Some value `T` | |
85aaf69f | 164 | #[stable(feature = "rust1", since = "1.0.0")] |
9e0c209e | 165 | Some(#[stable(feature = "rust1", since = "1.0.0")] T), |
1a4d82fc JJ |
166 | } |
167 | ||
168 | ///////////////////////////////////////////////////////////////////////////// | |
169 | // Type implementation | |
170 | ///////////////////////////////////////////////////////////////////////////// | |
171 | ||
172 | impl<T> Option<T> { | |
173 | ///////////////////////////////////////////////////////////////////////// | |
174 | // Querying the contained values | |
175 | ///////////////////////////////////////////////////////////////////////// | |
176 | ||
7cac9316 | 177 | /// Returns `true` if the option is a [`Some`] value. |
1a4d82fc | 178 | /// |
c34b1796 | 179 | /// # Examples |
1a4d82fc JJ |
180 | /// |
181 | /// ``` | |
85aaf69f | 182 | /// let x: Option<u32> = Some(2); |
1a4d82fc JJ |
183 | /// assert_eq!(x.is_some(), true); |
184 | /// | |
85aaf69f | 185 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
186 | /// assert_eq!(x.is_some(), false); |
187 | /// ``` | |
7cac9316 XL |
188 | /// |
189 | /// [`Some`]: #variant.Some | |
1a4d82fc | 190 | #[inline] |
85aaf69f | 191 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
192 | pub fn is_some(&self) -> bool { |
193 | match *self { | |
194 | Some(_) => true, | |
c1a9b12d | 195 | None => false, |
1a4d82fc JJ |
196 | } |
197 | } | |
198 | ||
7cac9316 | 199 | /// Returns `true` if the option is a [`None`] value. |
1a4d82fc | 200 | /// |
c34b1796 | 201 | /// # Examples |
1a4d82fc JJ |
202 | /// |
203 | /// ``` | |
85aaf69f | 204 | /// let x: Option<u32> = Some(2); |
1a4d82fc JJ |
205 | /// assert_eq!(x.is_none(), false); |
206 | /// | |
85aaf69f | 207 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
208 | /// assert_eq!(x.is_none(), true); |
209 | /// ``` | |
7cac9316 XL |
210 | /// |
211 | /// [`None`]: #variant.None | |
1a4d82fc | 212 | #[inline] |
85aaf69f | 213 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
214 | pub fn is_none(&self) -> bool { |
215 | !self.is_some() | |
216 | } | |
217 | ||
218 | ///////////////////////////////////////////////////////////////////////// | |
219 | // Adapter for working with references | |
220 | ///////////////////////////////////////////////////////////////////////// | |
221 | ||
9e0c209e | 222 | /// Converts from `Option<T>` to `Option<&T>`. |
1a4d82fc | 223 | /// |
c34b1796 | 224 | /// # Examples |
1a4d82fc | 225 | /// |
cc61c64b | 226 | /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original. |
9e0c209e | 227 | /// The [`map`] method takes the `self` argument by value, consuming the original, |
1a4d82fc JJ |
228 | /// so this technique uses `as_ref` to first take an `Option` to a reference |
229 | /// to the value inside the original. | |
230 | /// | |
9e0c209e | 231 | /// [`map`]: enum.Option.html#method.map |
cc61c64b XL |
232 | /// [`String`]: ../../std/string/struct.String.html |
233 | /// [`usize`]: ../../std/primitive.usize.html | |
9e0c209e | 234 | /// |
1a4d82fc JJ |
235 | /// ``` |
236 | /// let num_as_str: Option<String> = Some("10".to_string()); | |
237 | /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`, | |
238 | /// // then consume *that* with `map`, leaving `num_as_str` on the stack. | |
85aaf69f | 239 | /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len()); |
1a4d82fc JJ |
240 | /// println!("still can print num_as_str: {:?}", num_as_str); |
241 | /// ``` | |
242 | #[inline] | |
85aaf69f | 243 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 244 | pub fn as_ref(&self) -> Option<&T> { |
1a4d82fc JJ |
245 | match *self { |
246 | Some(ref x) => Some(x), | |
c1a9b12d | 247 | None => None, |
1a4d82fc JJ |
248 | } |
249 | } | |
250 | ||
9e0c209e | 251 | /// Converts from `Option<T>` to `Option<&mut T>`. |
1a4d82fc | 252 | /// |
c34b1796 | 253 | /// # Examples |
1a4d82fc JJ |
254 | /// |
255 | /// ``` | |
85aaf69f | 256 | /// let mut x = Some(2); |
1a4d82fc JJ |
257 | /// match x.as_mut() { |
258 | /// Some(v) => *v = 42, | |
259 | /// None => {}, | |
260 | /// } | |
85aaf69f | 261 | /// assert_eq!(x, Some(42)); |
1a4d82fc JJ |
262 | /// ``` |
263 | #[inline] | |
85aaf69f | 264 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 265 | pub fn as_mut(&mut self) -> Option<&mut T> { |
1a4d82fc JJ |
266 | match *self { |
267 | Some(ref mut x) => Some(x), | |
c1a9b12d | 268 | None => None, |
1a4d82fc JJ |
269 | } |
270 | } | |
271 | ||
1a4d82fc JJ |
272 | ///////////////////////////////////////////////////////////////////////// |
273 | // Getting to contained values | |
274 | ///////////////////////////////////////////////////////////////////////// | |
275 | ||
7cac9316 | 276 | /// Unwraps an option, yielding the content of a [`Some`]. |
1a4d82fc JJ |
277 | /// |
278 | /// # Panics | |
279 | /// | |
cc61c64b | 280 | /// Panics if the value is a [`None`] with a custom panic message provided by |
1a4d82fc JJ |
281 | /// `msg`. |
282 | /// | |
7cac9316 | 283 | /// [`Some`]: #variant.Some |
cc61c64b XL |
284 | /// [`None`]: #variant.None |
285 | /// | |
c34b1796 | 286 | /// # Examples |
1a4d82fc JJ |
287 | /// |
288 | /// ``` | |
289 | /// let x = Some("value"); | |
290 | /// assert_eq!(x.expect("the world is ending"), "value"); | |
291 | /// ``` | |
292 | /// | |
c34b1796 | 293 | /// ```{.should_panic} |
1a4d82fc | 294 | /// let x: Option<&str> = None; |
62682a34 | 295 | /// x.expect("the world is ending"); // panics with `the world is ending` |
1a4d82fc JJ |
296 | /// ``` |
297 | #[inline] | |
85aaf69f | 298 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
299 | pub fn expect(self, msg: &str) -> T { |
300 | match self { | |
301 | Some(val) => val, | |
7453a54e | 302 | None => expect_failed(msg), |
1a4d82fc JJ |
303 | } |
304 | } | |
305 | ||
7cac9316 | 306 | /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`]. |
1a4d82fc | 307 | /// |
1a4d82fc | 308 | /// In general, because this function may panic, its use is discouraged. |
7cac9316 | 309 | /// Instead, prefer to use pattern matching and handle the [`None`] |
1a4d82fc JJ |
310 | /// case explicitly. |
311 | /// | |
9e0c209e SL |
312 | /// # Panics |
313 | /// | |
cc61c64b XL |
314 | /// Panics if the self value equals [`None`]. |
315 | /// | |
7cac9316 | 316 | /// [`Some(v)`]: #variant.Some |
cc61c64b | 317 | /// [`None`]: #variant.None |
9e0c209e | 318 | /// |
c34b1796 | 319 | /// # Examples |
1a4d82fc JJ |
320 | /// |
321 | /// ``` | |
322 | /// let x = Some("air"); | |
323 | /// assert_eq!(x.unwrap(), "air"); | |
324 | /// ``` | |
325 | /// | |
c34b1796 | 326 | /// ```{.should_panic} |
1a4d82fc JJ |
327 | /// let x: Option<&str> = None; |
328 | /// assert_eq!(x.unwrap(), "air"); // fails | |
329 | /// ``` | |
330 | #[inline] | |
85aaf69f | 331 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
332 | pub fn unwrap(self) -> T { |
333 | match self { | |
334 | Some(val) => val, | |
335 | None => panic!("called `Option::unwrap()` on a `None` value"), | |
336 | } | |
337 | } | |
338 | ||
339 | /// Returns the contained value or a default. | |
340 | /// | |
c34b1796 | 341 | /// # Examples |
1a4d82fc JJ |
342 | /// |
343 | /// ``` | |
344 | /// assert_eq!(Some("car").unwrap_or("bike"), "car"); | |
345 | /// assert_eq!(None.unwrap_or("bike"), "bike"); | |
346 | /// ``` | |
347 | #[inline] | |
85aaf69f | 348 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
349 | pub fn unwrap_or(self, def: T) -> T { |
350 | match self { | |
351 | Some(x) => x, | |
c1a9b12d | 352 | None => def, |
1a4d82fc JJ |
353 | } |
354 | } | |
355 | ||
356 | /// Returns the contained value or computes it from a closure. | |
357 | /// | |
c34b1796 | 358 | /// # Examples |
1a4d82fc JJ |
359 | /// |
360 | /// ``` | |
c34b1796 | 361 | /// let k = 10; |
85aaf69f SL |
362 | /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); |
363 | /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); | |
1a4d82fc JJ |
364 | /// ``` |
365 | #[inline] | |
85aaf69f | 366 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
367 | pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T { |
368 | match self { | |
369 | Some(x) => x, | |
c1a9b12d | 370 | None => f(), |
1a4d82fc JJ |
371 | } |
372 | } | |
373 | ||
374 | ///////////////////////////////////////////////////////////////////////// | |
375 | // Transforming contained values | |
376 | ///////////////////////////////////////////////////////////////////////// | |
377 | ||
9e0c209e | 378 | /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value. |
1a4d82fc | 379 | /// |
c34b1796 | 380 | /// # Examples |
1a4d82fc | 381 | /// |
cc61c64b XL |
382 | /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original: |
383 | /// | |
384 | /// [`String`]: ../../std/string/struct.String.html | |
385 | /// [`usize`]: ../../std/primitive.usize.html | |
1a4d82fc JJ |
386 | /// |
387 | /// ``` | |
62682a34 SL |
388 | /// let maybe_some_string = Some(String::from("Hello, World!")); |
389 | /// // `Option::map` takes self *by value*, consuming `maybe_some_string` | |
390 | /// let maybe_some_len = maybe_some_string.map(|s| s.len()); | |
391 | /// | |
392 | /// assert_eq!(maybe_some_len, Some(13)); | |
1a4d82fc JJ |
393 | /// ``` |
394 | #[inline] | |
85aaf69f | 395 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
396 | pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> { |
397 | match self { | |
398 | Some(x) => Some(f(x)), | |
c1a9b12d | 399 | None => None, |
1a4d82fc JJ |
400 | } |
401 | } | |
402 | ||
62682a34 | 403 | /// Applies a function to the contained value (if any), |
7cac9316 XL |
404 | /// or returns a [`default`][] (if not). |
405 | /// | |
406 | /// [`default`]: ../default/trait.Default.html#tymethod.default | |
1a4d82fc | 407 | /// |
c34b1796 | 408 | /// # Examples |
1a4d82fc JJ |
409 | /// |
410 | /// ``` | |
411 | /// let x = Some("foo"); | |
85aaf69f | 412 | /// assert_eq!(x.map_or(42, |v| v.len()), 3); |
1a4d82fc JJ |
413 | /// |
414 | /// let x: Option<&str> = None; | |
85aaf69f | 415 | /// assert_eq!(x.map_or(42, |v| v.len()), 42); |
1a4d82fc JJ |
416 | /// ``` |
417 | #[inline] | |
85aaf69f | 418 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 419 | pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { |
1a4d82fc JJ |
420 | match self { |
421 | Some(t) => f(t), | |
62682a34 | 422 | None => default, |
1a4d82fc JJ |
423 | } |
424 | } | |
425 | ||
62682a34 | 426 | /// Applies a function to the contained value (if any), |
7cac9316 XL |
427 | /// or computes a [`default`][] (if not). |
428 | /// | |
429 | /// [`default`]: ../default/trait.Default.html#tymethod.default | |
1a4d82fc | 430 | /// |
c34b1796 | 431 | /// # Examples |
1a4d82fc JJ |
432 | /// |
433 | /// ``` | |
85aaf69f | 434 | /// let k = 21; |
1a4d82fc JJ |
435 | /// |
436 | /// let x = Some("foo"); | |
85aaf69f | 437 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); |
1a4d82fc JJ |
438 | /// |
439 | /// let x: Option<&str> = None; | |
85aaf69f | 440 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); |
1a4d82fc JJ |
441 | /// ``` |
442 | #[inline] | |
85aaf69f | 443 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 444 | pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { |
1a4d82fc JJ |
445 | match self { |
446 | Some(t) => f(t), | |
c1a9b12d | 447 | None => default(), |
1a4d82fc JJ |
448 | } |
449 | } | |
450 | ||
7cac9316 XL |
451 | /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to |
452 | /// [`Ok(v)`] and [`None`] to [`Err(err)`]. | |
9e0c209e SL |
453 | /// |
454 | /// [`Result<T, E>`]: ../../std/result/enum.Result.html | |
455 | /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok | |
7cac9316 XL |
456 | /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err |
457 | /// [`None`]: #variant.None | |
458 | /// [`Some(v)`]: #variant.Some | |
1a4d82fc | 459 | /// |
c34b1796 | 460 | /// # Examples |
1a4d82fc JJ |
461 | /// |
462 | /// ``` | |
463 | /// let x = Some("foo"); | |
85aaf69f | 464 | /// assert_eq!(x.ok_or(0), Ok("foo")); |
1a4d82fc JJ |
465 | /// |
466 | /// let x: Option<&str> = None; | |
85aaf69f | 467 | /// assert_eq!(x.ok_or(0), Err(0)); |
1a4d82fc JJ |
468 | /// ``` |
469 | #[inline] | |
c34b1796 | 470 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
471 | pub fn ok_or<E>(self, err: E) -> Result<T, E> { |
472 | match self { | |
473 | Some(v) => Ok(v), | |
474 | None => Err(err), | |
475 | } | |
476 | } | |
477 | ||
7cac9316 XL |
478 | /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to |
479 | /// [`Ok(v)`] and [`None`] to [`Err(err())`]. | |
9e0c209e SL |
480 | /// |
481 | /// [`Result<T, E>`]: ../../std/result/enum.Result.html | |
482 | /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok | |
7cac9316 XL |
483 | /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err |
484 | /// [`None`]: #variant.None | |
485 | /// [`Some(v)`]: #variant.Some | |
1a4d82fc | 486 | /// |
c34b1796 | 487 | /// # Examples |
1a4d82fc JJ |
488 | /// |
489 | /// ``` | |
490 | /// let x = Some("foo"); | |
85aaf69f | 491 | /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); |
1a4d82fc JJ |
492 | /// |
493 | /// let x: Option<&str> = None; | |
85aaf69f | 494 | /// assert_eq!(x.ok_or_else(|| 0), Err(0)); |
1a4d82fc JJ |
495 | /// ``` |
496 | #[inline] | |
c34b1796 | 497 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
498 | pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> { |
499 | match self { | |
500 | Some(v) => Ok(v), | |
501 | None => Err(err()), | |
502 | } | |
503 | } | |
504 | ||
505 | ///////////////////////////////////////////////////////////////////////// | |
506 | // Iterator constructors | |
507 | ///////////////////////////////////////////////////////////////////////// | |
508 | ||
509 | /// Returns an iterator over the possibly contained value. | |
510 | /// | |
c34b1796 | 511 | /// # Examples |
1a4d82fc JJ |
512 | /// |
513 | /// ``` | |
85aaf69f | 514 | /// let x = Some(4); |
1a4d82fc JJ |
515 | /// assert_eq!(x.iter().next(), Some(&4)); |
516 | /// | |
85aaf69f | 517 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
518 | /// assert_eq!(x.iter().next(), None); |
519 | /// ``` | |
520 | #[inline] | |
85aaf69f | 521 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
522 | pub fn iter(&self) -> Iter<T> { |
523 | Iter { inner: Item { opt: self.as_ref() } } | |
524 | } | |
525 | ||
526 | /// Returns a mutable iterator over the possibly contained value. | |
527 | /// | |
c34b1796 | 528 | /// # Examples |
1a4d82fc JJ |
529 | /// |
530 | /// ``` | |
85aaf69f | 531 | /// let mut x = Some(4); |
1a4d82fc | 532 | /// match x.iter_mut().next() { |
b039eaaf | 533 | /// Some(v) => *v = 42, |
1a4d82fc JJ |
534 | /// None => {}, |
535 | /// } | |
536 | /// assert_eq!(x, Some(42)); | |
537 | /// | |
85aaf69f | 538 | /// let mut x: Option<u32> = None; |
1a4d82fc JJ |
539 | /// assert_eq!(x.iter_mut().next(), None); |
540 | /// ``` | |
541 | #[inline] | |
c34b1796 | 542 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
543 | pub fn iter_mut(&mut self) -> IterMut<T> { |
544 | IterMut { inner: Item { opt: self.as_mut() } } | |
545 | } | |
546 | ||
1a4d82fc JJ |
547 | ///////////////////////////////////////////////////////////////////////// |
548 | // Boolean operations on the values, eager and lazy | |
549 | ///////////////////////////////////////////////////////////////////////// | |
550 | ||
7cac9316 XL |
551 | /// Returns [`None`] if the option is [`None`], otherwise returns `optb`. |
552 | /// | |
553 | /// [`None`]: #variant.None | |
1a4d82fc | 554 | /// |
c34b1796 | 555 | /// # Examples |
1a4d82fc JJ |
556 | /// |
557 | /// ``` | |
85aaf69f | 558 | /// let x = Some(2); |
1a4d82fc JJ |
559 | /// let y: Option<&str> = None; |
560 | /// assert_eq!(x.and(y), None); | |
561 | /// | |
85aaf69f | 562 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
563 | /// let y = Some("foo"); |
564 | /// assert_eq!(x.and(y), None); | |
565 | /// | |
85aaf69f | 566 | /// let x = Some(2); |
1a4d82fc JJ |
567 | /// let y = Some("foo"); |
568 | /// assert_eq!(x.and(y), Some("foo")); | |
569 | /// | |
85aaf69f | 570 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
571 | /// let y: Option<&str> = None; |
572 | /// assert_eq!(x.and(y), None); | |
573 | /// ``` | |
574 | #[inline] | |
85aaf69f | 575 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
576 | pub fn and<U>(self, optb: Option<U>) -> Option<U> { |
577 | match self { | |
578 | Some(_) => optb, | |
579 | None => None, | |
580 | } | |
581 | } | |
582 | ||
7cac9316 | 583 | /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the |
1a4d82fc JJ |
584 | /// wrapped value and returns the result. |
585 | /// | |
85aaf69f SL |
586 | /// Some languages call this operation flatmap. |
587 | /// | |
7cac9316 XL |
588 | /// [`None`]: #variant.None |
589 | /// | |
c34b1796 | 590 | /// # Examples |
1a4d82fc JJ |
591 | /// |
592 | /// ``` | |
85aaf69f SL |
593 | /// fn sq(x: u32) -> Option<u32> { Some(x * x) } |
594 | /// fn nope(_: u32) -> Option<u32> { None } | |
1a4d82fc JJ |
595 | /// |
596 | /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); | |
597 | /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); | |
598 | /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); | |
599 | /// assert_eq!(None.and_then(sq).and_then(sq), None); | |
600 | /// ``` | |
601 | #[inline] | |
85aaf69f | 602 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
603 | pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> { |
604 | match self { | |
605 | Some(x) => f(x), | |
606 | None => None, | |
607 | } | |
608 | } | |
609 | ||
abe05a73 XL |
610 | /// Returns `None` if the option is `None`, otherwise calls `predicate` |
611 | /// with the wrapped value and returns: | |
612 | /// | |
613 | /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped | |
614 | /// value), and | |
615 | /// - `None` if `predicate` returns `false`. | |
616 | /// | |
617 | /// This function works similar to `Iterator::filter()`. You can imagine | |
618 | /// the `Option<T>` being an iterator over one or zero elements. `filter()` | |
619 | /// lets you decide which elements to keep. | |
620 | /// | |
621 | /// # Examples | |
622 | /// | |
623 | /// ```rust | |
624 | /// #![feature(option_filter)] | |
625 | /// | |
626 | /// fn is_even(n: &i32) -> bool { | |
627 | /// n % 2 == 0 | |
628 | /// } | |
629 | /// | |
630 | /// assert_eq!(None.filter(is_even), None); | |
631 | /// assert_eq!(Some(3).filter(is_even), None); | |
632 | /// assert_eq!(Some(4).filter(is_even), Some(4)); | |
633 | /// ``` | |
634 | #[inline] | |
635 | #[unstable(feature = "option_filter", issue = "45860")] | |
636 | pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self { | |
637 | if let Some(x) = self { | |
638 | if predicate(&x) { | |
639 | return Some(x) | |
640 | } | |
641 | } | |
642 | None | |
643 | } | |
644 | ||
1a4d82fc JJ |
645 | /// Returns the option if it contains a value, otherwise returns `optb`. |
646 | /// | |
c34b1796 | 647 | /// # Examples |
1a4d82fc JJ |
648 | /// |
649 | /// ``` | |
85aaf69f | 650 | /// let x = Some(2); |
1a4d82fc | 651 | /// let y = None; |
85aaf69f | 652 | /// assert_eq!(x.or(y), Some(2)); |
1a4d82fc JJ |
653 | /// |
654 | /// let x = None; | |
85aaf69f SL |
655 | /// let y = Some(100); |
656 | /// assert_eq!(x.or(y), Some(100)); | |
1a4d82fc | 657 | /// |
85aaf69f SL |
658 | /// let x = Some(2); |
659 | /// let y = Some(100); | |
660 | /// assert_eq!(x.or(y), Some(2)); | |
1a4d82fc | 661 | /// |
85aaf69f | 662 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
663 | /// let y = None; |
664 | /// assert_eq!(x.or(y), None); | |
665 | /// ``` | |
666 | #[inline] | |
85aaf69f | 667 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
668 | pub fn or(self, optb: Option<T>) -> Option<T> { |
669 | match self { | |
670 | Some(_) => self, | |
c1a9b12d | 671 | None => optb, |
1a4d82fc JJ |
672 | } |
673 | } | |
674 | ||
675 | /// Returns the option if it contains a value, otherwise calls `f` and | |
676 | /// returns the result. | |
677 | /// | |
c34b1796 | 678 | /// # Examples |
1a4d82fc JJ |
679 | /// |
680 | /// ``` | |
681 | /// fn nobody() -> Option<&'static str> { None } | |
682 | /// fn vikings() -> Option<&'static str> { Some("vikings") } | |
683 | /// | |
684 | /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); | |
685 | /// assert_eq!(None.or_else(vikings), Some("vikings")); | |
686 | /// assert_eq!(None.or_else(nobody), None); | |
687 | /// ``` | |
688 | #[inline] | |
85aaf69f | 689 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
690 | pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> { |
691 | match self { | |
692 | Some(_) => self, | |
c1a9b12d | 693 | None => f(), |
1a4d82fc JJ |
694 | } |
695 | } | |
696 | ||
8bb4bdeb XL |
697 | ///////////////////////////////////////////////////////////////////////// |
698 | // Entry-like operations to insert if None and return a reference | |
699 | ///////////////////////////////////////////////////////////////////////// | |
700 | ||
7cac9316 | 701 | /// Inserts `v` into the option if it is [`None`], then |
8bb4bdeb XL |
702 | /// returns a mutable reference to the contained value. |
703 | /// | |
7cac9316 XL |
704 | /// [`None`]: #variant.None |
705 | /// | |
8bb4bdeb XL |
706 | /// # Examples |
707 | /// | |
708 | /// ``` | |
8bb4bdeb XL |
709 | /// let mut x = None; |
710 | /// | |
711 | /// { | |
712 | /// let y: &mut u32 = x.get_or_insert(5); | |
713 | /// assert_eq!(y, &5); | |
714 | /// | |
715 | /// *y = 7; | |
716 | /// } | |
717 | /// | |
718 | /// assert_eq!(x, Some(7)); | |
719 | /// ``` | |
720 | #[inline] | |
041b39d2 | 721 | #[stable(feature = "option_entry", since = "1.20.0")] |
8bb4bdeb XL |
722 | pub fn get_or_insert(&mut self, v: T) -> &mut T { |
723 | match *self { | |
724 | None => *self = Some(v), | |
725 | _ => (), | |
726 | } | |
727 | ||
728 | match *self { | |
729 | Some(ref mut v) => v, | |
730 | _ => unreachable!(), | |
731 | } | |
732 | } | |
733 | ||
7cac9316 | 734 | /// Inserts a value computed from `f` into the option if it is [`None`], then |
8bb4bdeb XL |
735 | /// returns a mutable reference to the contained value. |
736 | /// | |
7cac9316 XL |
737 | /// [`None`]: #variant.None |
738 | /// | |
8bb4bdeb XL |
739 | /// # Examples |
740 | /// | |
741 | /// ``` | |
8bb4bdeb XL |
742 | /// let mut x = None; |
743 | /// | |
744 | /// { | |
745 | /// let y: &mut u32 = x.get_or_insert_with(|| 5); | |
746 | /// assert_eq!(y, &5); | |
747 | /// | |
748 | /// *y = 7; | |
749 | /// } | |
750 | /// | |
751 | /// assert_eq!(x, Some(7)); | |
752 | /// ``` | |
753 | #[inline] | |
041b39d2 | 754 | #[stable(feature = "option_entry", since = "1.20.0")] |
8bb4bdeb XL |
755 | pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T { |
756 | match *self { | |
757 | None => *self = Some(f()), | |
758 | _ => (), | |
759 | } | |
760 | ||
761 | match *self { | |
762 | Some(ref mut v) => v, | |
763 | _ => unreachable!(), | |
764 | } | |
765 | } | |
766 | ||
1a4d82fc JJ |
767 | ///////////////////////////////////////////////////////////////////////// |
768 | // Misc | |
769 | ///////////////////////////////////////////////////////////////////////// | |
770 | ||
7cac9316 XL |
771 | /// Takes the value out of the option, leaving a [`None`] in its place. |
772 | /// | |
773 | /// [`None`]: #variant.None | |
1a4d82fc | 774 | /// |
c34b1796 | 775 | /// # Examples |
1a4d82fc JJ |
776 | /// |
777 | /// ``` | |
85aaf69f | 778 | /// let mut x = Some(2); |
1a4d82fc JJ |
779 | /// x.take(); |
780 | /// assert_eq!(x, None); | |
781 | /// | |
85aaf69f | 782 | /// let mut x: Option<u32> = None; |
1a4d82fc JJ |
783 | /// x.take(); |
784 | /// assert_eq!(x, None); | |
785 | /// ``` | |
786 | #[inline] | |
85aaf69f | 787 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
788 | pub fn take(&mut self) -> Option<T> { |
789 | mem::replace(self, None) | |
790 | } | |
791 | } | |
792 | ||
c34b1796 | 793 | impl<'a, T: Clone> Option<&'a T> { |
b039eaaf SL |
794 | /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the |
795 | /// option. | |
476ff2be SL |
796 | /// |
797 | /// # Examples | |
798 | /// | |
799 | /// ``` | |
800 | /// let x = 12; | |
801 | /// let opt_x = Some(&x); | |
802 | /// assert_eq!(opt_x, Some(&12)); | |
803 | /// let cloned = opt_x.cloned(); | |
804 | /// assert_eq!(cloned, Some(12)); | |
805 | /// ``` | |
c34b1796 | 806 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 807 | pub fn cloned(self) -> Option<T> { |
c34b1796 | 808 | self.map(|t| t.clone()) |
1a4d82fc JJ |
809 | } |
810 | } | |
811 | ||
ea8adc8c XL |
812 | impl<'a, T: Clone> Option<&'a mut T> { |
813 | /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the | |
814 | /// option. | |
815 | /// | |
816 | /// # Examples | |
817 | /// | |
818 | /// ``` | |
819 | /// #![feature(option_ref_mut_cloned)] | |
820 | /// let mut x = 12; | |
821 | /// let opt_x = Some(&mut x); | |
822 | /// assert_eq!(opt_x, Some(&mut 12)); | |
823 | /// let cloned = opt_x.cloned(); | |
824 | /// assert_eq!(cloned, Some(12)); | |
825 | /// ``` | |
826 | #[unstable(feature = "option_ref_mut_cloned", issue = "43738")] | |
827 | pub fn cloned(self) -> Option<T> { | |
828 | self.map(|t| t.clone()) | |
829 | } | |
830 | } | |
831 | ||
1a4d82fc JJ |
832 | impl<T: Default> Option<T> { |
833 | /// Returns the contained value or a default | |
834 | /// | |
7cac9316 XL |
835 | /// Consumes the `self` argument then, if [`Some`], returns the contained |
836 | /// value, otherwise if [`None`], returns the default value for that | |
1a4d82fc JJ |
837 | /// type. |
838 | /// | |
c34b1796 | 839 | /// # Examples |
1a4d82fc JJ |
840 | /// |
841 | /// Convert a string to an integer, turning poorly-formed strings | |
7cac9316 XL |
842 | /// into 0 (the default value for integers). [`parse`] converts |
843 | /// a string to any other type that implements [`FromStr`], returning | |
844 | /// [`None`] on error. | |
1a4d82fc JJ |
845 | /// |
846 | /// ``` | |
847 | /// let good_year_from_input = "1909"; | |
848 | /// let bad_year_from_input = "190blarg"; | |
85aaf69f SL |
849 | /// let good_year = good_year_from_input.parse().ok().unwrap_or_default(); |
850 | /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default(); | |
1a4d82fc | 851 | /// |
85aaf69f SL |
852 | /// assert_eq!(1909, good_year); |
853 | /// assert_eq!(0, bad_year); | |
1a4d82fc | 854 | /// ``` |
7cac9316 XL |
855 | /// |
856 | /// [`Some`]: #variant.Some | |
857 | /// [`None`]: #variant.None | |
858 | /// [`parse`]: ../../std/primitive.str.html#method.parse | |
859 | /// [`FromStr`]: ../../std/str/trait.FromStr.html | |
1a4d82fc | 860 | #[inline] |
85aaf69f | 861 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
862 | pub fn unwrap_or_default(self) -> T { |
863 | match self { | |
864 | Some(x) => x, | |
c1a9b12d | 865 | None => Default::default(), |
1a4d82fc JJ |
866 | } |
867 | } | |
868 | } | |
869 | ||
7453a54e SL |
870 | // This is a separate function to reduce the code size of .expect() itself. |
871 | #[inline(never)] | |
872 | #[cold] | |
873 | fn expect_failed(msg: &str) -> ! { | |
874 | panic!("{}", msg) | |
875 | } | |
876 | ||
877 | ||
1a4d82fc JJ |
878 | ///////////////////////////////////////////////////////////////////////////// |
879 | // Trait implementations | |
880 | ///////////////////////////////////////////////////////////////////////////// | |
881 | ||
85aaf69f | 882 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 883 | impl<T> Default for Option<T> { |
7cac9316 XL |
884 | /// Returns [`None`]. |
885 | /// | |
886 | /// [`None`]: #variant.None | |
1a4d82fc | 887 | #[inline] |
1a4d82fc JJ |
888 | fn default() -> Option<T> { None } |
889 | } | |
890 | ||
9346a6ac AL |
891 | #[stable(feature = "rust1", since = "1.0.0")] |
892 | impl<T> IntoIterator for Option<T> { | |
893 | type Item = T; | |
894 | type IntoIter = IntoIter<T>; | |
895 | ||
896 | /// Returns a consuming iterator over the possibly contained value. | |
897 | /// | |
898 | /// # Examples | |
899 | /// | |
900 | /// ``` | |
901 | /// let x = Some("string"); | |
902 | /// let v: Vec<&str> = x.into_iter().collect(); | |
903 | /// assert_eq!(v, ["string"]); | |
904 | /// | |
905 | /// let x = None; | |
906 | /// let v: Vec<&str> = x.into_iter().collect(); | |
907 | /// assert!(v.is_empty()); | |
908 | /// ``` | |
909 | #[inline] | |
910 | fn into_iter(self) -> IntoIter<T> { | |
911 | IntoIter { inner: Item { opt: self } } | |
912 | } | |
913 | } | |
914 | ||
e9174d1e SL |
915 | #[stable(since = "1.4.0", feature = "option_iter")] |
916 | impl<'a, T> IntoIterator for &'a Option<T> { | |
917 | type Item = &'a T; | |
918 | type IntoIter = Iter<'a, T>; | |
919 | ||
920 | fn into_iter(self) -> Iter<'a, T> { | |
921 | self.iter() | |
922 | } | |
923 | } | |
924 | ||
925 | #[stable(since = "1.4.0", feature = "option_iter")] | |
926 | impl<'a, T> IntoIterator for &'a mut Option<T> { | |
927 | type Item = &'a mut T; | |
928 | type IntoIter = IterMut<'a, T>; | |
929 | ||
3b2f2976 | 930 | fn into_iter(self) -> IterMut<'a, T> { |
e9174d1e SL |
931 | self.iter_mut() |
932 | } | |
933 | } | |
934 | ||
5bcae85e SL |
935 | #[stable(since = "1.12.0", feature = "option_from")] |
936 | impl<T> From<T> for Option<T> { | |
937 | fn from(val: T) -> Option<T> { | |
938 | Some(val) | |
939 | } | |
940 | } | |
941 | ||
1a4d82fc JJ |
942 | ///////////////////////////////////////////////////////////////////////////// |
943 | // The Option Iterators | |
944 | ///////////////////////////////////////////////////////////////////////////// | |
945 | ||
54a0048b | 946 | #[derive(Clone, Debug)] |
1a4d82fc JJ |
947 | struct Item<A> { |
948 | opt: Option<A> | |
949 | } | |
950 | ||
951 | impl<A> Iterator for Item<A> { | |
952 | type Item = A; | |
953 | ||
954 | #[inline] | |
955 | fn next(&mut self) -> Option<A> { | |
956 | self.opt.take() | |
957 | } | |
958 | ||
959 | #[inline] | |
85aaf69f | 960 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
961 | match self.opt { |
962 | Some(_) => (1, Some(1)), | |
963 | None => (0, Some(0)), | |
964 | } | |
965 | } | |
966 | } | |
967 | ||
968 | impl<A> DoubleEndedIterator for Item<A> { | |
969 | #[inline] | |
970 | fn next_back(&mut self) -> Option<A> { | |
971 | self.opt.take() | |
972 | } | |
973 | } | |
974 | ||
975 | impl<A> ExactSizeIterator for Item<A> {} | |
9e0c209e | 976 | impl<A> FusedIterator for Item<A> {} |
c30ab7b3 | 977 | unsafe impl<A> TrustedLen for Item<A> {} |
1a4d82fc | 978 | |
cc61c64b XL |
979 | /// An iterator over a reference to the [`Some`] variant of an [`Option`]. |
980 | /// | |
981 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. | |
982 | /// | |
983 | /// This `struct` is created by the [`Option::iter`] function. | |
9e0c209e SL |
984 | /// |
985 | /// [`Option`]: enum.Option.html | |
cc61c64b XL |
986 | /// [`Some`]: enum.Option.html#variant.Some |
987 | /// [`Option::iter`]: enum.Option.html#method.iter | |
85aaf69f | 988 | #[stable(feature = "rust1", since = "1.0.0")] |
54a0048b | 989 | #[derive(Debug)] |
1a4d82fc JJ |
990 | pub struct Iter<'a, A: 'a> { inner: Item<&'a A> } |
991 | ||
85aaf69f | 992 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
993 | impl<'a, A> Iterator for Iter<'a, A> { |
994 | type Item = &'a A; | |
995 | ||
996 | #[inline] | |
997 | fn next(&mut self) -> Option<&'a A> { self.inner.next() } | |
998 | #[inline] | |
85aaf69f | 999 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
1000 | } |
1001 | ||
85aaf69f | 1002 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1003 | impl<'a, A> DoubleEndedIterator for Iter<'a, A> { |
1004 | #[inline] | |
1005 | fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() } | |
1006 | } | |
1007 | ||
85aaf69f | 1008 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1009 | impl<'a, A> ExactSizeIterator for Iter<'a, A> {} |
1010 | ||
9e0c209e SL |
1011 | #[unstable(feature = "fused", issue = "35602")] |
1012 | impl<'a, A> FusedIterator for Iter<'a, A> {} | |
1013 | ||
c30ab7b3 SL |
1014 | #[unstable(feature = "trusted_len", issue = "37572")] |
1015 | unsafe impl<'a, A> TrustedLen for Iter<'a, A> {} | |
1016 | ||
85aaf69f | 1017 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1018 | impl<'a, A> Clone for Iter<'a, A> { |
1019 | fn clone(&self) -> Iter<'a, A> { | |
1020 | Iter { inner: self.inner.clone() } | |
1021 | } | |
1022 | } | |
1023 | ||
cc61c64b XL |
1024 | /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`]. |
1025 | /// | |
1026 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. | |
1027 | /// | |
1028 | /// This `struct` is created by the [`Option::iter_mut`] function. | |
9e0c209e SL |
1029 | /// |
1030 | /// [`Option`]: enum.Option.html | |
cc61c64b XL |
1031 | /// [`Some`]: enum.Option.html#variant.Some |
1032 | /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut | |
85aaf69f | 1033 | #[stable(feature = "rust1", since = "1.0.0")] |
54a0048b | 1034 | #[derive(Debug)] |
1a4d82fc JJ |
1035 | pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> } |
1036 | ||
85aaf69f | 1037 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1038 | impl<'a, A> Iterator for IterMut<'a, A> { |
1039 | type Item = &'a mut A; | |
1040 | ||
1041 | #[inline] | |
1042 | fn next(&mut self) -> Option<&'a mut A> { self.inner.next() } | |
1043 | #[inline] | |
85aaf69f | 1044 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
1045 | } |
1046 | ||
85aaf69f | 1047 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1048 | impl<'a, A> DoubleEndedIterator for IterMut<'a, A> { |
1049 | #[inline] | |
1050 | fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() } | |
1051 | } | |
1052 | ||
85aaf69f | 1053 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1054 | impl<'a, A> ExactSizeIterator for IterMut<'a, A> {} |
1055 | ||
9e0c209e SL |
1056 | #[unstable(feature = "fused", issue = "35602")] |
1057 | impl<'a, A> FusedIterator for IterMut<'a, A> {} | |
c30ab7b3 SL |
1058 | #[unstable(feature = "trusted_len", issue = "37572")] |
1059 | unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {} | |
9e0c209e | 1060 | |
cc61c64b XL |
1061 | /// An iterator over the value in [`Some`] variant of an [`Option`]. |
1062 | /// | |
1063 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. | |
1064 | /// | |
1065 | /// This `struct` is created by the [`Option::into_iter`] function. | |
9e0c209e SL |
1066 | /// |
1067 | /// [`Option`]: enum.Option.html | |
cc61c64b XL |
1068 | /// [`Some`]: enum.Option.html#variant.Some |
1069 | /// [`Option::into_iter`]: enum.Option.html#method.into_iter | |
54a0048b | 1070 | #[derive(Clone, Debug)] |
85aaf69f | 1071 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1072 | pub struct IntoIter<A> { inner: Item<A> } |
1073 | ||
85aaf69f | 1074 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1075 | impl<A> Iterator for IntoIter<A> { |
1076 | type Item = A; | |
1077 | ||
1078 | #[inline] | |
1079 | fn next(&mut self) -> Option<A> { self.inner.next() } | |
1080 | #[inline] | |
85aaf69f | 1081 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
1082 | } |
1083 | ||
85aaf69f | 1084 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1085 | impl<A> DoubleEndedIterator for IntoIter<A> { |
1086 | #[inline] | |
1087 | fn next_back(&mut self) -> Option<A> { self.inner.next_back() } | |
1088 | } | |
1089 | ||
85aaf69f | 1090 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1091 | impl<A> ExactSizeIterator for IntoIter<A> {} |
1092 | ||
9e0c209e SL |
1093 | #[unstable(feature = "fused", issue = "35602")] |
1094 | impl<A> FusedIterator for IntoIter<A> {} | |
1095 | ||
c30ab7b3 SL |
1096 | #[unstable(feature = "trusted_len", issue = "37572")] |
1097 | unsafe impl<A> TrustedLen for IntoIter<A> {} | |
1098 | ||
1a4d82fc JJ |
1099 | ///////////////////////////////////////////////////////////////////////////// |
1100 | // FromIterator | |
1101 | ///////////////////////////////////////////////////////////////////////////// | |
1102 | ||
85aaf69f | 1103 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1104 | impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { |
7cac9316 XL |
1105 | /// Takes each element in the [`Iterator`]: if it is [`None`], no further |
1106 | /// elements are taken, and the [`None`] is returned. Should no [`None`] occur, a | |
1a4d82fc JJ |
1107 | /// container with the values of each `Option` is returned. |
1108 | /// | |
1109 | /// Here is an example which increments every integer in a vector, | |
1110 | /// checking for overflow: | |
1111 | /// | |
c34b1796 | 1112 | /// ``` |
85aaf69f | 1113 | /// use std::u16; |
1a4d82fc | 1114 | /// |
c30ab7b3 | 1115 | /// let v = vec![1, 2]; |
85aaf69f SL |
1116 | /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16| |
1117 | /// if x == u16::MAX { None } | |
1a4d82fc JJ |
1118 | /// else { Some(x + 1) } |
1119 | /// ).collect(); | |
c30ab7b3 | 1120 | /// assert!(res == Some(vec![2, 3])); |
1a4d82fc | 1121 | /// ``` |
7cac9316 XL |
1122 | /// |
1123 | /// [`Iterator`]: ../iter/trait.Iterator.html | |
1124 | /// [`None`]: enum.Option.html#variant.None | |
1a4d82fc | 1125 | #[inline] |
85aaf69f | 1126 | fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> { |
1a4d82fc JJ |
1127 | // FIXME(#11084): This could be replaced with Iterator::scan when this |
1128 | // performance bug is closed. | |
1129 | ||
1130 | struct Adapter<Iter> { | |
1131 | iter: Iter, | |
1132 | found_none: bool, | |
1133 | } | |
1134 | ||
1135 | impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> { | |
1136 | type Item = T; | |
1137 | ||
1138 | #[inline] | |
1139 | fn next(&mut self) -> Option<T> { | |
1140 | match self.iter.next() { | |
1141 | Some(Some(value)) => Some(value), | |
1142 | Some(None) => { | |
1143 | self.found_none = true; | |
1144 | None | |
1145 | } | |
1146 | None => None, | |
1147 | } | |
1148 | } | |
1149 | } | |
1150 | ||
85aaf69f | 1151 | let mut adapter = Adapter { iter: iter.into_iter(), found_none: false }; |
1a4d82fc JJ |
1152 | let v: V = FromIterator::from_iter(adapter.by_ref()); |
1153 | ||
1154 | if adapter.found_none { | |
1155 | None | |
1156 | } else { | |
1157 | Some(v) | |
1158 | } | |
1159 | } | |
1160 | } | |
ea8adc8c XL |
1161 | |
1162 | /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish | |
1163 | /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can | |
1164 | /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that | |
1165 | /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result. | |
1166 | #[unstable(feature = "try_trait", issue = "42327")] | |
1167 | #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] | |
1168 | pub struct NoneError; | |
1169 | ||
1170 | #[unstable(feature = "try_trait", issue = "42327")] | |
1171 | impl<T> ops::Try for Option<T> { | |
1172 | type Ok = T; | |
1173 | type Error = NoneError; | |
1174 | ||
1175 | fn into_result(self) -> Result<T, NoneError> { | |
1176 | self.ok_or(NoneError) | |
1177 | } | |
1178 | ||
1179 | fn from_ok(v: T) -> Self { | |
1180 | Some(v) | |
1181 | } | |
1182 | ||
1183 | fn from_error(_: NoneError) -> Self { | |
1184 | None | |
1185 | } | |
1186 | } |