1use crate::boundary;
37use crate::json::{self, Extension, Refusal};
38use crate::{
39 Date, DateTime, Duration, Error, EvaluationError, Key, Map, ParseError, Position, Value,
40};
41
42const REQUIRED_UNITS: [&str; 7] = [
45 "years", "months", "weeks", "days", "hours", "minutes", "seconds",
46];
47
48pub fn decode(text: &str) -> Result<Value, Error> {
72 json::read(text, &untag).map_err(|fault| {
73 ParseError::new(fault.refusal.reason, fault.refusal.message)
74 .with_position(position_of(text, fault.offset))
75 .into()
76 })
77}
78
79pub fn encode(value: &Value) -> Result<String, Error> {
106 boundary::check(value)?;
107 json::write(value, &Tagged)
108 .map_err(|refusal| EvaluationError::new(refusal.reason, refusal.message).into())
109}
110
111fn position_of(text: &str, offset: usize) -> Position {
113 let before = text.get(..offset).unwrap_or(text);
114 let line_start = before.rfind('\n').map_or(0, |at| at + 1);
115 Position {
116 line: before.matches('\n').count() + 1,
117 column: before.get(line_start..).unwrap_or_default().chars().count() + 1,
118 }
119}
120
121fn invalid(message: String) -> Refusal {
122 Refusal::new("invalid_tagged_value", message)
123}
124
125pub(crate) fn untag(map: Map) -> Result<Value, Refusal> {
128 let Some(tag) = map.get_str("$type") else {
129 return Ok(Value::Map(map));
130 };
131 let Value::String(tag) = tag else {
132 return Err(invalid(
133 "a $type that is not a string is not a tag".to_owned(),
134 ));
135 };
136 let refused = || {
137 let keys: Vec<&Key> = map.keys().collect();
138 invalid(format!(
139 "a {tag:?} tag with the keys {keys:?} is not a tagged value"
140 ))
141 };
142 let value = map.get_str("value");
143 let tagged = match (tag.as_str(), map.len(), value) {
144 ("undefined", 1, _) => Some(Value::Undefined),
145 ("date", 2, Some(Value::String(text))) => Date::parse(text).map(Value::Date),
146 ("datetime", 2, Some(Value::String(text))) => DateTime::parse(text).map(Value::DateTime),
147 ("duration", 2, Some(Value::Map(units))) => duration(units).map(Value::Duration),
148 _ => None,
149 };
150 tagged.ok_or_else(refused)
151}
152
153pub(crate) fn duration(units: &Map) -> Option<Duration> {
156 let mut duration = Duration::default();
157 for (name, amount) in units.iter() {
158 let (Key::String(name), Value::Integer(amount)) = (name, amount) else {
159 return None;
160 };
161 *duration.unit_mut(name)? = *amount;
162 }
163 REQUIRED_UNITS
164 .iter()
165 .all(|unit| units.get_str(unit).is_some())
166 .then_some(duration)
167}
168
169pub(crate) fn carried(year: i32, text: String) -> Result<String, Refusal> {
171 if (0..=9999).contains(&year) {
172 Ok(text)
173 } else {
174 Err(invalid(format!(
175 "{text} is outside the years 0 to 9999 the encoding carries"
176 )))
177 }
178}
179
180pub(crate) fn check_map(map: &Map) -> Result<(), Refusal> {
182 if map.get_str("$type").is_some() {
183 return Err(Refusal::new(
184 "reserved_map_key",
185 "a map with a \"$type\" key would read back as a tag",
186 ));
187 }
188 Ok(())
189}
190
191fn duration_text(duration: &Duration, out: &mut String) {
194 let mut units: Vec<(&str, i64)> = duration
195 .units()
196 .into_iter()
197 .filter(|(name, _, amount)| *name != "milliseconds" || *amount != 0)
198 .map(|(name, _, amount)| (name, amount))
199 .collect();
200 units.sort_unstable_by_key(|(name, _)| *name);
201 out.push('{');
202 for (index, (name, amount)) in units.into_iter().enumerate() {
203 if index > 0 {
204 out.push(',');
205 }
206 out.push_str(&format!("\"{name}\":{amount}"));
207 }
208 out.push('}');
209}
210
211struct Tagged;
213
214impl Extension for Tagged {
215 fn write_other(&self, value: &Value, depth: usize, out: &mut String) -> Result<(), Refusal> {
216 json::depth_check(depth)?;
217 match value {
218 Value::Date(date) => {
219 let text = carried(date.year(), date.to_string())?;
220 out.push_str(&format!("{{\"$type\":\"date\",\"value\":\"{text}\"}}"));
221 }
222 Value::DateTime(instant) => {
223 let text = carried(instant.date().year(), instant.to_string())?;
224 out.push_str(&format!("{{\"$type\":\"datetime\",\"value\":\"{text}\"}}"));
225 }
226 Value::Duration(duration) => {
227 json::depth_check(depth + 1)?;
228 out.push_str("{\"$type\":\"duration\",\"value\":");
229 duration_text(duration, out);
230 out.push('}');
231 }
232 _ => out.push_str("{\"$type\":\"undefined\"}"),
233 }
234 Ok(())
235 }
236
237 fn check_map(&self, map: &Map) -> Result<(), Refusal> {
238 check_map(map)
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn reason(text: &str) -> String {
247 decode(text).unwrap_err().reason().to_owned()
248 }
249
250 fn date(year: i32, month: u32, day: u32) -> Date {
251 Date::new(year, month, day).unwrap()
252 }
253
254 #[test]
257 fn each_kind_round_trips_through_its_text() {
258 let instant = DateTime::new(date(2026, 8, 9), 10, 30, 0, 500_000).unwrap();
259 let pairs = [
260 (Value::Null, "null"),
261 (Value::Undefined, r#"{"$type":"undefined"}"#),
262 (Value::from(true), "true"),
263 (Value::from(-7), "-7"),
264 (Value::from(3.0), "3.0"),
265 (Value::from("x"), r#""x""#),
266 (Value::from(vec![1.into(), 1.0.into()]), "[1,1.0]"),
267 (
268 Value::from(
269 [("b", Value::Null), ("a", Value::from(1))]
270 .into_iter()
271 .collect::<Map>(),
272 ),
273 r#"{"a":1,"b":null}"#,
274 ),
275 (
276 Value::from(date(2026, 8, 9)),
277 r#"{"$type":"date","value":"2026-08-09"}"#,
278 ),
279 (
280 Value::from(instant),
281 r#"{"$type":"datetime","value":"2026-08-09T10:30:00.500000Z"}"#,
282 ),
283 (
284 Value::from(DateTime::from_unix(0, 0).unwrap()),
285 r#"{"$type":"datetime","value":"1970-01-01T00:00:00Z"}"#,
286 ),
287 (
288 Value::from(Duration {
289 weeks: 2,
290 days: 3,
291 ..Duration::default()
292 }),
293 r#"{"$type":"duration","value":{"days":3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":2,"years":0}}"#,
294 ),
295 (
296 Value::from(Duration {
297 seconds: 1,
298 milliseconds: 500,
299 ..Duration::default()
300 }),
301 r#"{"$type":"duration","value":{"days":0,"hours":0,"milliseconds":500,"minutes":0,"months":0,"seconds":1,"weeks":0,"years":0}}"#,
302 ),
303 (
304 Value::from(Duration {
305 days: -3,
306 ..Duration::default()
307 }),
308 r#"{"$type":"duration","value":{"days":-3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0,"years":0}}"#,
309 ),
310 ];
311 for (value, text) in pairs {
312 assert_eq!(encode(&value).unwrap(), text);
313 assert_eq!(decode(text).unwrap(), value, "{text}");
314 }
315 }
316
317 #[test]
320 fn a_tag_that_does_not_carry_its_value_is_refused() {
321 let units = r#""days":0,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0"#;
322 for text in [
323 r#"{"$type":"nope"}"#,
324 r#"{"$type":1}"#,
325 r#"{"$type":"undefined","value":1}"#,
326 r#"{"$type":"date","value":"2026-02-30"}"#,
327 r#"{"$type":"date","value":20260806}"#,
328 r#"{"$type":"date"}"#,
329 r#"{"$type":"datetime","value":"2026-08-06"}"#,
330 r#"{"$type":"datetime","value":"2026-08-06T12:00:00Z","x":1}"#,
331 &format!(r#"{{"$type":"duration","value":{{{units}}}}}"#),
332 &format!(r#"{{"$type":"duration","value":{{{units},"years":0.5}}}}"#),
333 &format!(r#"{{"$type":"duration","value":{{{units},"years":0,"decades":0}}}}"#),
334 r#"{"$type":"duration","value":[]}"#,
335 ] {
336 assert_eq!(reason(text), "invalid_tagged_value", "{text}");
337 }
338 let decoded = decode(&format!(
339 r#"{{"$type":"duration","value":{{{units},"years":0}}}}"#
340 ));
341 assert_eq!(decoded.unwrap(), Value::from(Duration::default()));
342 let offset = decode(r#"{"$type":"datetime","value":"2026-08-06T12:00:00+01:30"}"#);
343 assert_eq!(
344 encode(&offset.unwrap()).unwrap(),
345 r#"{"$type":"datetime","value":"2026-08-06T10:30:00Z"}"#
346 );
347 }
348
349 #[test]
351 fn a_decode_refusal_is_a_parse_error_at_its_position() {
352 let refused = decode("[1,\n {\"$type\":\"nope\"}]").unwrap_err();
353 assert_eq!(refused.type_name(), "ParseError");
354 assert_eq!(refused.position(), Some(Position { line: 2, column: 3 }));
355 assert_eq!(reason("[1e400]"), "non_finite_number");
356 assert_eq!(reason("[9223372036854775808]"), "integer_out_of_range");
357 assert_eq!(reason("{"), "malformed_json");
358 let refused = decode("\"é\" x").unwrap_err();
359 assert_eq!(refused.position(), Some(Position { line: 1, column: 5 }));
360 }
361
362 #[test]
364 fn a_tag_counts_toward_the_depth_limit() {
365 let wrap = |mut value: Value, levels: usize| {
366 for _ in 0..levels {
367 value = Value::from(vec![value]);
368 }
369 value
370 };
371 assert!(encode(&wrap(Value::Undefined, 99)).is_ok());
372 assert_eq!(
373 encode(&wrap(Value::Undefined, 100)).unwrap_err().reason(),
374 "depth_limit_exceeded"
375 );
376 let duration = Value::from(Duration::default());
377 assert!(encode(&wrap(duration.clone(), 98)).is_ok());
378 assert_eq!(
379 encode(&wrap(duration, 99)).unwrap_err().reason(),
380 "depth_limit_exceeded"
381 );
382 let text = encode(&wrap(Value::from(Duration::default()), 98)).unwrap();
383 assert!(decode(&text).is_ok());
384 assert_eq!(reason(&format!("[{text}]")), "depth_limit_exceeded");
385 }
386
387 #[test]
390 fn a_map_key_that_is_not_a_string_has_no_tagged_form() {
391 for key in [Key::from(1), Key::from(true), Key::Undefined] {
392 let map: Map = [(key, Value::Null)].into_iter().collect();
393 let refused = encode(&Value::from(vec![map.into()]))
394 .map_err(|error| (error.type_name(), error.reason().to_owned()));
395 assert_eq!(
396 refused,
397 Err(("EvaluationError", "non_string_map_key".to_owned()))
398 );
399 }
400 let decoded = decode(r#"{"1":1,"true":2,"undefined":3}"#).unwrap();
401 let Value::Map(map) = &decoded else {
402 panic!("{decoded:?}")
403 };
404 assert_eq!(map.get(&"1".into()), Some(&Value::from(1)));
405 assert_eq!(map.get(&Key::from(1)), None);
406 assert_eq!(map.get(&Key::from(true)), None);
407 assert_eq!(map.get(&Key::Undefined), None);
408 }
409
410 #[test]
412 fn an_encode_refusal_is_an_evaluation_error() {
413 let refused = |value: Value| {
414 let error = encode(&value).unwrap_err();
415 assert_eq!(error.type_name(), "EvaluationError");
416 error.reason().to_owned()
417 };
418 assert_eq!(refused(Value::from(f64::NAN)), "non_finite_number");
419 assert_eq!(
420 refused(Value::from(date(10_000, 1, 1))),
421 "invalid_tagged_value"
422 );
423 assert_eq!(
424 refused(Value::from(date(-1, 12, 31))),
425 "invalid_tagged_value"
426 );
427 let far = DateTime::new(date(10_000, 1, 1), 0, 0, 0, 0).unwrap();
428 assert_eq!(refused(Value::from(far)), "invalid_tagged_value");
429 let inner: Map = [("$type", Value::from("date"))].into_iter().collect();
430 assert_eq!(refused(Value::from(vec![inner.into()])), "reserved_map_key");
431 assert!(encode(&Value::from(date(0, 1, 1))).is_ok());
432 assert!(encode(&Value::from(date(9999, 12, 31))).is_ok());
433 }
434}