From c8841344e29435d9d419321baaa723be2aee3027 Mon Sep 17 00:00:00 2001 From: Louis Dureuil Date: Wed, 30 Nov 2022 18:17:54 +0100 Subject: [PATCH] v1: RankingRule::from_str --- dump/src/reader/v1/settings.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/dump/src/reader/v1/settings.rs b/dump/src/reader/v1/settings.rs index 0065d3f97..2f7976534 100644 --- a/dump/src/reader/v1/settings.rs +++ b/dump/src/reader/v1/settings.rs @@ -1,6 +1,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::result::Result as StdResult; +use std::str::FromStr; +use once_cell::sync::Lazy; +use regex::Regex; use serde::{Deserialize, Deserializer, Serialize}; #[derive(Default, Clone, Serialize, Deserialize, Debug)] @@ -53,6 +56,34 @@ pub enum RankingRule { Desc(String), } +static ASC_DESC_REGEX: Lazy = + Lazy::new(|| Regex::new(r#"(asc|desc)\(([\w_-]+)\)"#).unwrap()); + +impl FromStr for RankingRule { + type Err = (); + + fn from_str(s: &str) -> Result { + Ok(match s { + "typo" => Self::Typo, + "words" => Self::Words, + "proximity" => Self::Proximity, + "attribute" => Self::Attribute, + "wordsPosition" => Self::WordsPosition, + "exactness" => Self::Exactness, + text => { + let caps = ASC_DESC_REGEX.captures(text).ok_or(())?; + let order = caps.get(1).unwrap().as_str(); + let field_name = caps.get(2).unwrap().as_str(); + match order { + "asc" => Self::Asc(field_name.to_string()), + "desc" => Self::Desc(field_name.to_string()), + _ => return Err(()), + } + } + }) + } +} + // Any value that is present is considered Some value, including null. fn deserialize_some<'de, T, D>(deserializer: D) -> StdResult, D::Error> where