| Crates.io | clia-config-expr |
| lib.rs | clia-config-expr |
| version | 0.1.4 |
| created_at | 2025-07-04 01:19:05.227405+00 |
| updated_at | 2025-07-10 01:18:49.949267+00 |
| description | A flexible configuration expression evaluator with JSON schema support |
| homepage | |
| repository | https://github.com/clia/config-expr |
| max_upload_size | |
| id | 1737338 |
| size | 45,141 |
一个灵活的配置表达式评估器,支持JSON schema定义的规则系统。
| 操作符 | 说明 | 示例 | 备注 |
|---|---|---|---|
equals |
完全等于 | "platform" equals "RTD" |
字符串比较 |
contains |
包含 | "platform" contains "RTD" |
字符串比较 |
prefix |
前缀匹配 | "platform" prefix "Hi" |
字符串比较 |
suffix |
后缀匹配 | "platform" suffix "Pro" |
字符串比较 |
regex |
正则匹配 | "version" regex "^v\\d+\\.\\d+\\.\\d+$" |
字符串比较 |
gt |
大于 | "score" gt "80" |
数值比较 |
lt |
小于 | "age" lt "18" |
数值比较 |
ge |
大于等于 | "level" ge "5" |
数值比较 |
le |
小于等于 | "temperature" le "25.5" |
数值比较 |
[dependencies]
clia-config-expr = "0.1.1"
use clia_config_expr::{evaluate_json, validate_json};
use std::collections::HashMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 定义规则
let rules = r#"
{
"rules": [
{
"if": {
"and": [
{ "field": "platform", "op": "contains", "value": "RTD" },
{ "field": "region", "op": "equals", "value": "CN" }
]
},
"then": "chip_rtd_cn"
},
{
"if": {
"field": "platform",
"op": "prefix",
"value": "Hi"
},
"then": "chip_hi"
},
{
"if": {
"field": "score",
"op": "ge",
"value": "80"
},
"then": "high_score"
}
],
"fallback": "default_chip"
}
"#;
// 验证规则
validate_json(rules)?;
// 准备参数
let mut params = HashMap::new();
params.insert("platform".to_string(), "RTD-2000".to_string());
params.insert("region".to_string(), "CN".to_string());
// 评估规则
let result = evaluate_json(rules, ¶ms)?;
println!("结果: {:?}", result); // Some(String("chip_rtd_cn"))
Ok(())
}
{
"rules": [
{
"if": "<条件表达式>",
"then": "<返回值>"
}
],
"fallback": "<可选的默认返回值>"
}
字符串比较:
{
"field": "platform",
"op": "equals",
"value": "RTD"
}
数值比较:
{
"field": "score",
"op": "ge",
"value": "80"
}
{
"and": [
{ "field": "platform", "op": "contains", "value": "RTD" },
{ "field": "region", "op": "equals", "value": "CN" }
]
}
{
"or": [
{ "field": "platform", "op": "equals", "value": "MT9950" },
{ "field": "platform", "op": "equals", "value": "MT9638" }
]
}
{
"if": { "field": "platform", "op": "equals", "value": "RTD" },
"then": "chip_rtd"
}
{
"if": { "field": "platform", "op": "equals", "value": "RTD" },
"then": {
"chip": "rtd",
"config": {
"memory": "2GB",
"cpu": "ARM"
}
}
}
ConfigEvaluator: 配置表达式评估器ConfigRules: 规则集定义Condition: 条件表达式RuleResult: 规则结果(字符串或JSON对象)Operator: 操作符枚举evaluate_json(json, params): 直接从JSON字符串评估validate_json(json): 验证JSON规则是否合法ConfigEvaluator::from_json(json): 从JSON创建评估器evaluator.evaluate(params): 评估参数并返回结果cargo run --example basic_usage
cargo test
本项目采用 MIT 或 Apache-2.0 双重许可证。
A JSON-based configuration expression processor.