use crate::{builder_fn, AutoDefault, CowStr};
use std::fmt;
#[derive(AutoDefault)]
pub struct RoutePath {
path: CowStr,
query: indexmap::IndexMap<String, String>,
}
impl RoutePath {
pub fn new(path: impl Into<CowStr>) -> Self {
Self {
path: path.into(),
query: indexmap::IndexMap::new(),
}
}
#[builder_fn]
pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.query.insert(key.into(), value.into());
self
}
#[builder_fn]
pub fn with_flag(mut self, flag: impl Into<String>) -> Self {
self.query.insert(flag.into(), String::new());
self
}
pub fn path(&self) -> &str {
&self.path
}
}
impl fmt::Display for RoutePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.path)?;
if !self.query.is_empty() {
f.write_str("?")?;
for (i, (key, value)) in self.query.iter().enumerate() {
if i > 0 {
f.write_str("&")?;
}
f.write_str(key)?;
if !value.is_empty() {
f.write_str("=")?;
f.write_str(value)?;
}
}
}
Ok(())
}
}
impl From<&'static str> for RoutePath {
fn from(path: &'static str) -> Self {
RoutePath::new(path)
}
}
impl From<String> for RoutePath {
fn from(path: String) -> Self {
RoutePath::new(path)
}
}