stencila_schema/
prelude.rs

1use chrono::{DateTime, Utc};
2pub use defaults::Defaults;
3pub use serde::{Deserialize, Serialize};
4pub use serde_json::Value;
5pub use serde_with::skip_serializing_none;
6pub use std::{
7    collections::BTreeMap,
8    convert::AsRef,
9    fmt::{self, Display},
10    sync::Arc,
11};
12pub use strum::AsRefStr;
13
14/// A null value
15///
16/// This is a struct, rather than a unit variant of `Primitive`, so that
17/// it can be treated the same way as other variants when dispatching to
18/// trait methods.
19#[derive(Clone, Debug)]
20pub struct Null {}
21
22impl Display for Null {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "null")
25    }
26}
27
28impl Serialize for Null {
29    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
30    where
31        S: serde::Serializer,
32    {
33        serializer.serialize_none()
34    }
35}
36
37impl<'de> Deserialize<'de> for Null {
38    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
39    where
40        D: serde::Deserializer<'de>,
41    {
42        let value = serde_json::Value::deserialize(deserializer)?;
43        match value.is_null() {
44            true => Ok(Null {}),
45            false => Err(serde::de::Error::custom("Expected a null value")),
46        }
47    }
48}
49
50/// A boolean value
51pub type Boolean = bool;
52
53/// An integer value
54///
55/// Uses `i64` for maximum precision.
56pub type Integer = i64;
57
58/// A floating point value (a.k.a real number)
59///
60/// Uses `i64` for maximum precision.
61pub type Number = f64;
62
63/// An array value (a.k.a. vector)
64pub type Array = Vec<Primitive>;
65
66/// An object value (a.k.a map, dictionary)
67///
68/// Uses `BTreeMap` to preserve order.
69pub type Object = BTreeMap<String, Primitive>;
70
71/// The set of primitive (non-Entity) node types
72#[derive(Clone, Debug, Serialize, Deserialize)]
73#[serde(untagged)]
74pub enum Primitive {
75    Null(Null),
76    Boolean(Boolean),
77    Integer(Integer),
78    Number(Number),
79    String(String),
80    Object(Object),
81    Array(Array),
82}
83
84/// A newtype derived from `String`
85///
86/// Defined primarily so that a customized `Patchable` implementation
87/// can be defined for strings where it is more appropriate to replace,
88/// rather than diff the string.
89#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
90pub struct Cord(pub String);
91
92// Convenience functions for `Date`
93
94impl From<DateTime<Utc>> for crate::Date {
95    fn from(date_time: DateTime<Utc>) -> Self {
96        Self {
97            value: date_time.to_rfc3339(),
98            ..Default::default()
99        }
100    }
101}
102
103impl crate::Date {
104    pub fn now() -> Self {
105        Self {
106            value: Utc::now().to_rfc3339(),
107            ..Default::default()
108        }
109    }
110}