ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
use std::fmt;

use super::{
    Component, Components, ElemId, Element, Field, Location, Path, PathSet, RawStr, Span, decode,
};

impl<'buf> Element<'buf> {
    /// Return `Some(&str)` if the `Value` is a `String`.
    pub fn to_raw_str(&self) -> Option<RawStr<'buf>> {
        self.value.to_raw_str()
    }

    /// Returns the items if this element is a JSON array, `None` otherwise.
    pub fn as_array(&self) -> Option<&[Element<'buf>]> {
        self.value.as_array()
    }

    /// Returns the span covering the value plus any trailing comma and the whitespace
    /// after it, so the span ends where the next sibling begins.
    ///
    /// When there is no trailing comma (the root element, or the last child of its
    /// parent), `full_span() == span()`.
    ///
    /// Use [`Element::span`] to replace a value. Removal is not simply a matter of
    /// erasing `full_span`: which span removes a child depends on which of its siblings
    /// survive, and erasing the `full_span` of a last child leaves a dangling comma on
    /// the sibling before it. Use [`Document::removal_spans`], which resolves a whole set
    /// of removals against the surviving siblings.
    pub fn full_span(&self) -> Span {
        Span {
            start: self.span.start,
            end: self.full_span_end,
        }
    }

    pub(crate) fn find_field(&self, key: &str) -> Option<&Field<'buf>> {
        let fields = self.as_object_fields()?;

        fields
            .iter()
            .find(|field| field.key().eq_escape_aware(key).ok().unwrap_or(false))
    }
}

impl Field<'_> {
    /// Returns the span covering `"key": value` plus any trailing comma and the whitespace
    /// after it, so the span ends where the next field begins.
    ///
    /// When there is no trailing comma (the last field), `full_span()` covers
    /// `"key": value` only.
    ///
    /// As with [`Element::full_span`], removing a field is not simply a matter of erasing
    /// this span; use [`Document::removal_spans`]. Erasing the `full_span` of a last field
    /// leaves a dangling comma on the field before it, and a field's value cannot be
    /// erased on its own without leaving a key with nothing after the colon.
    pub fn full_span(&self) -> Span {
        Span {
            start: self.key_span.start,
            end: self.element.full_span_end,
        }
    }
}

impl RawStr<'_> {
    /// Compare `other` against this raw `&str`, decoding any JSON escape
    /// sequences in the `&str` on the fly without allocating.
    ///
    /// Returns `Ok(true)`/`Ok(false)` for the comparison, or `Err` if the key
    /// contains a decoding problem (an invalid escape or a control character) at
    /// or before the first differing character.
    pub fn eq_escape_aware(&self, other: &str) -> Result<bool, decode::Warning> {
        decode::eq(self.0, other)
    }
}

/// The tests need to assert against literal `ElemId`s.
impl From<usize> for ElemId {
    fn from(value: usize) -> Self {
        Self(value)
    }
}

/// A `Display` object that writes out the JSON source and highlights the given line.
pub struct LineHighlighter {
    json: String,
    pos: Location,
}

impl LineHighlighter {
    pub fn from_value(json: &serde_json::Value, pos: Location) -> Self {
        let json = serde_json::to_string_pretty(json).unwrap();
        Self { json, pos }
    }
}

impl fmt::Display for LineHighlighter {
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "line count cannot realistically overflow usize"
    )]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Ok(target_line) = usize::try_from(self.pos.line) else {
            return Ok(());
        };

        for (index, line) in self.json.lines().enumerate() {
            let line_no = index + 1;
            if index == target_line {
                writeln!(f, "{line_no:3}| {line}")?;
            } else {
                writeln!(f, "   | {line}")?;
            }
        }

        Ok(())
    }
}

impl PathSet<'_> {
    /// Filter off the fields that match the glob.
    pub(crate) fn filter_matches(&mut self, glob: &PathGlob) {
        self.0.retain(|path| !glob.matches(path));
    }
}

/// A string based `Path` that can contain glob `*` patterns in place of a literal path element.
/// The glob means that the path section can be any valid section.
///
/// A glob with no `*` component matches one path and one path only, so an exact path in an
/// expect file is just the degenerate case of a glob.
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
pub(crate) struct PathGlob(String);

impl PathGlob {
    /// Return true if this `PathGlob` matches the given path string.
    ///
    /// The glob and path are compared component by component (see
    /// [`Path::components`]). A wildcard glob component, written `.*` and parsed
    /// as `Component::Member("*")`, matches any single path component, whether a
    /// member or an index; all other components must match exactly. The number
    /// of components must be equal.
    pub(crate) fn matches(&self, path: &Path) -> bool {
        let mut glob = Components::over(&self.0);
        let mut actual = path.components();

        loop {
            match (glob.next(), actual.next()) {
                (Some(glob_component), Some(component)) => {
                    let is_wildcard = matches!(glob_component, Component::Member("*"));
                    if !is_wildcard && glob_component != component {
                        return false;
                    }
                }
                // Both ran out at the same time: every component matched.
                (None, None) => return true,
                // The component counts differ.
                (None, Some(_)) | (Some(_), None) => return false,
            }
        }
    }
}

impl fmt::Debug for PathGlob {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for PathGlob {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl<'a> From<&'a str> for PathGlob {
    fn from(s: &'a str) -> Self {
        Self(s.into())
    }
}

impl From<String> for PathGlob {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl<'de> serde::Deserialize<'de> for PathGlob {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        let s = <String as ::serde::Deserialize>::deserialize(deserializer)?;
        Ok(Self(s))
    }
}