use ntex_bytes::ByteString;
use crate::chars::{self, QUERY};
use crate::error::InvalidUrl;
use crate::quoting::{Component, unquote_cow};
#[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) -> ByteString {
unquote_cow(&self.0, Component::Query).into()
}
pub fn pairs(&self) -> QueryPairs<'_> {
QueryPairs(self.0.split('&'))
}
pub fn get(&self, key: &str) -> Option<ByteString> {
self.get_all(key).next()
}
pub fn get_all<'a>(&'a self, key: &'a str) -> impl Iterator<Item = ByteString> + 'a {
self.raw_values(key)
.map(|v| unquote_cow(v, Component::QueryPart).into())
}
pub fn contains_key(&self, key: &str) -> bool {
self.raw_values(key).next().is_some()
}
fn raw_values<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'a str> + 'a {
pieces(&self.0)
.map(split_pair)
.filter_map(move |(k, v)| (unquote_cow(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 Iterator for QueryPairs<'_> {
type Item = (ByteString, ByteString);
fn next(&mut self) -> Option<Self::Item> {
let (k, v) = split_pair(self.0.by_ref().find(|piece| !piece.is_empty())?);
Some((
unquote_cow(k, Component::QueryPart).into(),
unquote_cow(v, Component::QueryPart).into(),
))
}
}
#[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) -> ByteString {
unquote_cow(&self.0, Component::Fragment).into()
}
}