feat(stdlib): Mid M4 csv and thickened text helpers

Add lib/csv parse/stringify and expand lib/text with contains,
replace, case, pad, and related golds plus public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-07 20:27:19 +08:00
1 parent 08384c7540
commit 506de65dae
22 files changed
+766 -15

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
//! Minimal RFC4180 CSV for Mid M4 (`lib/csv`).
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")),
}
}
/// Parse CSV text into a list of maps (first row = headers).
pub fn parse(text: &Value) -> Result<Value, String> {
let s = as_text(text, "text")?;
let rows = parse_rows(s)?;
if rows.is_empty() {
return Ok(Value::List(vec![]));
}
let headers = rows[0].clone();
if headers.is_empty() {
return Err("csv.parse: header row is empty".into());
}
let mut out = Vec::new();
for row in rows.into_iter().skip(1) {
let mut map = Vec::new();
for (i, key) in headers.iter().enumerate() {
let val = row.get(i).cloned().unwrap_or_default();
map.push((key.clone(), Value::Text(val)));
}
out.push(Value::Map(map));
}
Ok(Value::List(out))
}
/// Serialize list of maps to CSV (header order = first row's keys).
pub fn stringify(rows: &Value) -> Result<Value, String> {
let list = match rows {
Value::List(xs) => xs,
_ => return Err("csv.stringify: rows needs list".into()),
};
if list.is_empty() {
return Ok(Value::Text(String::new()));
}
let first = match &list[0] {
Value::Map(m) => m,
_ => return Err("csv.stringify: each row needs map".into()),
};
let headers: Vec<String> = first.iter().map(|(k, _)| k.clone()).collect();
let mut lines = Vec::new();
lines.push(headers.iter().map(|h| escape_field(h)).collect::<Vec<_>>().join(","));
for row in list {
let map = match row {
Value::Map(m) => m,
_ => return Err("csv.stringify: each row needs map".into()),
};
let mut fields = Vec::new();
for h in &headers {
let cell = map
.iter()
.find(|(k, _)| k == h)
.map(|(_, v)| value_to_cell(v))
.unwrap_or_default();
fields.push(escape_field(&cell));
}
lines.push(fields.join(","));
}
Ok(Value::Text(lines.join("\n")))
}
fn value_to_cell(v: &Value) -> String {
match v {
Value::Text(s) => s.clone(),
Value::Int(n) => n.to_string(),
Value::Num(n) => n.to_string(),
Value::Bool(b) => {
if *b {
"True".into()
} else {
"False".into()
}
}
Value::None => String::new(),
other => other.as_display(),
}
}
fn escape_field(s: &str) -> String {
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
fn parse_rows(input: &str) -> Result<Vec<Vec<String>>, String> {
let mut rows = Vec::new();
let mut row = Vec::new();
let mut field = String::new();
let mut chars = input.chars().peekable();
let mut in_quotes = false;
while let Some(c) = chars.next() {
if in_quotes {
if c == '"' {
if chars.peek() == Some(&'"') {
chars.next();
field.push('"');
} else {
in_quotes = false;
}
} else {
field.push(c);
}
} else {
match c {
'"' => in_quotes = true,
',' => {
row.push(std::mem::take(&mut field));
}
'\r' => {
// swallow optional \n
if chars.peek() == Some(&'\n') {
chars.next();
}
row.push(std::mem::take(&mut field));
rows.push(std::mem::take(&mut row));
}
'\n' => {
row.push(std::mem::take(&mut field));
rows.push(std::mem::take(&mut row));
}
_ => field.push(c),
}
}
}
if in_quotes {
return Err("csv.parse: unterminated quote".into());
}
if !field.is_empty() || !row.is_empty() {
row.push(field);
rows.push(row);
} else if !input.is_empty() && input.ends_with('\n') {
// trailing newline already flushed last row
}
// Drop a single trailing empty row produced by final newline only when last row empty?
while rows.last().is_some_and(|r| r.len() == 1 && r[0].is_empty()) {
// only drop if it's a spurious empty line at end with no fields
if rows.len() > 1 {
rows.pop();
} else {
break;
}
}
Ok(rows)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_simple() {
let text = Value::Text("a,b\n1,2\n3,\"x,y\"\n".into());
let rows = parse(&text).unwrap();
let Value::List(ref xs) = rows else {
panic!("list");
};
assert_eq!(xs.len(), 2);
let out = stringify(&rows).unwrap();
let again = parse(&out).unwrap();
assert_eq!(again, rows);
}
}
+79 -1
View File
@@ -3,7 +3,8 @@
use std::collections::HashMap;
use crate::host::{
encoding, fs, hash, json, math, net, path, re, secrets, sys, time, writeback, HostContext,
csv, encoding, fs, hash, json, math, net, path, re, secrets, sys, text_ops, time, writeback,
HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
@@ -155,6 +156,16 @@ pub enum HostFn {
HashHmacSha256 = 147,
SecretsTokenHex = 148,
SecretsTokenUrlsafe = 149,
TextContains = 150,
TextStartsWith = 151,
TextEndsWith = 152,
TextReplace = 153,
TextToUpper = 154,
TextToLower = 155,
TextRepeat = 156,
TextPad = 157,
CsvParse = 158,
CsvStringify = 159,
}
@@ -301,6 +312,16 @@ impl HostFn {
147 => Self::HashHmacSha256,
148 => Self::SecretsTokenHex,
149 => Self::SecretsTokenUrlsafe,
150 => Self::TextContains,
151 => Self::TextStartsWith,
152 => Self::TextEndsWith,
153 => Self::TextReplace,
154 => Self::TextToUpper,
155 => Self::TextToLower,
156 => Self::TextRepeat,
157 => Self::TextPad,
158 => Self::CsvParse,
159 => Self::CsvStringify,
_ => return None,
})
}
@@ -450,6 +471,16 @@ impl HostFn {
"host_hash_hmac_sha256" | "hash_hmac_sha256" => Self::HashHmacSha256,
"host_secrets_token_hex" | "secrets_token_hex" => Self::SecretsTokenHex,
"host_secrets_token_urlsafe" | "secrets_token_urlsafe" => Self::SecretsTokenUrlsafe,
"host_text_contains" | "text_contains" => Self::TextContains,
"host_text_starts_with" | "text_starts_with" => Self::TextStartsWith,
"host_text_ends_with" | "text_ends_with" => Self::TextEndsWith,
"host_text_replace" | "text_replace" => Self::TextReplace,
"host_text_to_upper" | "text_to_upper" => Self::TextToUpper,
"host_text_to_lower" | "text_to_lower" => Self::TextToLower,
"host_text_repeat" | "text_repeat" => Self::TextRepeat,
"host_text_pad" | "text_pad" => Self::TextPad,
"host_csv_parse" | "csv_parse" => Self::CsvParse,
"host_csv_stringify" | "csv_stringify" => Self::CsvStringify,
_ => return None,
})
}
@@ -586,6 +617,16 @@ impl HostFn {
Self::HashHmacSha256 => "host_hash_hmac_sha256",
Self::SecretsTokenHex => "host_secrets_token_hex",
Self::SecretsTokenUrlsafe => "host_secrets_token_urlsafe",
Self::TextContains => "host_text_contains",
Self::TextStartsWith => "host_text_starts_with",
Self::TextEndsWith => "host_text_ends_with",
Self::TextReplace => "host_text_replace",
Self::TextToUpper => "host_text_to_upper",
Self::TextToLower => "host_text_to_lower",
Self::TextRepeat => "host_text_repeat",
Self::TextPad => "host_text_pad",
Self::CsvParse => "host_csv_parse",
Self::CsvStringify => "host_csv_stringify",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -691,6 +732,15 @@ impl HostFn {
Self::HashSha256 | Self::HashSha1 | Self::HashMd5 => &["text"],
Self::HashHmacSha256 => &["key", "text"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &[],
Self::TextContains => &["text", "sub"],
Self::TextStartsWith => &["text", "prefix"],
Self::TextEndsWith => &["text", "suffix"],
Self::TextReplace => &["text", "old", "new"],
Self::TextToUpper | Self::TextToLower => &["text"],
Self::TextRepeat => &["text", "n"],
Self::TextPad => &["text", "width"],
Self::CsvParse => &["text"],
Self::CsvStringify => &["rows"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -726,6 +776,8 @@ impl HostFn {
Self::ReReplace => &["count"],
Self::FsMakeTemp => &["prefix"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &["n"],
Self::TextReplace => &["count"],
Self::TextPad => &["fill", "align"],
_ => &[],
}
}
@@ -1129,6 +1181,32 @@ pub fn call_host(
}
HostFn::SecretsTokenHex => secrets::token_hex(bound.get("n")),
HostFn::SecretsTokenUrlsafe => secrets::token_urlsafe(bound.get("n")),
HostFn::TextContains => {
text_ops::contains(require(bound, "text")?, require(bound, "sub")?)
}
HostFn::TextStartsWith => {
text_ops::starts_with(require(bound, "text")?, require(bound, "prefix")?)
}
HostFn::TextEndsWith => {
text_ops::ends_with(require(bound, "text")?, require(bound, "suffix")?)
}
HostFn::TextReplace => text_ops::replace(
require(bound, "text")?,
require(bound, "old")?,
require(bound, "new")?,
bound.get("count"),
),
HostFn::TextToUpper => text_ops::to_upper(require(bound, "text")?),
HostFn::TextToLower => text_ops::to_lower(require(bound, "text")?),
HostFn::TextRepeat => text_ops::repeat(require(bound, "text")?, require(bound, "n")?),
HostFn::TextPad => text_ops::pad(
require(bound, "text")?,
require(bound, "width")?,
bound.get("fill"),
bound.get("align"),
),
HostFn::CsvParse => csv::parse(require(bound, "text")?),
HostFn::CsvStringify => csv::stringify(require(bound, "rows")?),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
+2
View File
@@ -7,6 +7,7 @@
pub mod agent_rt;
pub mod collection;
mod dispatch;
mod csv;
mod encoding;
pub mod event_bus;
#[cfg(feature = "exec-host")]
@@ -19,6 +20,7 @@ mod net;
mod path;
mod re;
mod secrets;
mod text_ops;
#[cfg(feature = "plugin-host")]
pub mod plugin;
#[cfg(not(feature = "plugin-host"))]
+153
View File
@@ -0,0 +1,153 @@
//! Text helpers for Mid M4 (`lib/text` thicken).
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")),
}
}
fn as_usize(v: &Value, label: &str) -> Result<usize, String> {
match v {
Value::Int(n) if *n >= 0 => Ok(*n as usize),
Value::Int(_) => Err(format!("{label} must be non-negative")),
_ => Err(format!("{label} needs int")),
}
}
pub fn contains(text: &Value, sub: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let s = as_text(sub, "sub")?;
Ok(Value::Bool(t.contains(s)))
}
pub fn starts_with(text: &Value, prefix: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let p = as_text(prefix, "prefix")?;
Ok(Value::Bool(t.starts_with(p)))
}
pub fn ends_with(text: &Value, suffix: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let s = as_text(suffix, "suffix")?;
Ok(Value::Bool(t.ends_with(s)))
}
pub fn replace(
text: &Value,
old: &Value,
new: &Value,
count: Option<&Value>,
) -> Result<Value, String> {
let t = as_text(text, "text")?;
let old = as_text(old, "old")?;
let new = as_text(new, "new")?;
if old.is_empty() {
return Err("replace: old must be non-empty".into());
}
let limit = match count {
None | Some(Value::None) => None,
Some(v) => Some(as_usize(v, "count")?),
};
let out = match limit {
None => t.replace(old, new),
Some(0) => t.to_string(),
Some(n) => {
let mut out = String::new();
let mut rest = t;
let mut done = 0usize;
while done < n {
if let Some(i) = rest.find(old) {
out.push_str(&rest[..i]);
out.push_str(new);
rest = &rest[i + old.len()..];
done += 1;
} else {
break;
}
}
out.push_str(rest);
out
}
};
Ok(Value::Text(out))
}
pub fn to_upper(text: &Value) -> Result<Value, String> {
Ok(Value::Text(as_text(text, "text")?.to_uppercase()))
}
pub fn to_lower(text: &Value) -> Result<Value, String> {
Ok(Value::Text(as_text(text, "text")?.to_lowercase()))
}
pub fn repeat(text: &Value, n: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let n = as_usize(n, "n")?;
if n > 10_000 {
return Err("repeat: n too large".into());
}
Ok(Value::Text(t.repeat(n)))
}
pub fn pad(
text: &Value,
width: &Value,
fill: Option<&Value>,
align: Option<&Value>,
) -> Result<Value, String> {
let t = as_text(text, "text")?;
let width = as_usize(width, "width")?;
let fill = match fill {
None | Some(Value::None) => " ".to_string(),
Some(v) => as_text(v, "fill")?.to_string(),
};
if fill.is_empty() {
return Err("pad: fill must be non-empty".into());
}
let align = match align {
None | Some(Value::None) => "left",
Some(v) => as_text(v, "align")?,
};
let chars: Vec<char> = t.chars().collect();
if chars.len() >= width {
return Ok(Value::Text(t.to_string()));
}
let pad_n = width - chars.len();
let fill_chars: Vec<char> = fill.chars().collect();
let make_pad = |n: usize| {
let mut s = String::new();
for i in 0..n {
s.push(fill_chars[i % fill_chars.len()]);
}
s
};
let out = match align {
"right" => format!("{}{}", make_pad(pad_n), t),
"center" => {
let left = pad_n / 2;
format!("{}{}{}", make_pad(left), t, make_pad(pad_n - left))
}
_ => format!("{}{}", t, make_pad(pad_n)),
};
Ok(Value::Text(out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_and_contains() {
assert_eq!(
contains(&Value::Text("Hello".into()), &Value::Text("ell".into())).unwrap(),
Value::Bool(true)
);
assert_eq!(
to_upper(&Value::Text("ß".into())).unwrap(),
Value::Text("SS".into())
);
}
}