use crate::error::{MyError, MyResult};
use regex::{Match, Regex};
use std::num::ParseIntError;
#[derive(Clone, Default)]
pub struct RecurseDepth {
pub min_depth: Option<usize>,
pub max_depth: Option<usize>,
}
impl RecurseDepth {
pub fn from_str(value: &str) -> MyResult<Self> {
match value.parse::<usize>() {
Ok(value) => Ok(Self::from_pair(Some(1), Some(value + 1))),
Err(_) => {
let re = Regex::new("^(\\d+)?-(\\d+)?$")?;
match re.captures(value) {
Some(captures) => {
let min_depth = parse_integer(captures.get(1))?;
let max_depth = parse_integer(captures.get(2))?;
let min_depth = min_depth.map(|x| x + 1).or(Some(1));
let max_depth = max_depth.map(|x| x + 1);
Ok(Self::from_pair(min_depth, max_depth))
}
None => Err(MyError::create_clap("depth", value)),
}
}
}
}
fn from_pair(min_depth: Option<usize>, max_depth: Option<usize>) -> Self {
Self { min_depth, max_depth }
}
}
fn parse_integer(matched: Option<Match>) -> Result<Option<usize>, ParseIntError> {
match matched {
Some(m) => m.as_str().parse().map(|x| Some(x)),
None => Ok(None),
}
}