Struct ConfigEvaluator

Source
pub struct ConfigEvaluator { /* private fields */ }
Expand description

配置表达式评估器

Implementations§

Source§

impl ConfigEvaluator

Source

pub fn new(rules: ConfigRules) -> Result<Self, ConfigExprError>

创建新的评估器

Source

pub fn from_json(json: &str) -> Result<Self, ConfigExprError>

从JSON字符串创建评估器

Examples found in repository?
examples/basic_usage.rs (line 108)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    // 示例1: 基本用法 - 直接从JSON字符串评估
6    println!("=== 示例1: 基本用法 ===");
7
8    let json_rules = r#"
9    {
10        "rules": [
11            {
12                "if": {
13                    "and": [
14                        { "field": "platform", "op": "contains", "value": "RTD" },
15                        { "field": "region", "op": "equals", "value": "CN" }
16                    ]
17                },
18                "then": "chip_rtd_cn"
19            },
20            {
21                "if": {
22                    "or": [
23                        { "field": "platform", "op": "equals", "value": "MT9950" },
24                        { "field": "platform", "op": "equals", "value": "MT9638" }
25                    ]
26                },
27                "then": "chip_mt"
28            },
29            {
30                "if": {
31                    "field": "platform",
32                    "op": "prefix",
33                    "value": "Hi"
34                },
35                "then": "chip_hi"
36            }
37        ],
38        "fallback": "default_chip"
39    }
40    "#;
41
42    // 验证规则是否合法
43    println!("验证规则...");
44    validate_json(json_rules)?;
45    println!("✓ 规则验证通过");
46
47    // 测试不同的参数组合
48    let test_cases = vec![
49        (
50            vec![("platform", "RTD-2000"), ("region", "CN")],
51            "应该匹配 chip_rtd_cn",
52        ),
53        (vec![("platform", "MT9950")], "应该匹配 chip_mt"),
54        (vec![("platform", "Hi3516")], "应该匹配 chip_hi"),
55        (vec![("platform", "Unknown")], "应该使用 fallback"),
56    ];
57
58    for (params_vec, description) in test_cases {
59        let mut params = HashMap::new();
60        for (key, value) in params_vec {
61            params.insert(key.to_string(), value.to_string());
62        }
63
64        let result = evaluate_json(json_rules, &params)?;
65        println!("测试: {} -> {:?}", description, result);
66    }
67
68    // 示例2: JSON对象结果
69    println!("\n=== 示例2: JSON对象结果 ===");
70
71    let json_with_object = r#"
72    {
73        "rules": [
74            {
75                "if": {
76                    "field": "platform",
77                    "op": "equals",
78                    "value": "RTD"
79                },
80                "then": {
81                    "chip": "rtd",
82                    "config": {
83                        "memory": "2GB",
84                        "cpu": "ARM",
85                        "features": ["wifi", "bluetooth"]
86                    }
87                }
88            }
89        ]
90    }
91    "#;
92
93    let mut params = HashMap::new();
94    params.insert("platform".to_string(), "RTD".to_string());
95
96    let result = evaluate_json(json_with_object, &params)?;
97    if let Some(RuleResult::Object(obj)) = result {
98        println!("匹配到JSON对象结果:");
99        println!("  chip: {}", obj["chip"]);
100        println!("  memory: {}", obj["config"]["memory"]);
101        println!("  cpu: {}", obj["config"]["cpu"]);
102        println!("  features: {:?}", obj["config"]["features"]);
103    }
104
105    // 示例3: 使用ConfigEvaluator结构体
106    println!("\n=== 示例3: 使用ConfigEvaluator ===");
107
108    let evaluator = ConfigEvaluator::from_json(json_rules)?;
109
110    let mut params = HashMap::new();
111    params.insert("platform".to_string(), "Hi3516DV300".to_string());
112
113    let result = evaluator.evaluate(&params);
114    println!("Hi3516DV300 -> {:?}", result);
115
116    // 示例4: 正则表达式匹配
117    println!("\n=== 示例4: 正则表达式匹配 ===");
118
119    let regex_rules = r#"
120    {
121        "rules": [
122            {
123                "if": {
124                    "field": "version",
125                    "op": "regex",
126                    "value": "^v\\d+\\.\\d+\\.\\d+$"
127                },
128                "then": "valid_version"
129            }
130        ],
131        "fallback": "invalid_version"
132    }
133    "#;
134
135    let test_versions = vec!["v1.2.3", "v10.0.1", "1.2.3", "v1.2"];
136
137    for version in test_versions {
138        let mut params = HashMap::new();
139        params.insert("version".to_string(), version.to_string());
140
141        let result = evaluate_json(regex_rules, &params)?;
142        println!("版本 {} -> {:?}", version, result);
143    }
144
145    // 示例5: 复杂嵌套条件
146    println!("\n=== 示例5: 复杂嵌套条件 ===");
147
148    let complex_rules = r#"
149    {
150        "rules": [
151            {
152                "if": {
153                    "and": [
154                        {
155                            "or": [
156                                { "field": "platform", "op": "prefix", "value": "Hi" },
157                                { "field": "platform", "op": "prefix", "value": "MT" }
158                            ]
159                        },
160                        { "field": "region", "op": "equals", "value": "CN" },
161                        { "field": "env", "op": "contains", "value": "prod" }
162                    ]
163                },
164                "then": {
165                    "chip_type": "cn_production",
166                    "optimization": "high"
167                }
168            }
169        ]
170    }
171    "#;
172
173    let mut params = HashMap::new();
174    params.insert("platform".to_string(), "Hi3516".to_string());
175    params.insert("region".to_string(), "CN".to_string());
176    params.insert("env".to_string(), "production".to_string());
177
178    let result = evaluate_json(complex_rules, &params)?;
179    println!("复杂条件匹配结果: {:?}", result);
180
181    // 示例6: 数值比较操作符
182    println!("\n=== 示例6: 数值比较操作符 ===");
183
184    let numeric_rules = r#"
185    {
186        "rules": [
187            {
188                "if": {
189                    "field": "score",
190                    "op": "ge",
191                    "value": "90"
192                },
193                "then": "excellent"
194            },
195            {
196                "if": {
197                    "field": "score",
198                    "op": "ge",
199                    "value": "80"
200                },
201                "then": "good"
202            },
203            {
204                "if": {
205                    "field": "score",
206                    "op": "ge",
207                    "value": "60"
208                },
209                "then": "pass"
210            }
211        ],
212        "fallback": "fail"
213    }
214    "#;
215
216    let test_scores = vec!["95", "85", "75", "50", "not_a_number"];
217
218    for score in test_scores {
219        let mut params = HashMap::new();
220        params.insert("score".to_string(), score.to_string());
221
222        let result = evaluate_json(numeric_rules, &params)?;
223        println!("分数 {} -> {:?}", score, result);
224    }
225
226    // 示例7: 混合条件(字符串和数值)
227    println!("\n=== 示例7: 混合条件 ===");
228
229    let mixed_rules = r#"
230    {
231        "rules": [
232            {
233                "if": {
234                    "and": [
235                        { "field": "category", "op": "equals", "value": "premium" },
236                        { "field": "price", "op": "gt", "value": "100.0" },
237                        { "field": "rating", "op": "ge", "value": "4.5" }
238                    ]
239                },
240                "then": {
241                    "tier": "premium",
242                    "discount": 0.1,
243                    "features": ["priority_support", "advanced_analytics"]
244                }
245            },
246            {
247                "if": {
248                    "and": [
249                        { "field": "category", "op": "equals", "value": "standard" },
250                        { "field": "price", "op": "le", "value": "50.0" }
251                    ]
252                },
253                "then": {
254                    "tier": "standard",
255                    "discount": 0.05
256                }
257            }
258        ]
259    }
260    "#;
261
262    let mut params = HashMap::new();
263    params.insert("category".to_string(), "premium".to_string());
264    params.insert("price".to_string(), "150.99".to_string());
265    params.insert("rating".to_string(), "4.8".to_string());
266
267    let result = evaluate_json(mixed_rules, &params)?;
268    println!("混合条件匹配结果: {:?}", result);
269
270    Ok(())
271}
Source

