feat(stdlib): Mid2 M8 toml, html escape, and base32

Add read-only TOML subset parse, HTML escape/unescape, and RFC 4648
base32 on encoding; gold tests and public demos included.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-09 09:22:00 +08:00
1 parent 08c48f3acb
commit 435f36b6e9
24 files changed
+748 -18

No files matched your search

+31 -3
View File
@@ -3,8 +3,8 @@
use std::collections::HashMap;
use crate::host::{
cli, csv, datetime, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops,
time, url_ops, uuid_ops, writeback, HostContext,
cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, sys,
text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
@@ -186,6 +186,11 @@ pub enum HostFn {
UrlParse = 177,
UrlQueryParse = 178,
UrlQueryStringify = 179,
TomlParse = 180,
HtmlEscape = 181,
HtmlUnescape = 182,
EncodingBase32Encode = 183,
EncodingBase32Decode = 184,
}
@@ -362,6 +367,11 @@ impl HostFn {
177 => Self::UrlParse,
178 => Self::UrlQueryParse,
179 => Self::UrlQueryStringify,
180 => Self::TomlParse,
181 => Self::HtmlEscape,
182 => Self::HtmlUnescape,
183 => Self::EncodingBase32Encode,
184 => Self::EncodingBase32Decode,
_ => return None,
})
}
@@ -541,6 +551,11 @@ impl HostFn {
"host_url_parse" | "url_parse" => Self::UrlParse,
"host_url_query_parse" | "url_query_parse" => Self::UrlQueryParse,
"host_url_query_stringify" | "url_query_stringify" => Self::UrlQueryStringify,
"host_toml_parse" | "toml_parse" => Self::TomlParse,
"host_html_escape" | "html_escape" => Self::HtmlEscape,
"host_html_unescape" | "html_unescape" => Self::HtmlUnescape,
"host_encoding_base32_encode" | "encoding_base32_encode" => Self::EncodingBase32Encode,
"host_encoding_base32_decode" | "encoding_base32_decode" => Self::EncodingBase32Decode,
_ => return None,
})
}
@@ -707,6 +722,11 @@ impl HostFn {
Self::UrlParse => "host_url_parse",
Self::UrlQueryParse => "host_url_query_parse",
Self::UrlQueryStringify => "host_url_query_stringify",
Self::TomlParse => "host_toml_parse",
Self::HtmlEscape => "host_html_escape",
Self::HtmlUnescape => "host_html_unescape",
Self::EncodingBase32Encode => "host_encoding_base32_encode",
Self::EncodingBase32Decode => "host_encoding_base32_decode",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -799,7 +819,9 @@ impl HostFn {
Self::EncodingBase64Encode
| Self::EncodingBase64Decode
| Self::EncodingHexEncode
| Self::EncodingHexDecode => &["text"],
| Self::EncodingHexDecode
| Self::EncodingBase32Encode
| Self::EncodingBase32Decode => &["text"],
Self::PathJoin => &["a", "b"],
Self::PathSplit
| Self::PathFileName
@@ -838,6 +860,7 @@ impl HostFn {
Self::DatetimeInZone => &["dt", "zone"],
Self::UrlParse | Self::UrlQueryParse => &["text"],
Self::UrlQueryStringify => &["map"],
Self::TomlParse | Self::HtmlEscape | Self::HtmlUnescape => &["text"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -1263,6 +1286,11 @@ pub fn call_host(
HostFn::EncodingBase64Decode => encoding::base64_decode(require(bound, "text")?),
HostFn::EncodingHexEncode => encoding::hex_encode(require(bound, "text")?),
HostFn::EncodingHexDecode => encoding::hex_decode(require(bound, "text")?),
HostFn::EncodingBase32Encode => encoding::base32_encode(require(bound, "text")?),
HostFn::EncodingBase32Decode => encoding::base32_decode(require(bound, "text")?),
HostFn::TomlParse => toml_ops::parse(require(bound, "text")?),
HostFn::HtmlEscape => html_ops::escape(require(bound, "text")?),
HostFn::HtmlUnescape => html_ops::unescape(require(bound, "text")?),
HostFn::PathJoin => path::join(require(bound, "a")?, require(bound, "b")?),
HostFn::PathSplit => path::split(require(bound, "path")?),
HostFn::PathFileName => path::file_name(require(bound, "path")?),
+71
View File
@@ -53,6 +53,74 @@ pub fn hex_decode(text: &Value) -> Result<Value, String> {
Ok(Value::Text(out))
}
const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
pub fn base32_encode(text: &Value) -> Result<Value, String> {
let s = as_text(text, "text")?;
Ok(Value::Text(encode_base32(s.as_bytes())))
}
pub fn base32_decode(text: &Value) -> Result<Value, String> {
let s = as_text(text, "text")?;
let bytes = decode_base32(s)?;
let out = String::from_utf8(bytes).map_err(|e| format!("base32_decode: invalid utf-8: {e}"))?;
Ok(Value::Text(out))
}
fn encode_base32(input: &[u8]) -> String {
let mut out = String::new();
let mut buffer: u64 = 0;
let mut bits = 0u32;
for &b in input {
buffer = (buffer << 8) | (b as u64);
bits += 8;
while bits >= 5 {
bits -= 5;
let idx = ((buffer >> bits) & 31) as usize;
out.push(B32[idx] as char);
}
}
if bits > 0 {
let idx = ((buffer << (5 - bits)) & 31) as usize;
out.push(B32[idx] as char);
}
while out.len() % 8 != 0 {
out.push('=');
}
out
}
fn decode_base32(input: &str) -> Result<Vec<u8>, String> {
let cleaned: String = input
.chars()
.filter(|c| !c.is_whitespace())
.map(|c| c.to_ascii_uppercase())
.collect();
if cleaned.len() % 8 != 0 {
return Err("base32_decode: length must be multiple of 8".into());
}
let mut out = Vec::new();
let mut buffer: u64 = 0;
let mut bits = 0u32;
for c in cleaned.bytes() {
if c == b'=' {
break;
}
let v = match c {
b'A'..=b'Z' => c - b'A',
b'2'..=b'7' => c - b'2' + 26,
_ => return Err(format!("base32_decode: invalid character {:?}", c as char)),
} as u64;
buffer = (buffer << 5) | v;
bits += 5;
if bits >= 8 {
bits -= 8;
out.push(((buffer >> bits) & 0xff) as u8);
}
}
Ok(out)
}
fn from_hex(b: u8) -> Result<u8, String> {
match b {
b'0'..=b'9' => Ok(b - b'0'),
@@ -153,5 +221,8 @@ mod tests {
let hx = hex_encode(&Value::Text("hi".into())).unwrap();
assert_eq!(hx, Value::Text("6869".into()));
assert_eq!(hex_decode(&hx).unwrap(), Value::Text("hi".into()));
let b32 = base32_encode(&Value::Text("hello".into())).unwrap();
assert_eq!(b32, Value::Text("NBSWY3DP".into()));
assert_eq!(base32_decode(&b32).unwrap(), Value::Text("hello".into()));
}
}
+71
View File
@@ -0,0 +1,71 @@
//! HTML escape / unescape for Mid2 M8 (`lib/html`).
use crate::value::Value;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} must be text")),
}
}
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("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#x27;"),
_ => 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 {
"&amp;" => Some('&'),
"&lt;" => Some('<'),
"&gt;" => Some('>'),
"&quot;" => Some('"'),
"&#x27;" | "&#39;" | "&apos;" => 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&lt;b&gt;&amp;&quot;c&#x27;".into())
);
assert_eq!(unescape(&e).unwrap(), Value::Text(r#"a<b>&"c'"#.into()));
}
}
+3 -1
View File
@@ -16,6 +16,7 @@ pub mod event_bus;
pub mod foreign;
mod fs;
mod hash;
mod html_ops;
pub(crate) mod json;
mod log;
pub mod math;
@@ -24,6 +25,8 @@ mod path;
mod re;
mod secrets;
mod text_ops;
mod time;
mod toml_ops;
mod url_ops;
mod uuid_ops;
#[cfg(feature = "plugin-host")]
@@ -37,7 +40,6 @@ pub mod subtask;
#[path = "subtask_stub.rs"]
pub mod subtask;
mod sys;
mod time;
pub mod writeback;
pub use dispatch::{call_host, HostFn};
+340
View File
@@ -0,0 +1,340 @@
//! Minimal TOML → Marqdo Value for Mid2 M8 (`lib/toml`).
//! Subset: comments, keys, strings, ints, floats, bools, arrays of scalars,
//! `[table]` / dotted tables. No datetime, inline tables, or array-of-tables.
use crate::host::json::json_to_value;
use crate::value::Value;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} must be text")),
}
}
pub fn parse(text: &Value) -> Result<Value, String> {
let raw = as_text(text, "text")?;
let json = toml_to_json(raw)?;
json_to_value(&json)
}
fn toml_to_json(src: &str) -> Result<serde_json::Value, String> {
let mut root = serde_json::Map::new();
let mut current_path: Vec<String> = Vec::new();
for (lineno, line) in src.lines().enumerate() {
let line_no = lineno + 1;
let stripped = strip_comment(line);
let t = stripped.trim();
if t.is_empty() {
continue;
}
if t.starts_with('[') {
if !t.ends_with(']') {
return Err(format!("toml.parse:{line_no}: bad table header"));
}
if t.starts_with("[[") {
return Err(format!(
"toml.parse:{line_no}: array-of-tables [[...]] not supported"
));
}
let inner = t[1..t.len() - 1].trim();
current_path = split_dotted_keys(inner, line_no)?;
ensure_table_path(&mut root, &current_path, line_no)?;
continue;
}
let (key, val) = t
.split_once('=')
.ok_or_else(|| format!("toml.parse:{line_no}: expected key = value"))?;
let key = key.trim();
if key.is_empty() {
return Err(format!("toml.parse:{line_no}: empty key"));
}
let key_parts = split_dotted_keys(key, line_no)?;
let value = parse_value(val.trim(), line_no)?;
let parent = table_at_path(&mut root, &current_path, line_no)?;
insert_dotted(parent, &key_parts, value, line_no)?;
}
Ok(serde_json::Value::Object(root))
}
fn strip_comment(line: &str) -> String {
// Strip unquoted `#` comments.
let mut out = String::new();
let mut in_str = false;
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
if !in_str && c == '#' {
break;
}
if c == '"' {
out.push(c);
in_str = !in_str;
continue;
}
if in_str && c == '\\' {
out.push(c);
if let Some(n) = chars.next() {
out.push(n);
}
continue;
}
out.push(c);
}
out
}
fn split_dotted_keys(s: &str, line_no: usize) -> Result<Vec<String>, String> {
let mut parts = Vec::new();
let mut cur = String::new();
let mut in_quote = false;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '"' {
in_quote = !in_quote;
continue;
}
if c == '.' && !in_quote {
if cur.is_empty() {
return Err(format!("toml.parse:{line_no}: empty key segment"));
}
parts.push(std::mem::take(&mut cur));
continue;
}
cur.push(c);
}
if in_quote {
return Err(format!("toml.parse:{line_no}: unclosed quoted key"));
}
if !cur.is_empty() {
parts.push(cur);
}
if parts.is_empty() {
return Err(format!("toml.parse:{line_no}: empty path"));
}
Ok(parts)
}
fn ensure_table_path(
root: &mut serde_json::Map<String, serde_json::Value>,
path: &[String],
line_no: usize,
) -> Result<(), String> {
let mut cur = root;
for seg in path {
if !cur.contains_key(seg) {
cur.insert(seg.clone(), serde_json::Value::Object(serde_json::Map::new()));
}
cur = match cur.get_mut(seg) {
Some(serde_json::Value::Object(m)) => m,
Some(_) => {
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
}
None => unreachable!(),
};
}
Ok(())
}
fn table_at_path<'a>(
root: &'a mut serde_json::Map<String, serde_json::Value>,
path: &[String],
line_no: usize,
) -> Result<&'a mut serde_json::Map<String, serde_json::Value>, String> {
let mut cur = root;
for seg in path {
cur = match cur.get_mut(seg) {
Some(serde_json::Value::Object(m)) => m,
Some(_) => {
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
}
None => {
return Err(format!("toml.parse:{line_no}: missing table {seg}"));
}
};
}
Ok(cur)
}
fn insert_dotted(
parent: &mut serde_json::Map<String, serde_json::Value>,
parts: &[String],
value: serde_json::Value,
line_no: usize,
) -> Result<(), String> {
if parts.len() == 1 {
if parent.contains_key(&parts[0]) {
return Err(format!(
"toml.parse:{line_no}: duplicate key {}",
parts[0]
));
}
parent.insert(parts[0].clone(), value);
return Ok(());
}
let head = &parts[0];
let entry = parent
.entry(head.clone())
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
let obj = match entry {
serde_json::Value::Object(m) => m,
_ => {
return Err(format!("toml.parse:{line_no}: {head} is not a table"));
}
};
insert_dotted(obj, &parts[1..], value, line_no)
}
fn parse_value(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
if s.is_empty() {
return Err(format!("toml.parse:{line_no}: empty value"));
}
if s == "true" {
return Ok(serde_json::Value::Bool(true));
}
if s == "false" {
return Ok(serde_json::Value::Bool(false));
}
if s.starts_with('"') {
return Ok(serde_json::Value::String(parse_basic_string(s, line_no)?));
}
if s.starts_with('\'') {
return Ok(serde_json::Value::String(parse_literal_string(s, line_no)?));
}
if s.starts_with('[') {
return parse_array(s, line_no);
}
if let Ok(i) = s.replace('_', "").parse::<i64>() {
return Ok(serde_json::Value::Number(i.into()));
}
if let Ok(f) = s.replace('_', "").parse::<f64>() {
if let Some(n) = serde_json::Number::from_f64(f) {
return Ok(serde_json::Value::Number(n));
}
}
Err(format!("toml.parse:{line_no}: unsupported value {s:?}"))
}
fn parse_basic_string(s: &str, line_no: usize) -> Result<String, String> {
if !s.ends_with('"') || s.len() < 2 {
return Err(format!("toml.parse:{line_no}: bad string"));
}
let inner = &s[1..s.len() - 1];
let mut out = String::new();
let mut chars = inner.chars();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('\\') => out.push('\\'),
Some('"') => out.push('"'),
Some(other) => {
return Err(format!(
"toml.parse:{line_no}: bad escape \\{other}"
));
}
None => return Err(format!("toml.parse:{line_no}: trailing escape")),
}
} else {
out.push(c);
}
}
Ok(out)
}
fn parse_literal_string(s: &str, line_no: usize) -> Result<String, String> {
if !s.ends_with('\'') || s.len() < 2 {
return Err(format!("toml.parse:{line_no}: bad literal string"));
}
Ok(s[1..s.len() - 1].to_string())
}
fn parse_array(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
if !s.ends_with(']') {
return Err(format!("toml.parse:{line_no}: bad array"));
}
let inner = s[1..s.len() - 1].trim();
if inner.is_empty() {
return Ok(serde_json::Value::Array(vec![]));
}
let mut items = Vec::new();
let mut cur = String::new();
let mut depth = 0i32;
let mut in_str = false;
let mut str_ch = '"';
let mut chars = inner.chars().peekable();
while let Some(c) = chars.next() {
if in_str {
cur.push(c);
if c == '\\' {
if let Some(n) = chars.next() {
cur.push(n);
}
continue;
}
if c == str_ch {
in_str = false;
}
continue;
}
match c {
'"' | '\'' => {
in_str = true;
str_ch = c;
cur.push(c);
}
'[' => {
depth += 1;
cur.push(c);
}
']' => {
depth -= 1;
cur.push(c);
}
',' if depth == 0 => {
items.push(parse_value(cur.trim(), line_no)?);
cur.clear();
}
_ => cur.push(c),
}
}
if !cur.trim().is_empty() {
items.push(parse_value(cur.trim(), line_no)?);
}
Ok(serde_json::Value::Array(items))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_simple() {
let t = r#"
# comment
name = "marqdo"
count = 3
ok = true
[pkg]
version = "0.1"
"#;
let v = parse(&Value::Text(t.into())).unwrap();
let Value::Map(entries) = v else { panic!() };
let get = |k: &str| {
entries
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
.unwrap()
};
assert_eq!(get("name"), Value::Text("marqdo".into()));
assert_eq!(get("count"), Value::Int(3));
assert_eq!(get("ok"), Value::Bool(true));
let Value::Map(pkg) = get("pkg") else { panic!() };
assert_eq!(
pkg.iter().find(|(k, _)| k == "version").unwrap().1,
Value::Text("0.1".into())
);
}
}