Как всплыть ошибка из замыкания, переданного в regex :: Regex :: replace? - PullRequest
0 голосов
/ 05 февраля 2020

У меня есть функция, которая выполняет замену строки на месте через regex::Regex::replace через замыкание, которое выполняет некоторые операции с Captures:

pub fn solve_dice_expression(expression: String) -> Result<i64, Box<dyn Error>> {
    lazy_static! {
        static ref PATTERN: Regex = Regex::new(r"(\d+)d(\d+)").expect("Problem compiling regex");
    }

    // For every match on the Dice expression regex, roll it in-place.
    let rolled_expression = PATTERN.replace(&expression, |caps: &Captures| {
        let diceroll_str = &caps.get(0).unwrap().as_str().to_string();
        let dice = Dice::from_string(&diceroll_str).unwrap();
        return format!("{}", roll_dice(&mut rng, &dice));
    });

    // Calculate the result
    let result = eval(&rolled_expression)?.as_int()?;

    return Ok(result);
}

Я пытаюсь всплыть при возврате ошибок Result<..., Box<dyn Error>>, который в основном работает через ?. Однако в закрытии, переданном в regex::Regex::replace, я не уверен, как распространять любые возможные ошибки, которые могут произойти, так как он ожидает, что закрытие вернет String, а не Result.

Что бы правильный способ обработки ошибок, происходящих в этом замыкании?

1 Ответ

1 голос
/ 05 февраля 2020

Вы не можете легко.

Что вы можете сделать, это вывести ошибку в изменяемый файл Option, а затем проверить, что после завершения замены:

use regex::{Captures, Regex}; // 1.3.3
use std::borrow::Cow;

type Error = Box<dyn std::error::Error>;
type Result<T, E = Error> = std::result::Result<T, E>;

fn example<'s>(r: &Regex, s: &'s str) -> Result<Cow<'s, str>> {
    let mut error = None;

    let v = r.replace(s, |caps: &Captures| {
        // TODO: Optimize by checking if we had an error already and exit early

        let digits = caps.get(0).unwrap().as_str();

        // Uncomment to see the failure
        // let digits = "bad";

        match digits.parse::<i32>() {
            Ok(v) => Cow::Owned((v + 1).to_string()),
            Err(e) => {
                // Save the error somewhere
                error = Some(e);
                // We are going to discard the replacement,
                // so it doesn't matter what we return
                Cow::Borrowed("")
            }
        }
    });

    match error {
        Some(e) => Err(Box::new(e)),
        None => Ok(v),
    }
}

fn main() {
    let r = Regex::new(r"\d+").unwrap();
    let v = example(&r, "1");
    println!("{:?}", v);
}

Вы также можете потенциально оптимизируйте черту Replacer для вашего собственного типа, чтобы упростить это и, возможно, немного оптимизировать его.

...