1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
//! with some additional limitations. All timestamps are expected to be in UTC. The absence of the
//! timezone designator implies a UTC timestamp. Fractional seconds may be used.
//!
//! # Examples
//!
//! Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
//!
//! - `"2015-06-29T20:39:09Z"`
//! - `"2015-06-29T20:39:09"`
//! - `"2016-12-29T17:45:09.2Z"`
//! - `"2016-12-29T17:45:09.2"`
//! - `"2018-01-01T01:08:01.123Z"`
//! - `"2018-01-01T01:08:01.123"`
#[cfg(test)]
pub(crate) mod test;
#[cfg(test)]
mod test_datetime_from_schema;
#[cfg(test)]
mod test_from_schema;
use std::fmt;
use chrono::{DateTime, NaiveDateTime, TimeZone as _, Utc};
use crate::{
json,
schema::{self, HasElement as _},
warning::{self, GatherWarnings as _},
FromSchema, IntoCaveat as _, Verdict,
};
/// The warnings that can happen when parsing or linting a `NaiveDate`, `NaiveTime`, or `DateTime`.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
/// The datetime does not need to contain escape codes.
ContainsEscapeCodes,
/// The field at the path could not be decoded.
Decode(json::decode::Warning),
/// The datetime is not valid.
///
/// Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
/// with some additional limitations. All timestamps are expected to be in UTC. The absence of the
/// timezone designator implies a UTC timestamp. Fractional seconds may be used.
///
/// # Examples
///
/// Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
///
/// - `"2015-06-29T20:39:09Z"`
/// - `"2015-06-29T20:39:09"`
/// - `"2016-12-29T17:45:09.2Z"`
/// - `"2016-12-29T17:45:09.2"`
/// - `"2018-01-01T01:08:01.123Z"`
/// - `"2018-01-01T01:08:01.123"`
Invalid(String),
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ContainsEscapeCodes => {
f.write_str("The value contains escape codes but it does not need them.")
}
Self::Decode(warning) => fmt::Display::fmt(warning, f),
Self::Invalid(err) => write!(f, "The value is not valid: {err}"),
}
}
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
Self::Decode(kind) => kind.id(),
Self::Invalid(_) => warning::Id::from_static("invalid"),
}
}
}
impl From<json::decode::Warning> for Warning {
fn from(warn_kind: json::decode::Warning) -> Self {
Self::Decode(warn_kind)
}
}
impl<'buf> FromSchema<'buf, schema::Str<'buf>> for DateTime<Utc> {
type Warning = Warning;
fn from_schema(source: &schema::Str<'buf>) -> Verdict<Self, Self::Warning> {
let mut warnings = warning::Set::new();
let elem = source.element();
let pending_str = source
.value()
.has_escapes(elem)
.gather_warnings_into(&mut warnings);
let s = match pending_str {
json::PendingStr::NoEscapes(s) => s,
json::PendingStr::HasEscapes(_) => {
return warnings.bail(elem, Warning::ContainsEscapeCodes);
}
};
// First try parsing with a timezone, if that doesn't work try to parse without
let err = match s.parse::<DateTime<Utc>>() {
Ok(date) => return Ok(date.into_caveat(warnings)),
Err(err) => err,
};
let Ok(date) = s.parse::<NaiveDateTime>() else {
return warnings.bail(elem, Warning::Invalid(err.to_string()));
};
let datetime = Utc.from_utc_datetime(&date);
Ok(datetime.into_caveat(warnings))
}
}
impl<'buf> FromSchema<'buf, schema::Str<'buf>> for chrono::NaiveDate {
type Warning = Warning;
fn from_schema(source: &schema::Str<'buf>) -> Verdict<Self, Self::Warning> {
let mut warnings = warning::Set::new();
let elem = source.element();
// The schema confirmed the value is a string, so there is no kind check; its
// content is read directly.
let pending_str = source
.value()
.has_escapes(elem)
.gather_warnings_into(&mut warnings);
let s = match pending_str {
json::PendingStr::NoEscapes(s) => s,
json::PendingStr::HasEscapes(_) => {
return warnings.bail(elem, Warning::ContainsEscapeCodes);
}
};
let date = match s.parse::<chrono::NaiveDate>() {
Ok(v) => v,
Err(err) => {
return warnings.bail(elem, Warning::Invalid(err.to_string()));
}
};
Ok(date.into_caveat(warnings))
}
}
impl<'buf> FromSchema<'buf, schema::Str<'buf>> for chrono::NaiveTime {
type Warning = Warning;
fn from_schema(source: &schema::Str<'buf>) -> Verdict<Self, Self::Warning> {
let mut warnings = warning::Set::new();
let elem = source.element();
// The schema confirmed the value is a string, so there is no kind check; its
// content is read directly.
let pending_str = source
.value()
.has_escapes(elem)
.gather_warnings_into(&mut warnings);
let s = match pending_str {
json::PendingStr::NoEscapes(s) => s,
json::PendingStr::HasEscapes(_) => {
return warnings.bail(elem, Warning::ContainsEscapeCodes);
}
};
let date = match chrono::NaiveTime::parse_from_str(s, "%H:%M") {
Ok(v) => v,
Err(err) => {
return warnings.bail(elem, Warning::Invalid(err.to_string()));
}
};
Ok(date.into_caveat(warnings))
}
}