ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
//! 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_from_schema;

#[cfg(test)]
mod test_parse_date;

#[cfg(test)]
mod test_parse_time;

use std::fmt;

use chrono::{DateTime, NaiveDateTime, TimeZone as _, Utc};

use crate::{
    FromSchema, IntoCaveat as _, Verdict, json,
    schema::{self, HasElement as _},
    warning::{self, GatherWarnings as _},
};

/// Read a calendar date matching `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
///
/// OCPI writes a date as `YYYY-MM-DD`. Two forms this function reads leave the date unambiguous: a
/// month or day without its leading zero, such as `2023-1-5`, and spaces around the date. The
/// schema walk reports both as `schema::Warning::IncorrectFormat`. Any four-digit year is read,
/// including `0023`.
///
/// chrono's `NaiveDate::from_str` would also read a sign and a short year, reading `23-01-05` as
/// the year `0023`. A `-` makes a year negative and a short year may not mean what it reads as, so
/// neither is unambiguous, and a `+` is rejected with the `-` so that no sign is read. chrono's
/// leniency is not documented either, so relying on it would let a chrono upgrade change which
/// dates the library reads.
///
/// The date lowering and the schema walk both read a date through this function, so the walk
/// proposes a date only when the library reads one, and proposes the date the library read.
pub(crate) fn parse_date(s: &str) -> Result<chrono::NaiveDate, DateError> {
    let s = s.trim_matches(' ');

    let digits = |text: &str, lengths: std::ops::RangeInclusive<usize>| {
        lengths.contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
    };

    let mut parts = s.split('-');
    let (Some(year), Some(month), Some(day), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err(DateError::Syntax);
    };

    if !digits(year, 4..=4) || !digits(month, 1..=2) || !digits(day, 1..=2) {
        return Err(DateError::Syntax);
    }

    // Each part is 1 to 4 ASCII digits, which always fits an `i32` or `u32`, so this `else` arm
    // is unreachable. It returns `Syntax` rather than unwrapping because this crate does not
    // panic.
    let (Ok(year), Ok(month), Ok(day)) = (year.parse(), month.parse(), day.parse()) else {
        return Err(DateError::Syntax);
    };

    chrono::NaiveDate::from_ymd_opt(year, month, day).ok_or(DateError::NotACalendarDate)
}

/// Read a time of day matching `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
///
/// OCPI writes `start_time` and `end_time` as `HH:MM`. Two forms this function reads leave the
/// time unambiguous: an hour or minute without its leading zero, such as `9:5`, and spaces around
/// the time. The schema walk reports both as `schema::Warning::IncorrectFormat`.
///
/// chrono's `%H:%M` would also read a space between the colon and the minute, as in `09: 00`, and
/// would reject a space after the time. A space inside the time is not a form OCPI or this function
/// reads as unambiguous, so this function rejects it. chrono's leniency is not documented, so
/// relying on it would let a chrono upgrade change which times the library reads.
///
/// The time lowering, the schema walk and the fix for `lint::tariff::Warning::ContainsEntireDay`
/// all read a time through this function. So the walk proposes a time only when the library reads
/// one, and the fix removes a bound only when the library reads it as midnight.
pub(crate) fn parse_time(s: &str) -> Result<chrono::NaiveTime, TimeError> {
    let s = s.trim_matches(' ');

    let Some((hour, minute)) = s.split_once(':') else {
        return Err(TimeError::Syntax);
    };

    let digits =
        |text: &str| (1..=2).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit());

    if !digits(hour) || !digits(minute) {
        return Err(TimeError::Syntax);
    }

    // Each part is 1 or 2 ASCII digits, which always fits a `u32`, so this `else` arm is
    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
    let (Ok(hour), Ok(minute)) = (hour.parse(), minute.parse()) else {
        return Err(TimeError::Syntax);
    };

    chrono::NaiveTime::from_hms_opt(hour, minute, 0).ok_or(TimeError::NotATimeOfDay)
}

/// Why [`parse_time`] could not parse the time.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum TimeError {
    /// The text does not match `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
    Syntax,

    /// The numbers don't name a time of day, as in `24:00` or `09:60`.
    NotATimeOfDay,
}

impl fmt::Display for TimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => f.write_str("expected a time written as `HH:MM`"),
            Self::NotATimeOfDay => f.write_str("the time does not exist in a day"),
        }
    }
}

/// Why [`parse_date`] could not parse the date.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum DateError {
    /// The text does not match `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
    Syntax,

    /// The numbers don't name a calendar date, as in `2023-02-30`.
    NotACalendarDate,
}

impl fmt::Display for DateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => f.write_str("expected a date written as `YYYY-MM-DD`"),
            Self::NotACalendarDate => f.write_str("the date does not exist in the calendar"),
        }
    }
}

/// 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 parse_date(s) {
            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 parse_time(s) {
            Ok(v) => v,
            Err(err) => {
                return warnings.bail(elem, Warning::Invalid(err.to_string()));
            }
        };

        Ok(date.into_caveat(warnings))
    }
}