feat(stdlib): Mid2 M7 datetime and url
Add calendar moments as {unix,zone,iso} maps and URL/query parse
helpers in lib/ with thin host_* forwards; gold and public demos.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ff1870cedc
commit
08c48f3acb
23 files changed
+1002
-15
No files matched your search
@@ -0,0 +1,302 @@
|
||||
//! Calendar / timezone subset for Mid2 M7 (`lib/datetime`).
|
||||
//!
|
||||
//! Moments are plain maps: `{unix, zone, iso}`. Zone is a fixed offset (`+08:00`)
|
||||
//! or alias (`UTC`); a few fixed-offset IANA names are accepted. Full tzdb is out of scope.
|
||||
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
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")),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_i64(v: Option<&Value>, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(0),
|
||||
Some(x) => as_i64(x, label),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_offset(off: FixedOffset) -> String {
|
||||
let secs = off.local_minus_utc();
|
||||
let sign = if secs >= 0 { '+' } else { '-' };
|
||||
let abs = secs.abs();
|
||||
let h = abs / 3600;
|
||||
let m = (abs % 3600) / 60;
|
||||
format!("{sign}{h:02}:{m:02}")
|
||||
}
|
||||
|
||||
fn parse_zone(s: &str) -> Result<FixedOffset, String> {
|
||||
let s = s.trim();
|
||||
if s.is_empty() || s.eq_ignore_ascii_case("utc") || s.eq_ignore_ascii_case("gmt") || s == "Z" {
|
||||
return FixedOffset::east_opt(0).ok_or_else(|| "invalid UTC offset".into());
|
||||
}
|
||||
// Common fixed-offset IANA aliases (no DST).
|
||||
let aliased = match s {
|
||||
"Asia/Shanghai" | "Asia/Hong_Kong" | "Asia/Taipei" | "Asia/Singapore" => Some(8 * 3600),
|
||||
"Asia/Tokyo" | "Asia/Seoul" => Some(9 * 3600),
|
||||
"Asia/Kolkata" | "Asia/Calcutta" => Some(5 * 3600 + 30 * 60),
|
||||
"Europe/Moscow" => Some(3 * 3600),
|
||||
"America/Phoenix" => Some(-7 * 3600),
|
||||
"Pacific/Honolulu" => Some(-10 * 3600),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(secs) = aliased {
|
||||
return FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone: {s}"));
|
||||
}
|
||||
let (sign, rest) = if let Some(r) = s.strip_prefix('+') {
|
||||
(1i32, r)
|
||||
} else if let Some(r) = s.strip_prefix('-') {
|
||||
(-1i32, r)
|
||||
} else {
|
||||
return Err(format!(
|
||||
"unknown zone {s:?}; use +HH:MM / -HH:MM / UTC or a fixed-offset alias (e.g. Asia/Shanghai)"
|
||||
));
|
||||
};
|
||||
let (hh, mm) = if let Some((h, m)) = rest.split_once(':') {
|
||||
(
|
||||
h.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
m.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone minute in {s}"))?,
|
||||
)
|
||||
} else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
(
|
||||
rest[..2]
|
||||
.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
rest[2..]
|
||||
.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone minute in {s}"))?,
|
||||
)
|
||||
} else if rest.len() == 2 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
(
|
||||
rest.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
0,
|
||||
)
|
||||
} else {
|
||||
return Err(format!("bad zone offset {s}"));
|
||||
};
|
||||
if !(0..=14).contains(&hh) || !(0..60).contains(&mm) {
|
||||
return Err(format!("zone offset out of range: {s}"));
|
||||
}
|
||||
let secs = sign * (hh * 3600 + mm * 60);
|
||||
FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone offset: {s}"))
|
||||
}
|
||||
|
||||
fn moment(unix: i64, zone: FixedOffset) -> Result<Value, String> {
|
||||
let dt = zone
|
||||
.timestamp_opt(unix, 0)
|
||||
.single()
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {unix}"))?;
|
||||
Ok(Value::Map(vec![
|
||||
("unix".into(), Value::Int(unix)),
|
||||
("zone".into(), Value::Text(format_offset(zone))),
|
||||
(
|
||||
"iso".into(),
|
||||
Value::Text(dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
|
||||
),
|
||||
]))
|
||||
}
|
||||
|
||||
fn zone_of_moment(m: &[(String, Value)]) -> Result<FixedOffset, String> {
|
||||
for (k, v) in m {
|
||||
if k == "zone" {
|
||||
return parse_zone(as_text(v, "zone")?);
|
||||
}
|
||||
}
|
||||
Ok(FixedOffset::east_opt(0).unwrap())
|
||||
}
|
||||
|
||||
fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok((*n, FixedOffset::east_opt(0).unwrap())),
|
||||
Value::Map(entries) => {
|
||||
let mut unix = None;
|
||||
for (k, val) in entries {
|
||||
if k == "unix" {
|
||||
unix = Some(as_i64(val, "unix")?);
|
||||
}
|
||||
}
|
||||
let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?;
|
||||
Ok((unix, zone_of_moment(entries)?))
|
||||
}
|
||||
Value::Text(s) => {
|
||||
// Treat bare ISO/RFC3339 text as a moment.
|
||||
let parsed = parse_text(s, None)?;
|
||||
unix_of_value(&parsed)
|
||||
}
|
||||
_ => Err("datetime needs int unix, moment map, or ISO text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now() -> Result<Value, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err("datetime.now unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let secs = Utc::now().timestamp();
|
||||
moment(secs, FixedOffset::east_opt(0).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
let off = match zone {
|
||||
None | Some(Value::None) => FixedOffset::east_opt(0).unwrap(),
|
||||
Some(z) => parse_zone(as_text(z, "zone")?)?,
|
||||
};
|
||||
moment(secs, off)
|
||||
}
|
||||
|
||||
pub fn to_unix(dt: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
Ok(Value::Int(secs))
|
||||
}
|
||||
|
||||
fn parse_text(text: &str, pattern: Option<&str>) -> Result<Value, String> {
|
||||
if let Some(pat) = pattern {
|
||||
if pat.eq_ignore_ascii_case("rfc3339") || pat.eq_ignore_ascii_case("iso") {
|
||||
return parse_rfc3339(text);
|
||||
}
|
||||
if let Ok(dt) = DateTime::parse_from_str(text, pat) {
|
||||
return moment(dt.timestamp(), *dt.offset());
|
||||
}
|
||||
let naive = NaiveDateTime::parse_from_str(text, pat)
|
||||
.or_else(|_| {
|
||||
NaiveDate::parse_from_str(text, pat).map(|d| d.and_hms_opt(0, 0, 0).unwrap())
|
||||
})
|
||||
.map_err(|e| format!("datetime.parse: {e}"))?;
|
||||
return moment(naive.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(v) = parse_rfc3339(text) {
|
||||
return Ok(v);
|
||||
}
|
||||
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S") {
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S") {
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(d) = NaiveDate::parse_from_str(text, "%Y-%m-%d") {
|
||||
let dt = d.and_hms_opt(0, 0, 0).unwrap();
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
Err(format!(
|
||||
"datetime.parse: unrecognized {text:?}; pass pattern= or use RFC3339 / YYYY-MM-DD"
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_rfc3339(text: &str) -> Result<Value, String> {
|
||||
let dt = DateTime::parse_from_rfc3339(text).map_err(|e| format!("datetime.parse: {e}"))?;
|
||||
moment(dt.timestamp(), *dt.offset())
|
||||
}
|
||||
|
||||
pub fn parse(text: &Value, pattern: Option<&Value>) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let pat = match pattern {
|
||||
None | Some(Value::None) => None,
|
||||
Some(p) => Some(as_text(p, "pattern")?),
|
||||
};
|
||||
parse_text(t, pat)
|
||||
}
|
||||
|
||||
pub fn format(dt: &Value, style: Option<&Value>) -> Result<Value, String> {
|
||||
let (secs, zone) = unix_of_value(dt)?;
|
||||
let local = zone
|
||||
.timestamp_opt(secs, 0)
|
||||
.single()
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
|
||||
let style = match style {
|
||||
None | Some(Value::None) => "rfc3339",
|
||||
Some(s) => as_text(s, "style")?,
|
||||
};
|
||||
let out = match style {
|
||||
"rfc3339" | "iso" => local.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
"date" => local.format("%Y-%m-%d").to_string(),
|
||||
"time" => local.format("%H:%M:%S").to_string(),
|
||||
other => local.format(other).to_string(),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn add(
|
||||
dt: &Value,
|
||||
days: Option<&Value>,
|
||||
hours: Option<&Value>,
|
||||
minutes: Option<&Value>,
|
||||
seconds: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let (secs, zone) = unix_of_value(dt)?;
|
||||
let days = optional_i64(days, "days")?;
|
||||
let hours = optional_i64(hours, "hours")?;
|
||||
let minutes = optional_i64(minutes, "minutes")?;
|
||||
let seconds = optional_i64(seconds, "seconds")?;
|
||||
let delta = Duration::days(days)
|
||||
+ Duration::hours(hours)
|
||||
+ Duration::minutes(minutes)
|
||||
+ Duration::seconds(seconds);
|
||||
let new_secs = secs
|
||||
.checked_add(delta.num_seconds())
|
||||
.ok_or_else(|| "datetime.add overflow".to_string())?;
|
||||
moment(new_secs, zone)
|
||||
}
|
||||
|
||||
pub fn in_zone(dt: &Value, zone: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
let off = parse_zone(as_text(zone, "zone")?)?;
|
||||
moment(secs, off)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn from_unix_utc_iso() {
|
||||
let m = from_unix(&Value::Int(0), None).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
|
||||
assert_eq!(iso, Value::Text("1970-01-01T00:00:00Z".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shanghai_alias() {
|
||||
let m = from_unix(&Value::Int(0), Some(&Value::Text("Asia/Shanghai".into()))).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
|
||||
assert_eq!(iso, Value::Text("1970-01-01T08:00:00+08:00".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rfc3339_roundtrip() {
|
||||
let m = parse(
|
||||
&Value::Text("2020-01-02T03:04:05+08:00".into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let u = to_unix(&m).unwrap();
|
||||
assert_eq!(u, Value::Int(1_577_905_445));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_day() {
|
||||
let m = from_unix(&Value::Int(0), None).unwrap();
|
||||
let n = add(&m, Some(&Value::Int(1)), None, None, None).unwrap();
|
||||
assert_eq!(to_unix(&n).unwrap(), Value::Int(86_400));
|
||||
}
|
||||
}
|
||||
+75
-2
@@ -3,8 +3,8 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{
|
||||
cli, csv, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops, time,
|
||||
uuid_ops, writeback, HostContext,
|
||||
cli, csv, datetime, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops,
|
||||
time, url_ops, uuid_ops, writeback, HostContext,
|
||||
};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
@@ -176,6 +176,16 @@ pub enum HostFn {
|
||||
LogSetLevel = 167,
|
||||
LogLine = 168,
|
||||
UuidV4 = 169,
|
||||
DatetimeNow = 170,
|
||||
DatetimeFromUnix = 171,
|
||||
DatetimeToUnix = 172,
|
||||
DatetimeParse = 173,
|
||||
DatetimeFormat = 174,
|
||||
DatetimeAdd = 175,
|
||||
DatetimeInZone = 176,
|
||||
UrlParse = 177,
|
||||
UrlQueryParse = 178,
|
||||
UrlQueryStringify = 179,
|
||||
}
|
||||
|
||||
|
||||
@@ -342,6 +352,16 @@ impl HostFn {
|
||||
167 => Self::LogSetLevel,
|
||||
168 => Self::LogLine,
|
||||
169 => Self::UuidV4,
|
||||
170 => Self::DatetimeNow,
|
||||
171 => Self::DatetimeFromUnix,
|
||||
172 => Self::DatetimeToUnix,
|
||||
173 => Self::DatetimeParse,
|
||||
174 => Self::DatetimeFormat,
|
||||
175 => Self::DatetimeAdd,
|
||||
176 => Self::DatetimeInZone,
|
||||
177 => Self::UrlParse,
|
||||
178 => Self::UrlQueryParse,
|
||||
179 => Self::UrlQueryStringify,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -511,6 +531,16 @@ impl HostFn {
|
||||
"host_log_set_level" | "log_set_level" => Self::LogSetLevel,
|
||||
"host_log_line" | "log_line" => Self::LogLine,
|
||||
"host_uuid_v4" | "uuid_v4" => Self::UuidV4,
|
||||
"host_datetime_now" | "datetime_now" => Self::DatetimeNow,
|
||||
"host_datetime_from_unix" | "datetime_from_unix" => Self::DatetimeFromUnix,
|
||||
"host_datetime_to_unix" | "datetime_to_unix" => Self::DatetimeToUnix,
|
||||
"host_datetime_parse" | "datetime_parse" => Self::DatetimeParse,
|
||||
"host_datetime_format" | "datetime_format" => Self::DatetimeFormat,
|
||||
"host_datetime_add" | "datetime_add" => Self::DatetimeAdd,
|
||||
"host_datetime_in_zone" | "datetime_in_zone" => Self::DatetimeInZone,
|
||||
"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,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -667,6 +697,16 @@ impl HostFn {
|
||||
Self::LogSetLevel => "host_log_set_level",
|
||||
Self::LogLine => "host_log_line",
|
||||
Self::UuidV4 => "host_uuid_v4",
|
||||
Self::DatetimeNow => "host_datetime_now",
|
||||
Self::DatetimeFromUnix => "host_datetime_from_unix",
|
||||
Self::DatetimeToUnix => "host_datetime_to_unix",
|
||||
Self::DatetimeParse => "host_datetime_parse",
|
||||
Self::DatetimeFormat => "host_datetime_format",
|
||||
Self::DatetimeAdd => "host_datetime_add",
|
||||
Self::DatetimeInZone => "host_datetime_in_zone",
|
||||
Self::UrlParse => "host_url_parse",
|
||||
Self::UrlQueryParse => "host_url_query_parse",
|
||||
Self::UrlQueryStringify => "host_url_query_stringify",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -789,6 +829,15 @@ impl HostFn {
|
||||
Self::LogSetLevel => &["level"],
|
||||
Self::LogLine => &["level", "text"],
|
||||
Self::UuidV4 => &[],
|
||||
Self::DatetimeNow => &[],
|
||||
Self::DatetimeFromUnix => &["unix"],
|
||||
Self::DatetimeToUnix => &["dt"],
|
||||
Self::DatetimeParse => &["text"],
|
||||
Self::DatetimeFormat => &["dt"],
|
||||
Self::DatetimeAdd => &["dt"],
|
||||
Self::DatetimeInZone => &["dt", "zone"],
|
||||
Self::UrlParse | Self::UrlQueryParse => &["text"],
|
||||
Self::UrlQueryStringify => &["map"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -827,6 +876,10 @@ impl HostFn {
|
||||
Self::TextReplace => &["count"],
|
||||
Self::TextPad => &["fill", "align"],
|
||||
Self::CliParse => &["args"],
|
||||
Self::DatetimeFromUnix => &["zone"],
|
||||
Self::DatetimeParse => &["pattern"],
|
||||
Self::DatetimeFormat => &["style"],
|
||||
Self::DatetimeAdd => &["days", "hours", "minutes", "seconds"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -1272,6 +1325,26 @@ pub fn call_host(
|
||||
HostFn::LogSetLevel => log::set_level(ctx, require(bound, "level")?),
|
||||
HostFn::LogLine => log::line(ctx, require(bound, "level")?, require(bound, "text")?),
|
||||
HostFn::UuidV4 => uuid_ops::v4(),
|
||||
HostFn::DatetimeNow => datetime::now(),
|
||||
HostFn::DatetimeFromUnix => {
|
||||
datetime::from_unix(require(bound, "unix")?, bound.get("zone"))
|
||||
}
|
||||
HostFn::DatetimeToUnix => datetime::to_unix(require(bound, "dt")?),
|
||||
HostFn::DatetimeParse => datetime::parse(require(bound, "text")?, bound.get("pattern")),
|
||||
HostFn::DatetimeFormat => datetime::format(require(bound, "dt")?, bound.get("style")),
|
||||
HostFn::DatetimeAdd => datetime::add(
|
||||
require(bound, "dt")?,
|
||||
bound.get("days"),
|
||||
bound.get("hours"),
|
||||
bound.get("minutes"),
|
||||
bound.get("seconds"),
|
||||
),
|
||||
HostFn::DatetimeInZone => {
|
||||
datetime::in_zone(require(bound, "dt")?, require(bound, "zone")?)
|
||||
}
|
||||
HostFn::UrlParse => url_ops::parse(require(bound, "text")?),
|
||||
HostFn::UrlQueryParse => url_ops::query_parse(require(bound, "text")?),
|
||||
HostFn::UrlQueryStringify => url_ops::query_stringify(require(bound, "map")?),
|
||||
HostFn::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod collection;
|
||||
mod dispatch;
|
||||
mod cli;
|
||||
mod csv;
|
||||
mod datetime;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
@@ -23,6 +24,7 @@ mod path;
|
||||
mod re;
|
||||
mod secrets;
|
||||
mod text_ops;
|
||||
mod url_ops;
|
||||
mod uuid_ops;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! URL parse / query helpers for Mid2 M7 (`lib/url`).
|
||||
//! Distinct from `net::url_encode` (single-segment form encoding).
|
||||
//! Hand-rolled subset (no `url` crate): scheme://[userinfo@]host[:port]/path[?query][#frag].
|
||||
|
||||
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")),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_component(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(b as char);
|
||||
}
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_component(s: &str) -> Result<String, String> {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
}
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
let h = |c: u8| -> Result<u8, String> {
|
||||
match c {
|
||||
b'0'..=b'9' => Ok(c - b'0'),
|
||||
b'a'..=b'f' => Ok(c - b'a' + 10),
|
||||
b'A'..=b'F' => Ok(c - b'A' + 10),
|
||||
_ => Err(format!("bad percent escape in {s:?}")),
|
||||
}
|
||||
};
|
||||
let v = (h(bytes[i + 1])? << 4) | h(bytes[i + 2])?;
|
||||
out.push(v);
|
||||
i += 3;
|
||||
}
|
||||
b'%' => return Err(format!("truncated percent escape in {s:?}")),
|
||||
c => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).map_err(|e| format!("url decode utf8: {e}"))
|
||||
}
|
||||
|
||||
/// Parse `scheme://[userinfo@]host[:port]/path[?query][#fragment]`.
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let (scheme, rest) = raw
|
||||
.split_once("://")
|
||||
.ok_or_else(|| format!("url.parse: missing :// in {raw:?}"))?;
|
||||
if scheme.is_empty()
|
||||
|| !scheme
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
|
||||
{
|
||||
return Err(format!("url.parse: bad scheme in {raw:?}"));
|
||||
}
|
||||
|
||||
let (before_frag, fragment) = match rest.split_once('#') {
|
||||
Some((a, b)) => (a, b),
|
||||
None => (rest, ""),
|
||||
};
|
||||
let (before_query, query) = match before_frag.split_once('?') {
|
||||
Some((a, b)) => (a, b),
|
||||
None => (before_frag, ""),
|
||||
};
|
||||
|
||||
let (authority, path) = if let Some(i) = before_query.find('/') {
|
||||
(&before_query[..i], &before_query[i..])
|
||||
} else {
|
||||
(before_query, "")
|
||||
};
|
||||
|
||||
let (userinfo, hostport) = if let Some((u, h)) = authority.rsplit_once('@') {
|
||||
(u, h)
|
||||
} else {
|
||||
("", authority)
|
||||
};
|
||||
|
||||
let (host, port) = if hostport.starts_with('[') {
|
||||
// IPv6 literal [addr]:port
|
||||
let end = hostport
|
||||
.find(']')
|
||||
.ok_or_else(|| format!("url.parse: bad IPv6 host in {raw:?}"))?;
|
||||
let host = &hostport[1..end];
|
||||
let rest = &hostport[end + 1..];
|
||||
if rest.is_empty() {
|
||||
(host, Value::None)
|
||||
} else if let Some(p) = rest.strip_prefix(':') {
|
||||
let n: i64 = p
|
||||
.parse()
|
||||
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
|
||||
(host, Value::Int(n))
|
||||
} else {
|
||||
return Err(format!("url.parse: bad hostport in {raw:?}"));
|
||||
}
|
||||
} else if let Some((h, p)) = hostport.rsplit_once(':') {
|
||||
if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() {
|
||||
let n: i64 = p
|
||||
.parse()
|
||||
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
|
||||
(h, Value::Int(n))
|
||||
} else {
|
||||
(hostport, Value::None)
|
||||
}
|
||||
} else {
|
||||
(hostport, Value::None)
|
||||
};
|
||||
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
path.to_string()
|
||||
};
|
||||
|
||||
Ok(Value::Map(vec![
|
||||
("scheme".into(), Value::Text(scheme.to_string())),
|
||||
("userinfo".into(), Value::Text(userinfo.to_string())),
|
||||
("host".into(), Value::Text(host.to_string())),
|
||||
("port".into(), port),
|
||||
("path".into(), Value::Text(path)),
|
||||
("query".into(), Value::Text(query.to_string())),
|
||||
("fragment".into(), Value::Text(fragment.to_string())),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn query_parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let raw = raw.strip_prefix('?').unwrap_or(raw);
|
||||
let mut map: Vec<(String, Value)> = Vec::new();
|
||||
if raw.is_empty() {
|
||||
return Ok(Value::Map(map));
|
||||
}
|
||||
for pair in raw.split('&') {
|
||||
if pair.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (k, v) = match pair.split_once('=') {
|
||||
Some((k, v)) => (k, v),
|
||||
None => (pair, ""),
|
||||
};
|
||||
let key = decode_component(k)?;
|
||||
let val = Value::Text(decode_component(v)?);
|
||||
if let Some((_, slot)) = map.iter_mut().find(|(kk, _)| *kk == key) {
|
||||
match slot {
|
||||
Value::List(xs) => xs.push(val),
|
||||
other => {
|
||||
let prev = std::mem::replace(other, Value::None);
|
||||
*other = Value::List(vec![prev, val]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
map.push((key, val));
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
pub fn query_stringify(map: &Value) -> Result<Value, String> {
|
||||
let entries = match map {
|
||||
Value::Map(m) => m,
|
||||
Value::None => return Ok(Value::Text(String::new())),
|
||||
_ => return Err("url.query_stringify: map required".into()),
|
||||
};
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for (k, v) in entries {
|
||||
let key = encode_component(k);
|
||||
match v {
|
||||
Value::List(xs) => {
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::Text(s) => {
|
||||
parts.push(format!("{key}={}", encode_component(s)));
|
||||
}
|
||||
Value::Int(n) => {
|
||||
parts.push(format!("{key}={}", encode_component(&n.to_string())));
|
||||
}
|
||||
Value::Bool(b) => {
|
||||
parts.push(format!("{key}={}", encode_component(&b.to_string())));
|
||||
}
|
||||
Value::None => parts.push(format!("{key}=")),
|
||||
_ => {
|
||||
return Err("url.query_stringify: list values must be scalar".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Text(s) => parts.push(format!("{key}={}", encode_component(s))),
|
||||
Value::Int(n) => parts.push(format!("{key}={}", encode_component(&n.to_string()))),
|
||||
Value::Bool(b) => parts.push(format!("{key}={}", encode_component(&b.to_string()))),
|
||||
Value::None => parts.push(format!("{key}=")),
|
||||
_ => return Err("url.query_stringify: values must be scalar or list".into()),
|
||||
}
|
||||
}
|
||||
Ok(Value::Text(parts.join("&")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_https_query() {
|
||||
let m = parse(&Value::Text(
|
||||
"https://user:pass@example.com:8443/a/b?x=1&y=2#frag".into(),
|
||||
))
|
||||
.unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let get = |k: &str| {
|
||||
entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(get("scheme"), Value::Text("https".into()));
|
||||
assert_eq!(get("host"), Value::Text("example.com".into()));
|
||||
assert_eq!(get("port"), Value::Int(8443));
|
||||
assert_eq!(get("path"), Value::Text("/a/b".into()));
|
||||
assert_eq!(get("query"), Value::Text("x=1&y=2".into()));
|
||||
assert_eq!(get("fragment"), Value::Text("frag".into()));
|
||||
assert_eq!(get("userinfo"), Value::Text("user:pass".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_roundtrip() {
|
||||
let q = query_parse(&Value::Text("a=1&b=hello%20w&a=2".into())).unwrap();
|
||||
let s = query_stringify(&q).unwrap();
|
||||
assert_eq!(s, Value::Text("a=1&a=2&b=hello%20w".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_path_becomes_slash() {
|
||||
let m = parse(&Value::Text("https://example.com".into())).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let path = entries.iter().find(|(k, _)| k == "path").unwrap().1.clone();
|
||||
assert_eq!(path, Value::Text("/".into()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user