Skip to content

Commit 1e90922

Browse files
authored
Rollup merge of #144274 - Qelxiros:option-reduce, r=tgross35
add Option::reduce Tracking issue: #144273
2 parents 4f808ba + 613080b commit 1e90922

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

library/core/src/option.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1961,6 +1961,42 @@ impl<T> Option<T> {
19611961
_ => None,
19621962
}
19631963
}
1964+
1965+
/// Reduces two options into one, using the provided function if both are `Some`.
1966+
///
1967+
/// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1968+
/// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
1969+
/// If both `self` and `other` are `None`, `None` is returned.
1970+
///
1971+
/// # Examples
1972+
///
1973+
/// ```
1974+
/// #![feature(option_reduce)]
1975+
///
1976+
/// let s12 = Some(12);
1977+
/// let s17 = Some(17);
1978+
/// let n = None;
1979+
/// let f = |a, b| a + b;
1980+
///
1981+
/// assert_eq!(s12.reduce(s17, f), Some(29));
1982+
/// assert_eq!(s12.reduce(n, f), Some(12));
1983+
/// assert_eq!(n.reduce(s17, f), Some(17));
1984+
/// assert_eq!(n.reduce(n, f), None);
1985+
/// ```
1986+
#[unstable(feature = "option_reduce", issue = "144273")]
1987+
pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
1988+
where
1989+
T: Into<R>,
1990+
U: Into<R>,
1991+
F: FnOnce(T, U) -> R,
1992+
{
1993+
match (self, other) {
1994+
(Some(a), Some(b)) => Some(f(a, b)),
1995+
(Some(a), _) => Some(a.into()),
1996+
(_, Some(b)) => Some(b.into()),
1997+
_ => None,
1998+
}
1999+
}
19642000
}
19652001

19662002
impl<T, U> Option<(T, U)> {

library/coretests/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
#![feature(next_index)]
8181
#![feature(non_exhaustive_omitted_patterns_lint)]
8282
#![feature(numfmt)]
83+
#![feature(option_reduce)]
8384
#![feature(pattern)]
8485
#![feature(pointer_is_aligned_to)]
8586
#![feature(portable_simd)]

0 commit comments

Comments
 (0)