按审计结论清理冗余(不改变行为):
1. as_text:17 个 host 模块各自复制同一函数(两种措辞),合并为
crate::host::as_text(统一 "{label} needs text",无测试依赖旧措辞)
2. catalog.rs:extract_fm_field / extract_nested_by / extract_fm_list /
yaml_escape 与 knowledge::util 逐字相同,改为直接引用
3. view/mod.rs:handle 29 臂 + handle_debug 5 臂折叠成两张路由表
(Notebook/Debug/Action 三种处理器),每臂原本重复同一 api_debug_post 包装
实测:
- cargo build 零警告;cargo test --release 605 passed / 0 failed
- view 服务实测:GET / → 200;POST /api/debug/continue → 200(真实响应
{"error":"unknown session"});POST /api/nope → 405
行数:view/mod.rs -99(168 删 69 增);src 合计由 53,276 降至约 53,000
(as_text 18 文件各约 6 行、catalog 4 函数约 70 行)
期间发现并修正一处真实风险:路由臂分布在两个 handler(handle / handle_debug),
首次只替换了一个导致 debug 路由 405;已按 handler 分别建表并由实测覆盖。
67 lines
1.8 KiB
Rust
67 lines
1.8 KiB
Rust
//! HTML escape / unescape for Mid2 M8 (`lib/html`).
|
|
|
|
use crate::host::as_text;
|
|
use crate::value::Value;
|
|
|
|
|
|
pub fn escape(text: &Value) -> Result<Value, String> {
|
|
let s = as_text(text, "text")?;
|
|
let mut out = String::with_capacity(s.len());
|
|
for c in s.chars() {
|
|
match c {
|
|
'&' => out.push_str("&"),
|
|
'<' => out.push_str("<"),
|
|
'>' => out.push_str(">"),
|
|
'"' => out.push_str("""),
|
|
'\'' => out.push_str("'"),
|
|
_ => out.push(c),
|
|
}
|
|
}
|
|
Ok(Value::Text(out))
|
|
}
|
|
|
|
pub fn unescape(text: &Value) -> Result<Value, String> {
|
|
let s = as_text(text, "text")?;
|
|
let mut out = String::with_capacity(s.len());
|
|
let mut rest = s;
|
|
while let Some(i) = rest.find('&') {
|
|
out.push_str(&rest[..i]);
|
|
rest = &rest[i..];
|
|
if let Some(end) = rest.find(';') {
|
|
let ent = &rest[..=end];
|
|
let ch = match ent {
|
|
"&" => Some('&'),
|
|
"<" => Some('<'),
|
|
">" => Some('>'),
|
|
""" => Some('"'),
|
|
"'" | "'" | "'" => Some('\''),
|
|
_ => None,
|
|
};
|
|
if let Some(c) = ch {
|
|
out.push(c);
|
|
rest = &rest[end + 1..];
|
|
continue;
|
|
}
|
|
}
|
|
out.push('&');
|
|
rest = &rest[1..];
|
|
}
|
|
out.push_str(rest);
|
|
Ok(Value::Text(out))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn roundtrip() {
|
|
let e = escape(&Value::Text(r#"a<b>&"c'"#.into())).unwrap();
|
|
assert_eq!(
|
|
e,
|
|
Value::Text("a<b>&"c'".into())
|
|
);
|
|
assert_eq!(unescape(&e).unwrap(), Value::Text(r#"a<b>&"c'"#.into()));
|
|
}
|
|
}
|