4 releases
0.1.3 | May 11, 2021 |
---|---|
0.1.2 | Apr 5, 2021 |
0.1.1 | Apr 5, 2021 |
0.1.0 | Apr 5, 2021 |
#1695 in Text processing
23 downloads per month
Used in napchart
7KB
64 lines
noneifempty
About
Adds a trait NoneIfEmpty that converts a T to an Option by turning an empty T into None.
Usage
Add to your Cargo.toml:
[dependencies]
noneifempty = "0.1.2"
Examples
// Bring the trait into scope
use noneifempty::NoneIfEmpty;
// Converts empty strings to None
let empty_str = "";
assert_eq!(empty_str.none_if_empty(), None);
// And full strings to Some
let full_str = "hello, world!";
assert_eq!(full_str.none_if_empty(), Some("hello, world!"));
// Also works with vecs, hashmaps, hashsets, custom types...
let empty_vec: Vec<&str> = vec![];
let full_vec: Vec<&str> = vec!["hi"];
assert_eq!(empty_vec.none_if_empty(), None);
assert_eq!(full_vec.none_if_empty(), Some(vec!["hi"]));
// Automatically implemented for Option<T: NoneIfEmpty>
let no_vec: Option<Vec<&str>> = None;
let empty_vec: Option<Vec<&str>> = Some(vec![]);
let full_vec: Option<Vec<&str>> = Some(vec!["hi"]);
assert_eq!(no_vec.none_if_empty(), None);
assert_eq!(empty_vec.none_if_empty(), None);
assert_eq!(full_vec.none_if_empty(), Some(vec!["hi"]));