From 2fc357bfb79fb54e5e2ed0f31596ff9be9b1f9c5 Mon Sep 17 00:00:00 2001
From: Awiteb
Date: Tue, 20 Aug 2024 11:33:14 +0000
Subject: [PATCH] chore: Clap parser to parse `Either` type
Signed-off-by: Awiteb
---
src/clap_parsers.rs | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/src/clap_parsers.rs b/src/clap_parsers.rs
index 7666505..db60083 100644
--- a/src/clap_parsers.rs
+++ b/src/clap_parsers.rs
@@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
+use std::{fmt::Display, str::FromStr};
+
+use either::Either::{self, Left, Right};
+
use crate::{LprsError, LprsResult};
/// Parse the key & value arguments.
+///
/// ## Errors
/// - If the argument value syntax not `key=value`
pub fn kv_parser(value: &str) -> LprsResult<(String, Option)> {
@@ -30,3 +35,27 @@ pub fn kv_parser(value: &str) -> LprsResult<(String, Option)> {
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(value: &str) -> LprsResult>
+where
+ L: FromStr,
+ R: FromStr,
+ ::Err: Display,
+ ::Err: Display,
+{
+ value
+ .trim()
+ .parse::()
+ .map_err(|err| LprsError::ArgParse(err.to_string()))
+ .map(Left)
+ .or_else(|_| {
+ value
+ .parse::()
+ .map_err(|err| LprsError::ArgParse(err.to_string()))
+ .map(Right)
+ })
+}