feat(stdlib): Mid M1 regex and encoding libraries
Add lib/re and lib/encoding (EN/ZH) backed by host_re_* and host_encoding_*, with golds, public demos, and design docs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
1a5ee57a6f
commit
838a2b425a
26 files changed
+702
-13
No files matched your search
+60
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
|
||||
use crate::host::{encoding, fs, json, math, net, re, sys, time, writeback, HostContext};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
#[cfg(feature = "plugin-host")]
|
||||
@@ -128,6 +128,15 @@ pub enum HostFn {
|
||||
CookieParse = 122,
|
||||
MultipartParse = 123,
|
||||
MarkdownParse = 124,
|
||||
ReIsMatch = 125,
|
||||
ReFind = 126,
|
||||
ReFindAll = 127,
|
||||
ReReplace = 128,
|
||||
ReSplit = 129,
|
||||
EncodingBase64Encode = 130,
|
||||
EncodingBase64Decode = 131,
|
||||
EncodingHexEncode = 132,
|
||||
EncodingHexDecode = 133,
|
||||
}
|
||||
|
||||
|
||||
@@ -249,6 +258,15 @@ impl HostFn {
|
||||
122 => Self::CookieParse,
|
||||
123 => Self::MultipartParse,
|
||||
124 => Self::MarkdownParse,
|
||||
125 => Self::ReIsMatch,
|
||||
126 => Self::ReFind,
|
||||
127 => Self::ReFindAll,
|
||||
128 => Self::ReReplace,
|
||||
129 => Self::ReSplit,
|
||||
130 => Self::EncodingBase64Encode,
|
||||
131 => Self::EncodingBase64Decode,
|
||||
132 => Self::EncodingHexEncode,
|
||||
133 => Self::EncodingHexDecode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -373,6 +391,15 @@ impl HostFn {
|
||||
"host_cookie_parse" | "cookie_parse" => Self::CookieParse,
|
||||
"host_multipart_parse" | "multipart_parse" => Self::MultipartParse,
|
||||
"host_markdown_parse" | "markdown_parse" => Self::MarkdownParse,
|
||||
"host_re_is_match" | "re_is_match" => Self::ReIsMatch,
|
||||
"host_re_find" | "re_find" => Self::ReFind,
|
||||
"host_re_find_all" | "re_find_all" => Self::ReFindAll,
|
||||
"host_re_replace" | "re_replace" => Self::ReReplace,
|
||||
"host_re_split" | "re_split" => Self::ReSplit,
|
||||
"host_encoding_base64_encode" | "encoding_base64_encode" => Self::EncodingBase64Encode,
|
||||
"host_encoding_base64_decode" | "encoding_base64_decode" => Self::EncodingBase64Decode,
|
||||
"host_encoding_hex_encode" | "encoding_hex_encode" => Self::EncodingHexEncode,
|
||||
"host_encoding_hex_decode" | "encoding_hex_decode" => Self::EncodingHexDecode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -484,6 +511,15 @@ impl HostFn {
|
||||
Self::CookieParse => "host_cookie_parse",
|
||||
Self::MultipartParse => "host_multipart_parse",
|
||||
Self::MarkdownParse => "host_markdown_parse",
|
||||
Self::ReIsMatch => "host_re_is_match",
|
||||
Self::ReFind => "host_re_find",
|
||||
Self::ReFindAll => "host_re_find_all",
|
||||
Self::ReReplace => "host_re_replace",
|
||||
Self::ReSplit => "host_re_split",
|
||||
Self::EncodingBase64Encode => "host_encoding_base64_encode",
|
||||
Self::EncodingBase64Decode => "host_encoding_base64_decode",
|
||||
Self::EncodingHexEncode => "host_encoding_hex_encode",
|
||||
Self::EncodingHexDecode => "host_encoding_hex_decode",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -569,6 +605,14 @@ impl HostFn {
|
||||
Self::CookieParse => &["text", "is_response"],
|
||||
Self::MultipartParse => &["body", "boundary"],
|
||||
Self::MarkdownParse => &["text"],
|
||||
Self::ReIsMatch | Self::ReFind | Self::ReFindAll | Self::ReSplit => {
|
||||
&["text", "pattern"]
|
||||
}
|
||||
Self::ReReplace => &["text", "pattern", "with"],
|
||||
Self::EncodingBase64Encode
|
||||
| Self::EncodingBase64Decode
|
||||
| Self::EncodingHexEncode
|
||||
| Self::EncodingHexDecode => &["text"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -601,6 +645,7 @@ impl HostFn {
|
||||
Self::WritebackEnsure => &["placeholder", "line"],
|
||||
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
|
||||
Self::ListSlice => &["end"],
|
||||
Self::ReReplace => &["count"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -970,6 +1015,20 @@ pub fn call_host(
|
||||
HostFn::CookieParse => net::cookie_parse(require(bound, "text")?, bound.get("is_response")),
|
||||
HostFn::MultipartParse => net::multipart_parse(require(bound, "body")?, require(bound, "boundary")?),
|
||||
HostFn::MarkdownParse => net::markdown_parse(require(bound, "text")?),
|
||||
HostFn::ReIsMatch => re::is_match(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReFind => re::find(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReFindAll => re::find_all(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReReplace => re::replace(
|
||||
require(bound, "text")?,
|
||||
require(bound, "pattern")?,
|
||||
require(bound, "with")?,
|
||||
bound.get("count"),
|
||||
),
|
||||
HostFn::ReSplit => re::split(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::EncodingBase64Encode => encoding::base64_encode(require(bound, "text")?),
|
||||
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::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Base64 / hex encoding for Mid M1 (`lib/encoding`).
|
||||
//! No third-party crates — standard alphabet + padding.
|
||||
|
||||
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} needs text")),
|
||||
}
|
||||
}
|
||||
|
||||
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
Ok(Value::Text(encode_base64(s.as_bytes())))
|
||||
}
|
||||
|
||||
pub fn base64_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let bytes = decode_base64(s)?;
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("base64_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let mut out = String::with_capacity(s.len() * 2);
|
||||
for b in s.as_bytes() {
|
||||
out.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
if s.len() % 2 != 0 {
|
||||
return Err("hex_decode: length must be even".into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(s.len() / 2);
|
||||
// Require ASCII hex digits only (byte-oriented).
|
||||
let raw = s.as_bytes();
|
||||
if raw.len() != s.len() {
|
||||
return Err("hex_decode: needs ASCII hex".into());
|
||||
}
|
||||
for i in (0..raw.len()).step_by(2) {
|
||||
let hi = from_hex(raw[i])?;
|
||||
let lo = from_hex(raw[i + 1])?;
|
||||
bytes.push((hi << 4) | lo);
|
||||
}
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("hex_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
fn from_hex(b: u8) -> Result<u8, String> {
|
||||
match b {
|
||||
b'0'..=b'9' => Ok(b - b'0'),
|
||||
b'a'..=b'f' => Ok(b - b'a' + 10),
|
||||
b'A'..=b'F' => Ok(b - b'A' + 10),
|
||||
_ => Err(format!("hex_decode: invalid digit {:?}", b as char)),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_base64(input: &[u8]) -> String {
|
||||
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= input.len() {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8) | (input[i + 2] as u32);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push(B64[(n & 63) as usize] as char);
|
||||
i += 3;
|
||||
}
|
||||
let rem = input.len() - i;
|
||||
if rem == 1 {
|
||||
let n = (input[i] as u32) << 16;
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
out.push('=');
|
||||
} else if rem == 2 {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
let raw = input.as_bytes();
|
||||
if raw.len() % 4 != 0 {
|
||||
return Err("base64_decode: length must be multiple of 4".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(raw.len() / 4 * 3);
|
||||
let mut i = 0;
|
||||
while i < raw.len() {
|
||||
let a = decode_b64_char(raw[i])?;
|
||||
let b = decode_b64_char(raw[i + 1])?;
|
||||
let c = raw[i + 2];
|
||||
let d = raw[i + 3];
|
||||
let c_val = if c == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(c)?
|
||||
};
|
||||
let d_val = if d == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(d)?
|
||||
};
|
||||
let n = (a << 18) | (b << 12) | (c_val << 6) | d_val;
|
||||
out.push(((n >> 16) & 0xff) as u8);
|
||||
if c != b'=' {
|
||||
out.push(((n >> 8) & 0xff) as u8);
|
||||
}
|
||||
if d != b'=' {
|
||||
out.push((n & 0xff) as u8);
|
||||
}
|
||||
if c == b'=' && d != b'=' {
|
||||
return Err("base64_decode: invalid padding".into());
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn decode_b64_char(b: u8) -> Result<u32, String> {
|
||||
let v = match b {
|
||||
b'A'..=b'Z' => b - b'A',
|
||||
b'a'..=b'z' => b - b'a' + 26,
|
||||
b'0'..=b'9' => b - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return Err(format!("base64_decode: invalid character {:?}", b as char)),
|
||||
};
|
||||
Ok(v as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_hello() {
|
||||
let enc = base64_encode(&Value::Text("hello".into())).unwrap();
|
||||
assert_eq!(enc, Value::Text("aGVsbG8=".into()));
|
||||
let dec = base64_decode(&enc).unwrap();
|
||||
assert_eq!(dec, Value::Text("hello".into()));
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
@@ -14,6 +15,7 @@ mod fs;
|
||||
pub(crate) mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
mod re;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
//! Regex host primitives for Mid M1 (`lib/re`).
|
||||
|
||||
use crate::value::Value;
|
||||
use regex::Regex;
|
||||
|
||||
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} needs text")),
|
||||
}
|
||||
}
|
||||
|
||||
fn compile(pattern: &str) -> Result<Regex, String> {
|
||||
Regex::new(pattern).map_err(|e| format!("invalid regex: {e}"))
|
||||
}
|
||||
|
||||
pub fn is_match(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(Value::Bool(re.is_match(t)))
|
||||
}
|
||||
|
||||
pub fn find(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(match re.find(t) {
|
||||
Some(m) => Value::Text(m.as_str().to_string()),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_all(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.find_iter(t)
|
||||
.map(|m| Value::Text(m.as_str().to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
pub fn replace(
|
||||
text: &Value,
|
||||
pattern: &Value,
|
||||
with: &Value,
|
||||
count: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let w = as_text(with, "with")?;
|
||||
let re = compile(p)?;
|
||||
let limit = match count {
|
||||
None | Some(Value::None) => None,
|
||||
Some(Value::Int(n)) => {
|
||||
if *n < 0 {
|
||||
return Err("count must be non-negative".into());
|
||||
}
|
||||
Some(*n as usize)
|
||||
}
|
||||
Some(_) => return Err("count needs int".into()),
|
||||
};
|
||||
let out = match limit {
|
||||
None => re.replace_all(t, w).into_owned(),
|
||||
Some(0) => t.to_string(),
|
||||
Some(n) => re.replacen(t, n, w).into_owned(),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn split(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.split(t)
|
||||
.map(|s| Value::Text(s.to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn match_and_find() {
|
||||
assert_eq!(
|
||||
is_match(
|
||||
&Value::Text("abc123".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Bool(true)
|
||||
);
|
||||
assert_eq!(
|
||||
find(
|
||||
&Value::Text("ab12cd34".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Text("12".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user