option_filter/
lib.rs

1#![deny(missing_docs)]
2
3//! This crate adds a `.filter()` method to `Option<T>`, for older
4//! versions of Rust that don't provide it.
5//!
6//! **Note: [`Option::filter`][std] was added to the standard library in
7//! [Rust 1.27][rust]. Unless you need to support older versions of
8//! Rust, you do not need to use this crate.**
9//!
10//! [std]: https://doc.rust-lang.org/std/option/enum.Option.html#method.filter
11//! [rust]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1270-2018-06-21
12//!
13//! To use it, add `option-filter` to your `Cargo.toml`:
14//!
15//! ```toml
16//! [dependencies]
17//! option-filter = "1.0"
18//! ```
19//!
20//! Then import the extension trait:
21//!
22//! ```rust,ignore
23//! extern crate option_filter;
24//! use option_filter::OptionFilterExt;
25//! ```
26//!
27//! Now you can filter your `Option`s!
28//!
29//! ```rust
30//! # use option_filter::OptionFilterExt;
31//! let answer = Some(42);
32//! assert_eq!(answer.filter(|x| *x == 42), Some(42));
33//! assert_eq!(answer.filter(|x| *x == 43), None);
34//! ```
35
36/// Extension trait for adding a `.filter()` method to `Option<T>`.
37///
38/// This trait is intended for extending `Option<T>` only, and should
39/// not be implemented for other types.
40pub trait OptionFilterExt {
41    /// The inner type of the `Option`.
42    ///
43    /// This is given an unwieldy name so that it's unlikely to conflict
44    /// with other associated types.
45    type OptionFilterInner;
46
47    /// Filters the element of an `Option`.
48    fn filter<F: FnOnce(&Self::OptionFilterInner) -> bool>(self, F) -> Self;
49}
50
51impl<T> OptionFilterExt for Option<T> {
52    type OptionFilterInner = T;
53    fn filter<F: FnOnce(&T) -> bool>(self, callback: F) -> Option<T> {
54        match self {
55            None => None,
56            Some(x) => if callback(&x) { Some(x) } else { None }
57        }
58    }
59}