Skip to main content

tilo_resource/
dates.rs

1//! Dates and times as model values: written whole as their ISO
2//! 8601 text, last writer wins.
3
4use automerge::{ObjId, ScalarValue, Value};
5use jiff::civil::{Date, DateTime, Time};
6
7use crate::model::{Doc, Model, ModelError, Slot, json_shape};
8use crate::path::Settable;
9
10macro_rules! date_model {
11    ($($ty:ty => $schema:literal, $what:literal, $field:ident;)*) => {$(
12        impl Settable for $ty {}
13        impl Model for $ty {
14            crate::__own_table!($ty);
15            crate::model::leaf_paths!();
16            fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
17                let _ = types;
18                crate::FieldType::$field
19            }
20            fn to_json(&self) -> serde_json::Value {
21                serde_json::Value::String(self.to_string())
22            }
23            fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
24                match value {
25                    serde_json::Value::String(text) => text
26                        .parse()
27                        .map_err(|_| ModelError::invalid(format!("not {}: {text}", $what))),
28                    _ => Err(json_shape($what)),
29                }
30            }
31            fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
32                match value {
33                    Value::Scalar(scalar) => match scalar.as_ref() {
34                        ScalarValue::Str(text) => text
35                            .parse()
36                            .map_err(|_| ModelError::invalid(format!("not {}: {text}", $what))),
37                        _ => Err(ModelError::shape($what)),
38                    },
39                    Value::Object(_) => Err(ModelError::shape($what)),
40                }
41            }
42            fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
43                slot.put_scalar(doc, ScalarValue::Str(self.to_string().into()))
44            }
45            fn collect_text(&self, out: &mut Vec<String>) {
46                out.push(self.to_string());
47            }
48        }
49        impl crate::JsonSchema for $ty {
50            fn json_schema() -> serde_json::Value {
51                serde_json::json!({"type": "string", "pattern": $schema})
52            }
53            fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
54                crate::FieldType::$field
55            }
56        }
57    )*};
58}
59
60date_model! {
61    Date => r"^\d{4}-\d{2}-\d{2}$", "a date", Date;
62    Time => r"^\d{2}:\d{2}:\d{2}(\.\d+)?$", "a time", Text;
63    DateTime =>
64        r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?$", "a date and time", Time;
65}