laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use std::collections::HashMap;

use laravel::url::RouteParam;

/// Values for the parameters of a localized route, and for the query string.
///
/// A parameter that the route's URI names fills its placeholder. Any other named parameter becomes
/// part of the query string, as in Laravel. Positional values fill the placeholders that no named
/// parameter filled, in order.
///
/// ```
/// use laralang::Params;
///
/// let params = Params::new().with("slug", "hola").with("page", 2);
/// # let _ = params;
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Params {
    pub(crate) named: Vec<(String, String)>,
    pub(crate) positional: Vec<String>,
}

impl Params {
    /// No parameters.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a named parameter. A later value with the same name replaces the earlier one.
    #[must_use]
    pub fn with(mut self, name: impl Into<String>, value: impl RouteParam) -> Self {
        self.set(name.into(), value.to_route_param());

        self
    }

    /// Positional values, which fill the route's placeholders in order.
    #[must_use]
    pub fn positional<V: RouteParam>(values: impl IntoIterator<Item = V>) -> Self {
        Self {
            named: Vec::new(),
            positional: values.into_iter().map(|value| value.to_route_param()).collect(),
        }
    }

    pub(crate) fn set(&mut self, name: String, value: String) {
        match self.named.iter_mut().find(|(existing, _)| *existing == name) {
            Some(slot) => slot.1 = value,
            None => self.named.push((name, value)),
        }
    }

    /// Whether there is nothing to fill.
    pub fn is_empty(&self) -> bool {
        self.named.is_empty() && self.positional.is_empty()
    }

    pub(crate) fn take(&mut self, name: &str) -> Option<String> {
        match self.named.iter().position(|(key, _)| key == name) {
            Some(index) => Some(self.named.remove(index).1),
            None if !self.positional.is_empty() => Some(self.positional.remove(0)),
            None => None,
        }
    }

    pub(crate) fn from_pairs(pairs: impl IntoIterator<Item = (String, String)>) -> Self {
        let mut params = Self::new();

        for (name, value) in pairs {
            params.set(name, value);
        }

        params
    }
}

/// Anything that can stand for a route's parameters: `()`, [`Params`], or pairs such as
/// `[("slug", "hola")]`.
pub trait IntoParams {
    /// The parameters.
    fn into_params(self) -> Params;
}

impl IntoParams for () {
    fn into_params(self) -> Params {
        Params::new()
    }
}

impl IntoParams for Params {
    fn into_params(self) -> Params {
        self
    }
}

impl IntoParams for &Params {
    fn into_params(self) -> Params {
        self.clone()
    }
}

fn pairs<K: AsRef<str>, V: RouteParam>(pairs: impl IntoIterator<Item = (K, V)>) -> Params {
    Params::from_pairs(
        pairs
            .into_iter()
            .map(|(key, value)| (key.as_ref().to_owned(), value.to_route_param())),
    )
}

impl<K: AsRef<str>, V: RouteParam, const N: usize> IntoParams for [(K, V); N] {
    fn into_params(self) -> Params {
        pairs(self)
    }
}

impl<K: AsRef<str>, V: RouteParam> IntoParams for Vec<(K, V)> {
    fn into_params(self) -> Params {
        pairs(self)
    }
}

impl<K: AsRef<str>, V: RouteParam> IntoParams for &[(K, V)] {
    fn into_params(self) -> Params {
        pairs(self.iter().map(|(key, value)| (key, value)))
    }
}

impl<K: AsRef<str>, V: RouteParam, const N: usize> IntoParams for &[(K, V); N] {
    fn into_params(self) -> Params {
        self.as_slice().into_params()
    }
}

impl<K: AsRef<str>, V: RouteParam> IntoParams for HashMap<K, V> {
    fn into_params(self) -> Params {
        let mut ordered: Vec<(K, V)> = self.into_iter().collect();

        ordered.sort_by(|a, b| a.0.as_ref().cmp(b.0.as_ref()));
        pairs(ordered)
    }
}