1use serde_json::{Map, Value, json};
6
7use crate::TypeDesc;
8
9#[cfg(test)]
10mod tests;
11
12pub const MAX_PARAMS_BYTES: usize = 64 * 1024;
14
15const TAGS: [&str; 5] = ["$datetime", "$date", "$timedelta", "$tuple", "$dict"];
17
18const DAY_MICROS: i128 = 86_400_000_000;
20
21pub fn to_stored(value: &Value, ty: &TypeDesc) -> Result<Value, Misfit> {
29 checked(value, ty, Form::Given)
30}
31
32pub fn to_reported(value: &Value, ty: &TypeDesc) -> Result<Value, Misfit> {
40 checked(value, ty, Form::Whole)
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45enum Form {
46 Given,
48 Whole,
50}
51
52fn checked(value: &Value, ty: &TypeDesc, form: Form) -> Result<Value, Misfit> {
53 let result = match nul_at(value) {
54 Some(at) => Err((at, "text containing NUL (\\0) can't be stored".to_owned())),
55 None => stored(value, ty, form),
56 };
57 result.map_err(|(path, why)| Misfit { path, why })
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Misfit {
63 pub path: Vec<Step>,
66 pub why: String,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Step {
73 Key(String),
75 Index(usize),
77}
78
79impl Misfit {
80 pub fn fields(&self) -> impl Iterator<Item = &str> {
82 self.path.iter().filter_map(|step| match step {
83 Step::Key(key) => Some(key.as_str()),
84 Step::Index(_) => None,
85 })
86 }
87
88 #[must_use]
90 pub fn at(&self) -> String {
91 let mut at = String::new();
92 for step in &self.path {
93 match step {
94 Step::Key(key) => {
95 if !at.is_empty() {
96 at.push('.');
97 }
98 at.push_str(key);
99 }
100 Step::Index(i) => {
101 at.push('[');
102 at.push_str(&i.to_string());
103 at.push(']');
104 }
105 }
106 }
107 at
108 }
109}
110
111impl std::fmt::Display for Misfit {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 if self.path.is_empty() {
114 f.write_str(&self.why)
115 } else {
116 write!(f, "`{}`: {}", self.at(), self.why)
117 }
118 }
119}
120
121impl std::error::Error for Misfit {}
122
123type Problem = (Vec<Step>, String);
125
126fn misfit(why: impl Into<String>) -> Problem {
127 (Vec::new(), why.into())
128}
129
130#[must_use]
133pub fn nul_at(value: &Value) -> Option<Vec<Step>> {
134 match value {
135 Value::String(text) if text.contains('\0') => Some(Vec::new()),
136 Value::Array(items) => items.iter().enumerate().find_map(|(i, v)| {
137 nul_at(v).map(|mut path| {
138 path.insert(0, Step::Index(i));
139 path
140 })
141 }),
142 Value::Object(object) => object.iter().find_map(|(k, v)| {
143 if k.contains('\0') {
144 return Some(Vec::new());
146 }
147 nul_at(v).map(|mut path| {
148 path.insert(0, Step::Key(k.clone()));
149 path
150 })
151 }),
152 _ => None,
153 }
154}
155
156fn stored(value: &Value, ty: &TypeDesc, form: Form) -> Result<Value, Problem> {
157 match ty {
158 TypeDesc::Any | TypeDesc::Model { .. } => Ok(escape_tags(value)),
159 TypeDesc::None if value.is_null() => Ok(Value::Null),
160 TypeDesc::Bool if value.is_boolean() => Ok(value.clone()),
161 TypeDesc::Int if value.is_i64() || value.is_u64() => Ok(value.clone()),
162 TypeDesc::Int if let Some(number) = whole(value) => Ok(Value::from(number)),
164 TypeDesc::Float if value.is_number() => Ok(value.clone()),
165 TypeDesc::Str if value.is_string() => Ok(value.clone()),
166 TypeDesc::Datetime => text(value, "a date and time").and_then(|t| {
167 t.parse::<jiff::Timestamp>()
168 .map_err(|_| misfit("not a date and time with an offset (RFC 3339)"))
169 .and_then(|_| python_year(t))
170 .map(|()| json!({"$datetime": t}))
171 }),
172 TypeDesc::Date => text(value, "a date").and_then(|t| {
173 t.parse::<jiff::civil::Date>()
174 .map_err(|_| misfit("not a date (YYYY-MM-DD)"))
175 .and_then(|_| python_year(t))
176 .map(|()| json!({"$date": t}))
177 }),
178 TypeDesc::Timedelta => text(value, "a duration").and_then(|t| {
179 duration_micros(t)
180 .map(|micros| json!({"$timedelta": micros}))
181 .map_err(misfit)
182 }),
183 TypeDesc::List { item } => {
184 let items = array(value)?;
185 Ok(Value::Array(elements(items, |_| item, form)?))
186 }
187 TypeDesc::Tuple { items: types } => {
188 let items = array(value)?;
189 if items.len() != types.len() {
190 return Err(misfit(format!(
191 "expected {} elements, got {}",
192 types.len(),
193 items.len()
194 )));
195 }
196 Ok(json!({"$tuple": elements(items, |i| &types[i], form)?}))
197 }
198 TypeDesc::Dict { value: item } => {
199 let object = object(value)?;
200 let mut out = Map::new();
201 for (key, v) in object {
202 out.insert(
203 key.clone(),
204 within(stored(v, item, form), Step::Key(key.clone()))?,
205 );
206 }
207 Ok(escaped(out))
208 }
209 TypeDesc::Literal { values } if values.contains(value) => Ok(value.clone()),
210 TypeDesc::Union { variants } => variants
213 .iter()
214 .filter(|v| !matches!(v, TypeDesc::Any | TypeDesc::Model { .. }))
215 .chain(
216 variants
217 .iter()
218 .filter(|v| matches!(v, TypeDesc::Any | TypeDesc::Model { .. })),
219 )
220 .find_map(|v| stored(value, v, form).ok())
221 .ok_or_else(|| misfit(format!("{} fits none of its types", kind_of(value)))),
222 TypeDesc::TypedDict { fields, .. } | TypeDesc::Dataclass { fields, .. } => {
223 let object = object(value)?;
224 let mut out = Map::new();
225 for (key, v) in object {
226 let field = fields
227 .iter()
228 .find(|f| &f.name == key)
229 .ok_or_else(|| misfit(format!("unknown field `{key}`")))?;
230 out.insert(
231 key.clone(),
232 within(stored(v, &field.ty, form), Step::Key(key.clone()))?,
233 );
234 }
235 let whole = form == Form::Whole && matches!(ty, TypeDesc::Dataclass { .. });
236 if let Some(missing) = fields
237 .iter()
238 .find(|f| (f.required || whole) && !out.contains_key(&f.name))
239 {
240 return Err(misfit(format!("`{}` is required", missing.name)));
241 }
242 Ok(escaped(out))
243 }
244 TypeDesc::ProcessResult => Err(misfit("a command's result can't be a parameter")),
245 TypeDesc::None
246 | TypeDesc::Bool
247 | TypeDesc::Int
248 | TypeDesc::Float
249 | TypeDesc::Str
250 | TypeDesc::Literal { .. } => Err(misfit(format!(
251 "expected {}, got {}",
252 expected(ty),
253 kind_of(value)
254 ))),
255 }
256}
257
258fn python_year(text: &str) -> Result<(), Problem> {
261 let year = text
262 .get(..4)
263 .filter(|y| y.bytes().all(|b| b.is_ascii_digit()))
264 .and_then(|y| y.parse::<u16>().ok());
265 match year {
266 Some(1..=9999) if text.as_bytes().get(4) == Some(&b'-') => Ok(()),
267 _ => Err(misfit(
268 "a year Python can't read: four digits, 0001 to 9999",
269 )),
270 }
271}
272
273fn whole(value: &Value) -> Option<i64> {
275 const EXACT: f64 = 9_007_199_254_740_992.0;
277 let number = value.as_f64().filter(|n| n.fract() == 0.0)?;
278 #[expect(
279 clippy::cast_possible_truncation,
280 reason = "a whole number, checked in range"
281 )]
282 (-EXACT..=EXACT).contains(&number).then_some(number as i64)
283}
284
285fn within(result: Result<Value, Problem>, step: Step) -> Result<Value, Problem> {
286 result.map_err(|(mut path, why)| {
287 path.insert(0, step);
288 (path, why)
289 })
290}
291
292fn elements<'t>(
293 items: &[Value],
294 ty: impl Fn(usize) -> &'t TypeDesc,
295 form: Form,
296) -> Result<Vec<Value>, Problem> {
297 items
298 .iter()
299 .enumerate()
300 .map(|(i, v)| within(stored(v, ty(i), form), Step::Index(i)))
301 .collect()
302}
303
304fn text<'v>(value: &'v Value, what: &str) -> Result<&'v str, Problem> {
305 value
306 .as_str()
307 .ok_or_else(|| misfit(format!("expected {what} as text, got {}", kind_of(value))))
308}
309
310fn array(value: &Value) -> Result<&Vec<Value>, Problem> {
311 value
312 .as_array()
313 .ok_or_else(|| misfit(format!("expected a list, got {}", kind_of(value))))
314}
315
316fn object(value: &Value) -> Result<&Map<String, Value>, Problem> {
317 value
318 .as_object()
319 .ok_or_else(|| misfit(format!("expected an object, got {}", kind_of(value))))
320}
321
322pub fn duration_micros(text: &str) -> Result<i64, &'static str> {
330 let span = jiff::fmt::temporal::SpanParser::new()
331 .parse_span(text)
332 .map_err(|_| "not an ISO 8601 duration (e.g. PT1H30M, P1DT0.5S)")?;
333 if span.get_years() != 0 || span.get_months() != 0 {
334 return Err(
335 "a duration in years or months, which vary: give it in weeks, days, hours, minutes \
336 and seconds",
337 );
338 }
339 let micros = i128::from(span.get_weeks()) * 7 * DAY_MICROS
340 + i128::from(span.get_days()) * DAY_MICROS
341 + i128::from(span.get_hours()) * 3_600_000_000
342 + i128::from(span.get_minutes()) * 60_000_000
343 + i128::from(span.get_seconds()) * 1_000_000
344 + i128::from(span.get_milliseconds()) * 1000
345 + i128::from(span.get_microseconds())
346 + i128::from(span.get_nanoseconds()) / 1000;
347 i64::try_from(micros).map_err(|_| "a duration too long to store")
348}
349
350#[must_use]
352pub fn escaped(object: Map<String, Value>) -> Value {
353 if object.len() == 1 && object.keys().all(|k| TAGS.contains(&k.as_str())) {
354 json!({ "$dict": object })
355 } else {
356 Value::Object(object)
357 }
358}
359
360#[must_use]
362pub fn escape_tags(value: &Value) -> Value {
363 match value {
364 Value::Array(items) => Value::Array(items.iter().map(escape_tags).collect()),
365 Value::Object(object) => escaped(
366 object
367 .iter()
368 .map(|(k, v)| (k.clone(), escape_tags(v)))
369 .collect(),
370 ),
371 other => other.clone(),
372 }
373}
374
375fn kind_of(value: &Value) -> &'static str {
376 match value {
377 Value::Null => "null",
378 Value::Bool(_) => "a boolean",
379 Value::Number(n) if n.is_f64() => "a number",
380 Value::Number(_) => "an integer",
381 Value::String(_) => "text",
382 Value::Array(_) => "a list",
383 Value::Object(_) => "an object",
384 }
385}
386
387const fn expected(ty: &TypeDesc) -> &'static str {
388 match ty {
389 TypeDesc::None => "null",
390 TypeDesc::Bool => "a boolean",
391 TypeDesc::Int => "an integer",
392 TypeDesc::Float => "a number",
393 TypeDesc::Str => "text",
394 TypeDesc::Literal { .. } => "one of its values",
395 _ => "another type",
396 }
397}
398
399#[must_use]
403pub fn shown(stored: &Value) -> Value {
404 match stored {
405 Value::Array(items) => Value::Array(items.iter().map(shown).collect()),
406 Value::Object(object) if object.len() == 1 => {
407 let (tag, inner) = object.iter().next().unwrap_or_else(|| unreachable!());
408 match (tag.as_str(), inner) {
409 ("$datetime" | "$date", Value::String(_)) => inner.clone(),
410 ("$tuple", Value::Array(_)) | ("$dict", Value::Object(_)) => shown_fields(inner),
411 ("$timedelta", Value::Number(n)) if n.is_i64() => {
412 Value::String(iso_duration(n.as_i64().unwrap_or_default()))
413 }
414 _ => shown_fields(stored),
415 }
416 }
417 _ => shown_fields(stored),
418 }
419}
420
421fn shown_fields(value: &Value) -> Value {
422 match value {
423 Value::Array(items) => Value::Array(items.iter().map(shown).collect()),
424 Value::Object(object) => {
425 Value::Object(object.iter().map(|(k, v)| (k.clone(), shown(v))).collect())
426 }
427 other => other.clone(),
428 }
429}
430
431fn iso_duration(micros: i64) -> String {
433 let sign = if micros < 0 { "-" } else { "" };
434 let all = i128::from(micros).abs();
435 let (days, rest) = (all / DAY_MICROS, all % DAY_MICROS);
436 format!(
437 "{sign}P{days}DT{}.{:06}S",
438 rest / 1_000_000,
439 rest % 1_000_000
440 )
441}