1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
// Copyright © 2024 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use core::str::FromStr;
/// Converts a string to an `Option<T>`, where `T` implements [`FromStr`].
///
/// If the string does not represent a valid `Option<T>`, `None` is returned.
///
/// If `T` does not implement [`FromStr`], try using [`option_from_str_custom`] instead.
///
/// # Examples
/// ```
/// use malachite_base::options::option_from_str;
///
/// assert_eq!(option_from_str::<bool>("Some(false)"), Some(Some(false)));
/// assert_eq!(option_from_str::<u32>("Some(5)"), Some(Some(5)));
/// assert_eq!(option_from_str::<u32>("None"), Some(None));
/// assert_eq!(option_from_str::<u32>("Some(hi)"), None);
/// assert_eq!(option_from_str::<bool>("abc"), None);
/// ```
#[inline]
pub fn option_from_str<T: FromStr>(src: &str) -> Option<Option<T>> {
option_from_str_custom(&(|t| t.parse().ok()), src)
}
/// Converts a string to an `Option<T>`, given a function to parse a string into a `T`.
///
/// If the string does not represent a valid `Option<T>`, `None` is returned.
///
/// If `f` just uses the [`FromStr`] implementation on `T`, you can use [`option_from_str`] instead.
///
/// # Examples
/// ```
/// use malachite_base::options::{option_from_str, option_from_str_custom};
/// use malachite_base::orderings::ordering_from_str;
/// use std::cmp::Ordering::{self, *};
///
/// assert_eq!(
/// option_from_str_custom::<Ordering>(&ordering_from_str, "Some(Less)"),
/// Some(Some(Less))
/// );
/// assert_eq!(
/// option_from_str_custom::<Option<bool>>(&option_from_str, "Some(Some(false))"),
/// Some(Some(Some(false)))
/// );
/// assert_eq!(
/// option_from_str_custom::<Ordering>(&ordering_from_str, "Some(hi)"),
/// None
/// );
/// assert_eq!(
/// option_from_str_custom::<Ordering>(&ordering_from_str, "abc"),
/// None
/// );
/// ```
pub fn option_from_str_custom<T>(f: &dyn Fn(&str) -> Option<T>, src: &str) -> Option<Option<T>> {
if src == "None" {
Some(None)
} else if src.starts_with("Some(") && src.ends_with(')') {
f(&src[5..src.len() - 1]).map(Some)
} else {
None
}
}
/// Iterators that generate [`Option`]s without repetition.
pub mod exhaustive;
#[cfg(feature = "random")]
/// Iterators that generate [`Option`]s randomly.
pub mod random;