ref_map/option.rs
1/*
2 * option.rs
3 *
4 * ref-map - Convenience methods for references of Option and Result.
5 * Copyright (c) 2020-2021 Ammon Smith
6 *
7 * ref-map is available free of charge under the terms of the MIT
8 * License. You are free to redistribute and/or modify it under those
9 * terms. It is distributed in the hopes that it will be useful, but
10 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
11 *
12 */
13
14/// Adds the `ref_map()` extension method onto [`Option`].
15///
16/// The `ref_map()` method borrows the internal object and passes it
17/// to a closure to be mapped in some way. This allows convenient use
18/// of `as_*` type methods or calculations which require the borrowed
19/// internal value.
20///
21/// ```
22/// use ref_map::*;
23///
24/// let values = Some(vec![4, 7, 9, 5, 6]);
25///
26/// let filtered = values.ref_map(|v| &v[3..]);
27/// let answer = &[5, 6];
28///
29/// assert_eq!(filtered, Some(&answer[..]));
30/// ```
31///
32/// See the crate-level documentation for more information.
33///
34/// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
35pub trait OptionRefMap<'o, T: 'o> {
36 /// Borrows the internal value and maps it using the provided closure.
37 fn ref_map<U, F>(&'o self, f: F) -> Option<U>
38 where
39 F: FnOnce(&'o T) -> U;
40}
41
42impl<'o, T: 'o> OptionRefMap<'o, T> for Option<T> {
43 #[inline]
44 fn ref_map<U, F>(&'o self, f: F) -> Option<U>
45 where
46 F: FnOnce(&'o T) -> U,
47 {
48 match *self {
49 Some(ref x) => Some(f(x)),
50 None => None,
51 }
52 }
53}