refactor: Use Either<usize, String> type instade of String for index or name #65

Merged
awiteb merged 3 commits from awiteb/refactor-index-or-name-location into master 2024-08-20 13:44:50 +02:00 AGit
Showing only changes of commit 2fc357bfb7 - Show all commits

View file

@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>. // along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::{fmt::Display, str::FromStr};
use either::Either::{self, Left, Right};
use crate::{LprsError, LprsResult}; use crate::{LprsError, LprsResult};
/// Parse the key & value arguments. /// Parse the key & value arguments.
///
/// ## Errors /// ## Errors
/// - If the argument value syntax not `key=value` /// - If the argument value syntax not `key=value`
pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> { pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> {
@ -30,3 +35,27 @@ pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> {
Ok((value.trim().to_owned(), None)) Ok((value.trim().to_owned(), None))
} }
} }
/// Parse `Either` type arguments.
///
/// ## Errors
/// - If the argument value can't be parsed to `L` or `R`
pub fn either_parser<L, R>(value: &str) -> LprsResult<Either<L, R>>
where
L: FromStr,
R: FromStr,
<L as FromStr>::Err: Display,
<R as FromStr>::Err: Display,
{
value
.trim()
.parse::<L>()
.map_err(|err| LprsError::ArgParse(err.to_string()))
.map(Left)
.or_else(|_| {
value
.parse::<R>()
.map_err(|err| LprsError::ArgParse(err.to_string()))
.map(Right)
})
}