pub fn evaluate(&self, params: &HashMap<String, String>) -> Option<RuleResult>

评估请求参数,返回匹配的结果

Examples found in repository?
examples/basic_usage.rs (line 113)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    // 示例1: 基本用法 - 直接从JSON字符串评估
6    println!("=== 示例1: 基本用法 ===");
7
8    let json_rules = r#"
9    {
10        "rules": [
11            {
12                "if": {
13                    "and": [
14                        { "field": "platform", "op": "contains", "value": "RTD" },
15                        { "field": "region", "op": "equals", "value": "CN" }
16                    ]
17                },
18                "then": "chip_rtd_cn"
19            },
20            {
21                "if": {
22                    "or": [
23                        { "field": "platform", "op": "equals", "value": "MT9950" },
24                        { "field": "platform", "op": "equals", "value": "MT9638" }
25                    ]
26                },
27                "then": "chip_mt"
28            },
29            {
30                "if": {
31                    "field": "platform",
32                    "op": "prefix",
33                    "value": "Hi"
34                },
35                "then": "chip_hi"
36            }
37        ],
38        "fallback": "default_chip"
39    }
40    "#;
41
42    // 验证规则是否合法
43    println!("验证规则...");
44    validate_json(json_rules)?;
45    println!("✓ 规则验证通过");
46
47    // 测试不同的参数组合
48    let test_cases = vec![
49        (
50            vec![("platform", "RTD-2000"), ("region", "CN")],
51            "应该匹配 chip_rtd_cn",
52        ),
53        (vec![("platform", "MT9950")], "应该匹配 chip_mt"),
54        (vec![("platform", "Hi3516")], "应该匹配 chip_hi"),
55        (vec![("platform", "Unknown")], "应该使用 fallback"),
56    ];
57
58    for (params_vec, description) in test_cases {
59        let mut params = HashMap::new();
60        for (key, value) in params_vec {
61            params.insert(key.to_string(), value.to_string());
62        }
63
64        let result = evaluate_json(json_rules, &params)?;
65        println!("测试: {} -> {:?}", description, result);
66    }
67
68    // 示例2: JSON对象结果
69    println!("\n=== 示例2: JSON对象结果 ===");
70
71    let json_with_object = r#"
72    {
73        "rules": [
74            {
75                "if": {
76                    "field": "platform",
77                    "op": "equals",
78                    "value": "RTD"
79                },
80                "then": {
81                    "chip": "rtd",
82                    "config": {
83                        "memory": "2GB",
84                        "cpu": "ARM",
85                        "features": ["wifi", "bluetooth"]
86                    }
87                }
88            }
89        ]
90    }
91    "#;
92
93    let mut params = HashMap::new();
94    params.insert("platform".to_string(), "RTD".to_string());
95
96    let result = evaluate_json(json_with_object, &params)?;
97    if let Some(RuleResult::Object(obj)) = result {
98        println!("匹配到JSON对象结果:");
99        println!("  chip: {}", obj["chip"]);
100        println!("  memory: {}", obj["config"]["memory"]);
101        println!("  cpu: {}", obj["config"]["cpu"]);
102        println!("  features: {:?}", obj["config"]["features"]);
103    }
104
105    // 示例3: 使用ConfigEvaluator结构体
106    println!("\n=== 示例3: 使用ConfigEvaluator ===");
107
108    let evaluator = ConfigEvaluator::from_json(json_rules)?;
109
110    let mut params = HashMap::new();
111    params.insert("platform".to_string(), "Hi3516DV300".to_string());
112
113    let result = evaluator.evaluate(&params);
114    println!("Hi3516DV300 -> {:?}", result);
115
116    // 示例4: 正则表达式匹配
117    println!("\n=== 示例4: 正则表达式匹配 ===");
118
119    let regex_rules = r#"
120    {
121        "rules": [
122            {
123                "if": {
124                    "field": "version",
125                    "op": "regex",
126                    "value": "^v\\d+\\.\\d+\\.\\d+$"
127                },
128                "then": "valid_version"
129            }
130        ],
131        "fallback": "invalid_version"
132    }
133    "#;
134
135    let test_versions = vec!["v1.2.3", "v10.0.1", "1.2.3", "v1.2"];
136
137    for version in test_versions {
138        let mut params = HashMap::new();
139        params.insert("version".to_string(), version.to_string());
140
141        let result = evaluate_json(regex_rules, &params)?;
142        println!("版本 {} -> {:?}", version, result);
143    }
144
145    // 示例5: 复杂嵌套条件
146    println!("\n=== 示例5: 复杂嵌套条件 ===");
147
148    let complex_rules = r#"
149    {
150        "rules": [
151            {
152                "if": {
153                    "and": [
154                        {
155                            "or": [
156                                { "field": "platform", "op": "prefix", "value": "Hi" },
157                                { "field": "platform", "op": "prefix", "value": "MT" }
158                            ]
159                        },
160                        { "field": "region", "op": "equals", "value": "CN" },
161                        { "field": "env", "op": "contains", "value": "prod" }
162                    ]
163                },
164                "then": {
165                    "chip_type": "cn_production",
166                    "optimization": "high"
167                }
168            }
169        ]
170    }
171    "#;
172
173    let mut params = HashMap::new();
174    params.insert("platform".to_string(), "Hi3516".to_string());
175    params.insert("region".to_string(), "CN".to_string());
176    params.insert("env".to_string(), "production".to_string());
177
178    let result = evaluate_json(complex_rules, &params)?;
179    println!("复杂条件匹配结果: {:?}", result);
180
181    // 示例6: 数值比较操作符
182    println!("\n=== 示例6: 数值比较操作符 ===");
183
184    let numeric_rules = r#"
185    {
186        "rules": [
187            {
188                "if": {
189                    "field": "score",
190                    "op": "ge",
191                    "value": "90"
192                },
193                "then": "excellent"
194            },
195            {
196                "if": {
197                    "field": "score",
198                    "op": "ge",
199                    "value": "80"
200                },
201                "then": "good"
202            },
203            {
204                "if": {
205                    "field": "score",
206                    "op": "ge",
207                    "value": "60"
208                },
209                "then": "pass"
210            }
211        ],
212        "fallback": "fail"
213    }
214    "#;
215
216    let test_scores = vec!["95", "85", "75", "50", "not_a_number"];
217
218    for score in test_scores {
219        let mut params = HashMap::new();
220        params.insert("score".to_string(), score.to_string());
221
222        let result = evaluate_json(numeric_rules, &params)?;
223        println!("分数 {} -> {:?}", score, result);
224    }
225
226    // 示例7: 混合条件(字符串和数值)
227    println!("\n=== 示例7: 混合条件 ===");
228
229    let mixed_rules = r#"
230    {
231        "rules": [
232            {
233                "if": {
234                    "and": [
235                        { "field": "category", "op": "equals", "value": "premium" },
236                        { "field": "price", "op": "gt", "value": "100.0" },
237                        { "field": "rating", "op": "ge", "value": "4.5" }
238                    ]
239                },
240                "then": {
241                    "tier": "premium",
242                    "discount": 0.1,
243                    "features": ["priority_support", "advanced_analytics"]
244                }
245            },
246            {
247                "if": {
248                    "and": [
249                        { "field": "category", "op": "equals", "value": "standard" },
250                        { "field": "price", "op": "le", "value": "50.0" }
251                    ]
252                },
253                "then": {
254                    "tier": "standard",
255                    "discount": 0.05
256                }
257            }
258        ]
259    }
260    "#;
261
262    let mut params = HashMap::new();
263    params.insert("category".to_string(), "premium".to_string());
264    params.insert("price".to_string(), "150.99".to_string());
265    params.insert("rating".to_string(), "4.8".to_string());
266
267    let result = evaluate_json(mixed_rules, &params)?;
268    println!("混合条件匹配结果: {:?}", result);
269
270    Ok(())
271}

Trait Implementations§

Source§

impl Clone for ConfigEvaluator

Source§

fn clone(&self) -> ConfigEvaluator

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConfigEvaluator

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ConfigEvaluator

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for ConfigEvaluator

Source§

fn eq(&self, other: &ConfigEvaluator) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for ConfigEvaluator

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ConfigEvaluator

Source§

impl StructuralPartialEq for ConfigEvaluator

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,