use std::borrow::Cow;
use crate::chars::{self, QUERY};
use crate::error::InvalidUrl;
use crate::quoting::{Component, unquote};
#[repr(transparent)]
pub struct Query(str);
str_type!(Query);
str_eq!(Query);
impl Query {
pub fn new(src: &str) -> Result<&Query, InvalidUrl> {
chars::check(src, &QUERY)?;
Ok(Query::from_str_unchecked(src))
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn decode(&self) -> Cow<'_, str> {
unquote(&self.0, Component::Query)
}
pub fn pairs(&self) -> QueryPairs<'_> {
QueryPairs(self.0.split('&'))
}
pub fn get<'a>(&'a self, key: &str) -> Option<Cow<'a, str>> {
self.get_all(key).next()
}
pub fn get_all<'a>(&'a self, key: &str) -> impl Iterator<Item = Cow<'a, str>> {
self.raw_values(key)
.map(|v| unquote(v, Component::QueryPart))
}
pub fn contains_key(&self, key: &str) -> bool {
self.raw_values(key).next().is_some()
}
fn raw_values<'a>(&'a self, key: &str) -> impl Iterator<Item = &'a str> {
pieces(&self.0)
.map(split_pair)
.filter_map(move |(k, v)| (unquote(k, Component::QueryPart) == key).then_some(v))
}
}
pub(crate) fn pieces(query: &str) -> impl Iterator<Item = &str> {
query.split('&').filter(|piece| !piece.is_empty())
}
pub(crate) fn split_pair(piece: &str) -> (&str, &str) {
piece.split_once('=').unwrap_or((piece, ""))
}
#[derive(Clone, Debug)]
pub struct QueryPairs<'a>(std::str::Split<'a, char>);
impl<'a> Iterator for QueryPairs<'a> {
type Item = (Cow<'a, str>, Cow<'a, str>);
fn next(&mut self) -> Option<Self::Item> {
let (k, v) = split_pair(self.0.by_ref().find(|piece| !piece.is_empty())?);
Some((
unquote(k, Component::QueryPart),
unquote(v, Component::QueryPart),
))
}
}
#[repr(transparent)]
pub struct Fragment(str);
str_type!(Fragment);
str_eq!(Fragment);
impl Fragment {
pub fn new(src: &str) -> Result<&Fragment, InvalidUrl> {
chars::check(src, &QUERY)?;
Ok(Fragment::from_str_unchecked(src))
}
pub fn decode(&self) -> Cow<'_, str> {
unquote(&self.0, Component::Fragment)
}
}