Skip to main content

ocpi_tariffs/
datetime.rs

1//! Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
2//! with some additional limitations. All timestamps are expected to be in UTC. The absence of the
3//! timezone designator implies a UTC timestamp. Fractional seconds may be used.
4//!
5//! # Examples
6//!
7//! Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
8//!
9//! - `"2015-06-29T20:39:09Z"`
10//! - `"2015-06-29T20:39:09"`
11//! - `"2016-12-29T17:45:09.2Z"`
12//! - `"2016-12-29T17:45:09.2"`
13//! - `"2018-01-01T01:08:01.123Z"`
14//! - `"2018-01-01T01:08:01.123"`
15
16#[cfg(test)]
17pub(crate) mod test;
18
19#[cfg(test)]
20mod test_from_schema;
21
22#[cfg(test)]
23mod test_parse_date;
24
25#[cfg(test)]
26mod test_parse_date_time;
27
28#[cfg(test)]
29mod test_parse_time;
30
31use std::fmt;
32
33use jiff::{Timestamp, civil, tz};
34
35use crate::{
36    LowerSchema, json,
37    schema::{self, HasElement as _},
38    warning,
39};
40
41/// Read a calendar date matching `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
42///
43/// OCPI writes a date as `YYYY-MM-DD`. Two forms this function reads leave the date unambiguous: a
44/// month or day without its leading zero, such as `2023-1-5`, and spaces around the date. The
45/// schema walk reports both as `schema::Warning::IncorrectFormat`. Any four-digit year is read,
46/// including `0023`.
47///
48/// This function rejects a year with a sign and a year of fewer than four digits, because neither
49/// reads unambiguously. A `-` makes the year negative. A short year, such as the `23` of
50/// `23-01-05`, may not mean the year it reads as. This function rejects a `+` too, so that it
51/// reads no sign at all.
52///
53/// `jiff`'s parser for `civil::Date` reads `20230105` and `+002023-01-05`, and rejects
54/// `2023-1-5` and spaces around the date. So this function sets the forms itself, as
55/// [`parse_date_time`] does.
56///
57/// The date lowering and the schema walk both read a date through this function, so the walk
58/// proposes a date only when the library reads one, and proposes the date the library read.
59pub(crate) fn parse_date(s: &str) -> Result<civil::Date, DateError> {
60    let s = s.trim_matches(' ');
61
62    let mut parts = s.split('-');
63    let (Some(year), Some(month), Some(day), None) =
64        (parts.next(), parts.next(), parts.next(), parts.next())
65    else {
66        return Err(DateError::Syntax);
67    };
68
69    if !digits(year, 4..=4) || !digits(month, 1..=2) || !digits(day, 1..=2) {
70        return Err(DateError::Syntax);
71    }
72
73    // The year is 4 ASCII digits, which always fit an `i16`. The month and day are each 1 or 2
74    // ASCII digits, which always fit an `i8`. So this `else` arm is unreachable. It returns
75    // `Syntax` rather than unwrapping because this crate does not panic.
76    let (Ok(year), Ok(month), Ok(day)) = (year.parse(), month.parse(), day.parse()) else {
77        return Err(DateError::Syntax);
78    };
79
80    let Ok(date) = civil::Date::new(year, month, day) else {
81        return Err(DateError::NotACalendarDate);
82    };
83
84    Ok(date)
85}
86
87/// Read a time of day matching `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
88///
89/// OCPI writes `start_time` and `end_time` as `HH:MM`. Two forms this function reads leave the
90/// time unambiguous: an hour or minute without its leading zero, such as `9:5`, and spaces around
91/// the time. The schema walk reports both as `schema::Warning::IncorrectFormat`.
92///
93/// This function rejects a space inside the time, as in `09: 00`. OCPI's `HH:MM` has no such
94/// space, and the space isn't one of the two forms above that this function reads anyway.
95///
96/// `jiff`'s parser for `civil::Time` reads `0900` and a bare hour such as `09`, and rejects
97/// `9:5` and spaces around the time. So this function sets the forms itself, as
98/// [`parse_date_time`] does.
99///
100/// The time lowering, the schema walk and the fix for `lint::tariff::Warning::ContainsEntireDay`
101/// all read a time through this function. So the walk proposes a time only when the library reads
102/// one, and the fix removes a bound only when the library reads it as midnight.
103pub(crate) fn parse_time(s: &str) -> Result<civil::Time, TimeError> {
104    let s = s.trim_matches(' ');
105
106    let Some((hour, minute)) = s.split_once(':') else {
107        return Err(TimeError::Syntax);
108    };
109
110    if !digits(hour, 1..=2) || !digits(minute, 1..=2) {
111        return Err(TimeError::Syntax);
112    }
113
114    // Each part is 1 or 2 ASCII digits, which always fits an `i8`, so this `else` arm is
115    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
116    let (Ok(hour), Ok(minute)) = (hour.parse(), minute.parse()) else {
117        return Err(TimeError::Syntax);
118    };
119
120    let Ok(time) = civil::Time::new(hour, minute, 0, 0) else {
121        return Err(TimeError::NotATimeOfDay);
122    };
123
124    Ok(time)
125}
126
127/// Read a datetime and return the instant it names, in UTC.
128///
129/// OCPI writes a datetime following RFC 3339, as `2015-06-29T20:39:09Z`, and a datetime without
130/// an offset is in UTC. This function reads:
131///
132/// - a date as [`parse_date`] reads it, so a month or day may lack its leading zero
133/// - a `T`, a `t` or one space between the date and the time
134/// - a time written `H:M:S`, each field one or two digits, optionally followed by a `.` and 1 to 9
135///   fractional digits
136/// - an optional `Z`, `z` or `±HH:MM` offset directly after the time
137/// - spaces around the datetime
138///
139/// This function rejects these forms, none of which OCPI writes:
140///
141/// - a signed or short year, such as `+2024` or `24`
142/// - an offset without its colon, such as `+0100`
143/// - `UTC` as an offset
144/// - a space before the offset
145/// - more than one space between the date and the time
146/// - more than 9 fractional digits
147///
148/// `jiff`'s parser for `Timestamp` reads an offset without its colon, such as `+0100`,
149/// which OCPI doesn't allow. It rejects a month with one digit, which a real CDR writes. So this
150/// function sets the forms itself.
151///
152/// RFC 3339 allows a second of `60` for a leap second, and this function rejects it. A
153/// timestamp has no instant for that second, so reading it means choosing another instant. jiff's
154/// parser chooses `59`, the second before the leap second. Rejecting the leap second keeps that
155/// choice from deciding when a session started or ended.
156///
157/// The last instant this function returns is `9999-12-30T22:00:00.999999999Z`, and it reads
158/// any later instant as that one.
159pub(crate) fn parse_date_time(s: &str) -> Result<Timestamp, DateTimeError> {
160    let s = s.trim_matches(' ');
161
162    let Some((date, time_and_offset)) = s.split_once(['T', 't', ' ']) else {
163        return Err(DateTimeError::Syntax);
164    };
165
166    let date = match parse_date(date) {
167        Ok(date) => date,
168        Err(DateError::Syntax) => return Err(DateTimeError::Syntax),
169        Err(DateError::NotACalendarDate) => return Err(DateTimeError::NotACalendarDate),
170    };
171
172    // A time is digits, `:` and `.`, so the first `+` or `-` after the date starts the offset.
173    // One that falls inside a malformed time leaves a time the field checks below reject.
174    let (time, offset) = if let Some(time) = time_and_offset.strip_suffix(['Z', 'z']) {
175        (time, None)
176    } else if let Some(sign_at) = time_and_offset.find(['+', '-']) {
177        let (time, offset) = time_and_offset.split_at(sign_at);
178        (time, Some(offset))
179    } else {
180        (time_and_offset, None)
181    };
182
183    let mut fields = time.split(':');
184    let (Some(hour), Some(minute), Some(second), None) =
185        (fields.next(), fields.next(), fields.next(), fields.next())
186    else {
187        return Err(DateTimeError::Syntax);
188    };
189
190    let (second, fraction) = match second.split_once('.') {
191        Some((second, fraction)) => (second, Some(fraction)),
192        None => (second, None),
193    };
194
195    if !digits(hour, 1..=2) || !digits(minute, 1..=2) || !digits(second, 1..=2) {
196        return Err(DateTimeError::Syntax);
197    }
198
199    let fraction = match fraction {
200        // A datetime without a fraction is read as one with the fraction `.0`.
201        None => "0",
202        Some(fraction) if digits(fraction, 1..=9) => fraction,
203        Some(_) => return Err(DateTimeError::Syntax),
204    };
205
206    // The hour, minute and second are each 1 or 2 ASCII digits, which always fit an `i8`. The
207    // fraction is 1 to 9 ASCII digits, which always fit an `i32`. So this `else` arm is
208    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
209    let (Ok(hour), Ok(minute), Ok(second), Ok(fraction_value)) = (
210        hour.parse(),
211        minute.parse(),
212        second.parse(),
213        fraction.parse::<i32>(),
214    ) else {
215        return Err(DateTimeError::Syntax);
216    };
217
218    // A fraction of n digits counts units of 10^-n seconds, so multiplying it by 10^(9 - n)
219    // gives nanoseconds: `.2` is 200,000,000. A fraction has 1 to 9 digits, so the product is
220    // under 1,000,000,000 and this `else` arm is unreachable. It returns `Syntax` rather than
221    // unwrapping because this crate does not panic.
222    let nanoseconds = u32::try_from(fraction.len())
223        .ok()
224        .and_then(|fraction_digits| 9_u32.checked_sub(fraction_digits))
225        .and_then(|zeros| 10_i32.checked_pow(zeros))
226        .and_then(|scale| fraction_value.checked_mul(scale));
227    let Some(nanoseconds) = nanoseconds else {
228        return Err(DateTimeError::Syntax);
229    };
230
231    // RFC 3339 writes a leap second as a second of `60`, which `civil::Time::new` rejects.
232    let Ok(time) = civil::Time::new(hour, minute, second, nanoseconds) else {
233        return Err(DateTimeError::NotATimeOfDay);
234    };
235
236    let date_time = date.to_datetime(time);
237
238    // A datetime without an offset is in UTC.
239    let offset = offset.unwrap_or("+00:00");
240
241    let (sign, hours_and_minutes) = offset.split_at(1);
242    let Some((hours, minutes)) = hours_and_minutes.split_once(':') else {
243        return Err(DateTimeError::Syntax);
244    };
245
246    if !digits(hours, 2..=2) || !digits(minutes, 2..=2) {
247        return Err(DateTimeError::Syntax);
248    }
249
250    // Each part is 2 ASCII digits, which always fits an `i8`, so this `else` arm is
251    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
252    let (Ok(hours), Ok(minutes)) = (hours.parse(), minutes.parse()) else {
253        return Err(DateTimeError::Syntax);
254    };
255
256    // A `tz::Offset` holds up to 25:59:59, so building one directly would read `+24:00`.
257    // This function allows an offset only within the range of a time of day, so
258    // `civil::Time::new` checks the hours and minutes.
259    let Ok(offset) = civil::Time::new(hours, minutes, 0, 0) else {
260        return Err(DateTimeError::NotAnOffset);
261    };
262
263    // An offset is under 24 hours, which a `tz::Offset` always holds, so this `else` arm
264    // is unreachable. It returns `NotAnOffset` rather than unwrapping because this crate does not
265    // panic.
266    let Ok(offset) = tz::Offset::try_from(offset.duration_since(civil::Time::midnight())) else {
267        return Err(DateTimeError::NotAnOffset);
268    };
269
270    let offset = if sign == "+" { offset } else { offset.negate() };
271
272    // A `jiff::Timestamp` holds no instant after `9999-12-30T22:00:00.999999999Z`, and a
273    // tariff may write a later one, such as an `end_date_time` of `9999-12-31T23:59:59Z` to mean
274    // it never expires. Rejecting that instant would reject the tariff, so this function reads it
275    // as `Timestamp::MAX`. No session reaches either instant, so the tariff prices the same.
276    // A year is at least `0000`, so no datetime falls before `Timestamp::MIN`.
277    let timestamp = offset.to_timestamp(date_time).unwrap_or(Timestamp::MAX);
278
279    Ok(timestamp)
280}
281
282/// Return whether `text` is only ASCII digits and has a length within `lengths`.
283fn digits(text: &str, lengths: std::ops::RangeInclusive<usize>) -> bool {
284    lengths.contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
285}
286
287/// Why [`parse_time`] could not parse the time.
288#[derive(Debug, Eq, PartialEq)]
289pub(crate) enum TimeError {
290    /// The text does not match `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
291    Syntax,
292
293    /// The numbers don't name a time of day, as in `24:00` or `09:60`.
294    NotATimeOfDay,
295}
296
297impl fmt::Display for TimeError {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        match self {
300            Self::Syntax => f.write_str("expected a time written as `HH:MM`"),
301            Self::NotATimeOfDay => f.write_str("the time does not exist in a day"),
302        }
303    }
304}
305
306/// Why [`parse_date`] could not parse the date.
307#[derive(Debug, Eq, PartialEq)]
308pub(crate) enum DateError {
309    /// The text does not match `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
310    Syntax,
311
312    /// The numbers don't name a calendar date, as in `2023-02-30`.
313    NotACalendarDate,
314}
315
316impl fmt::Display for DateError {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        match self {
319            Self::Syntax => f.write_str("expected a date written as `YYYY-MM-DD`"),
320            Self::NotACalendarDate => f.write_str("the date does not exist in the calendar"),
321        }
322    }
323}
324
325/// Why [`parse_date_time`] could not parse the datetime.
326#[derive(Debug, Eq, PartialEq)]
327pub(crate) enum DateTimeError {
328    /// The text is not in a form [`parse_date_time`] reads.
329    Syntax,
330
331    /// The date doesn't name a calendar date, as in `2023-02-30T00:00:00Z`.
332    NotACalendarDate,
333
334    /// The time doesn't name a time of day, as in `2023-01-05T24:00:00Z` or the leap second
335    /// `2016-12-31T23:59:60Z`.
336    NotATimeOfDay,
337
338    /// The offset is 24 hours or more, or its minutes are 60 or more, as in `+24:00`.
339    NotAnOffset,
340}
341
342impl fmt::Display for DateTimeError {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        match self {
345            Self::Syntax => f.write_str("expected a datetime written as `YYYY-MM-DDTHH:MM:SSZ`"),
346            Self::NotACalendarDate => f.write_str("the date does not exist in the calendar"),
347            Self::NotATimeOfDay => f.write_str("the time does not exist in a day"),
348            Self::NotAnOffset => f.write_str("the offset is not between -23:59 and +23:59"),
349        }
350    }
351}
352
353/// The warnings that can happen when parsing or linting a date, a time or a datetime.
354#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
355pub enum Warning {
356    /// The datetime does not need to contain escape codes.
357    ContainsEscapeCodes,
358
359    /// The field at the path could not be decoded.
360    Decode(json::decode::Warning),
361
362    /// The datetime is not valid.
363    ///
364    /// Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
365    /// with some additional limitations. All timestamps are expected to be in UTC. The absence of the
366    /// timezone designator implies a UTC timestamp. Fractional seconds may be used.
367    ///
368    /// # Examples
369    ///
370    /// Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
371    ///
372    /// - `"2015-06-29T20:39:09Z"`
373    /// - `"2015-06-29T20:39:09"`
374    /// - `"2016-12-29T17:45:09.2Z"`
375    /// - `"2016-12-29T17:45:09.2"`
376    /// - `"2018-01-01T01:08:01.123Z"`
377    /// - `"2018-01-01T01:08:01.123"`
378    Invalid(String),
379}
380
381impl fmt::Display for Warning {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        match self {
384            Self::ContainsEscapeCodes => {
385                f.write_str("The value contains escape codes but it does not need them.")
386            }
387            Self::Decode(warning) => fmt::Display::fmt(warning, f),
388            Self::Invalid(err) => write!(f, "The value is not valid: {err}"),
389        }
390    }
391}
392
393impl crate::Warning for Warning {
394    fn id(&self) -> warning::Id {
395        match self {
396            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
397            Self::Decode(kind) => kind.id(),
398            Self::Invalid(_) => warning::Id::from_static("invalid"),
399        }
400    }
401}
402
403impl From<json::decode::Warning> for Warning {
404    fn from(warn_kind: json::decode::Warning) -> Self {
405        Self::Decode(warn_kind)
406    }
407}
408
409impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for Timestamp {
410    type Warning = Warning;
411
412    fn lower_schema(
413        source: &schema::Str<'buf>,
414        warnings: &mut dyn warning::Gather<Warning>,
415    ) -> Result<Self, warning::Error<Warning>> {
416        let elem = source.element();
417
418        let pending_str = source
419            .value()
420            .has_escapes(elem, &mut warning::Converting::new(warnings));
421
422        let s = match pending_str {
423            json::PendingStr::NoEscapes(s) => s,
424            json::PendingStr::HasEscapes => {
425                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
426            }
427        };
428
429        let date_time = match parse_date_time(s) {
430            Ok(v) => v,
431            Err(err) => {
432                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
433            }
434        };
435
436        Ok(date_time)
437    }
438}
439
440impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for civil::Date {
441    type Warning = Warning;
442
443    fn lower_schema(
444        source: &schema::Str<'buf>,
445        warnings: &mut dyn warning::Gather<Warning>,
446    ) -> Result<Self, warning::Error<Warning>> {
447        let elem = source.element();
448
449        // The schema confirmed the value is a string, so there is no kind check; its
450        // content is read directly.
451        let pending_str = source
452            .value()
453            .has_escapes(elem, &mut warning::Converting::new(warnings));
454
455        let s = match pending_str {
456            json::PendingStr::NoEscapes(s) => s,
457            json::PendingStr::HasEscapes => {
458                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
459            }
460        };
461
462        let date = match parse_date(s) {
463            Ok(v) => v,
464            Err(err) => {
465                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
466            }
467        };
468
469        Ok(date)
470    }
471}
472
473impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for civil::Time {
474    type Warning = Warning;
475
476    fn lower_schema(
477        source: &schema::Str<'buf>,
478        warnings: &mut dyn warning::Gather<Warning>,
479    ) -> Result<Self, warning::Error<Warning>> {
480        let elem = source.element();
481
482        // The schema confirmed the value is a string, so there is no kind check; its
483        // content is read directly.
484        let pending_str = source
485            .value()
486            .has_escapes(elem, &mut warning::Converting::new(warnings));
487
488        let s = match pending_str {
489            json::PendingStr::NoEscapes(s) => s,
490            json::PendingStr::HasEscapes => {
491                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
492            }
493        };
494
495        let date = match parse_time(s) {
496            Ok(v) => v,
497            Err(err) => {
498                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
499            }
500        };
501
502        Ok(date)
503    }
504}