use alloc::string::{String, ToString};
use core::fmt;
use core::marker::PhantomData;
pub trait Context {
const NAME: &'static str;
}
macro_rules! contexts {
($($(#[$doc:meta])* $marker:ident => $name:literal),* $(,)?) => {$(
$(#[$doc])*
#[derive(Clone, Copy, Debug)]
pub enum $marker {}
impl Context for $marker {
const NAME: &'static str = $name;
}
)*};
}
contexts! {
UrlContext => "url",
SrcsetContext => "srcset",
ScriptContext => "script",
StyleContext => "style",
DocumentContext => "document",
NavigationContext => "navigation",
ResourceContext => "resource",
AnimationContext => "animation",
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a checked URL, so it cannot be the whole value of a URL attribute",
label = "a string could hold a `javascript:` URL",
note = "parse it with `hemplate::Url::parse(..)` and handle the error, or start the attribute with fixed text such as `/`, `?`, `#` or `https://`",
note = "for a scheme such as `data:` or `sms:`, vouch for it explicitly with `hemplate::TrustedUrl::new_unchecked(..)`"
)]
pub trait UrlValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into a `srcset` attribute",
label = "every candidate in a srcset must be a checked URL",
note = "build a `hemplate::Srcset` from checked `hemplate::Url` values",
note = "or vouch for a list explicitly with `hemplate::TrustedSrcset::new_unchecked(..)`"
)]
pub trait SrcsetValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into an event-handler attribute (`on*`)",
label = "this value would be run as JavaScript",
note = "HTML escaping does not make a value safe as code: the browser decodes the attribute before running it",
note = "pass data in a `data-*` attribute and read it from a script, or use a Hemx handle",
note = "code you wrote yourself can be vouched for with `hemplate::TrustedScript::new_unchecked(..)`"
)]
pub trait ScriptValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into a `style` attribute",
label = "this value would be read as CSS",
note = "a `;` ends the property, so a value can add others such as `background: url(..)` that fetch a URL",
note = "choose among fixed styles with `+class=\"..\"`, or implement `hemplate::StyleValue` for a type that can only build valid values",
note = "or vouch for CSS explicitly with `hemplate::TrustedStyle::new_unchecked(..)`"
)]
pub trait StyleValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into a `srcdoc` attribute",
label = "this value would be parsed as a whole HTML document",
note = "serve the document from its own URL and use `src`, or vouch for it with `hemplate::TrustedDocument::new_unchecked(..)`"
)]
pub trait DocumentValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into `<base href>` or `<meta http-equiv>`",
label = "this value changes how the whole page navigates or behaves",
note = "use fixed text, or vouch for the value with `hemplate::TrustedNavigation::new_unchecked(..)`"
)]
pub trait NavigationValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into a URL that loads script, styles or plug-ins",
label = "even an `https:` URL would run code or styles from wherever it points",
note = "use a fixed URL, or a type implementing `hemplate::ResourceValue` that can only name files you serve",
note = "or vouch for the URL with `hemplate::TrustedResource::new_unchecked(..)`"
)]
pub trait ResourceValue: fmt::Display {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be interpolated into an SVG animation attribute",
label = "an animation can set `href` to a `javascript:` URL",
note = "use fixed values, or vouch for them with `hemplate::TrustedAnimation::new_unchecked(..)`"
)]
pub trait AnimationValue: fmt::Display {}
macro_rules! forward_refs {
($($trait:ident),* $(,)?) => {$(
#[diagnostic::do_not_recommend]
impl<T: $trait + ?Sized> $trait for &T {}
)*};
}
forward_refs!(
UrlValue,
SrcsetValue,
ScriptValue,
StyleValue,
DocumentValue,
NavigationValue,
ResourceValue,
AnimationValue,
);
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Trusted<C: Context> {
value: String,
context: PhantomData<fn() -> C>,
}
impl<C: Context> Trusted<C> {
pub fn new_unchecked(value: impl Into<String>) -> Self {
Self {
value: value.into(),
context: PhantomData,
}
}
pub fn as_str(&self) -> &str {
&self.value
}
}
impl<C: Context> fmt::Display for Trusted<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.value)
}
}
impl<C: Context> fmt::Debug for Trusted<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Trusted<{}>({:?})", C::NAME, self.value)
}
}
pub type TrustedUrl = Trusted<UrlContext>;
pub type TrustedSrcset = Trusted<SrcsetContext>;
pub type TrustedScript = Trusted<ScriptContext>;
pub type TrustedStyle = Trusted<StyleContext>;
pub type TrustedDocument = Trusted<DocumentContext>;
pub type TrustedNavigation = Trusted<NavigationContext>;
pub type TrustedResource = Trusted<ResourceContext>;
pub type TrustedAnimation = Trusted<AnimationContext>;
#[diagnostic::do_not_recommend]
impl UrlValue for Trusted<UrlContext> {}
#[diagnostic::do_not_recommend]
impl SrcsetValue for Trusted<SrcsetContext> {}
#[diagnostic::do_not_recommend]
impl ScriptValue for Trusted<ScriptContext> {}
#[diagnostic::do_not_recommend]
impl StyleValue for Trusted<StyleContext> {}
#[diagnostic::do_not_recommend]
impl DocumentValue for Trusted<DocumentContext> {}
#[diagnostic::do_not_recommend]
impl NavigationValue for Trusted<NavigationContext> {}
#[diagnostic::do_not_recommend]
impl ResourceValue for Trusted<ResourceContext> {}
#[diagnostic::do_not_recommend]
impl AnimationValue for Trusted<AnimationContext> {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UrlError {
DisallowedScheme(String),
ControlCharacter,
NotSrcsetSafe,
InvalidDensity,
}
impl fmt::Display for UrlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DisallowedScheme(scheme) => write!(
f,
"URL scheme `{scheme}` is not allowed (http, https, mailto and tel are)"
),
Self::ControlCharacter => f.write_str("URL contains a control character"),
Self::NotSrcsetSafe => f.write_str("URL contains whitespace or a comma"),
Self::InvalidDensity => f.write_str("srcset density must be a positive finite number"),
}
}
}
impl core::error::Error for UrlError {}
const ALLOWED_SCHEMES: [&str; 4] = ["http", "https", "mailto", "tel"];
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Url(String);
impl Url {
pub fn parse(input: &str) -> Result<Self, UrlError> {
let stripped: String = input
.chars()
.filter(|c| !matches!(c, '\t' | '\n' | '\r'))
.collect();
let trimmed = stripped.trim_matches(|c: char| c <= ' ');
if trimmed.chars().any(|c| c.is_ascii_control()) {
return Err(UrlError::ControlCharacter);
}
if let Some(scheme) = scheme_of(trimmed) {
let scheme = scheme.to_ascii_lowercase();
if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
return Err(UrlError::DisallowedScheme(scheme));
}
}
Ok(Self(trimmed.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
fn scheme_of(url: &str) -> Option<&str> {
let mut chars = url.char_indices();
match chars.next() {
Some((_, first)) if first.is_ascii_alphabetic() => {}
_ => return None,
}
for (index, c) in chars {
match c {
':' => return Some(&url[..index]),
c if c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.') => {}
_ => return None,
}
}
None
}
impl fmt::Display for Url {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for Url {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Url({:?})", self.0)
}
}
impl core::str::FromStr for Url {
type Err = UrlError;
fn from_str(input: &str) -> Result<Self, UrlError> {
Self::parse(input)
}
}
impl TryFrom<&str> for Url {
type Error = UrlError;
fn try_from(input: &str) -> Result<Self, UrlError> {
Self::parse(input)
}
}
#[diagnostic::do_not_recommend]
impl UrlValue for Url {}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Descriptor {
Width(u32),
Density(f32),
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct Srcset(String);
impl Srcset {
pub fn new() -> Self {
Self::default()
}
pub fn candidate(
mut self,
url: &Url,
descriptor: Option<Descriptor>,
) -> Result<Self, UrlError> {
if url.as_str().chars().any(|c| c.is_whitespace() || c == ',') {
return Err(UrlError::NotSrcsetSafe);
}
if let Some(Descriptor::Density(density)) = descriptor
&& (!density.is_finite() || density <= 0.0)
{
return Err(UrlError::InvalidDensity);
}
if !self.0.is_empty() {
self.0.push_str(", ");
}
self.0.push_str(url.as_str());
match descriptor {
Some(Descriptor::Width(width)) => {
self.0.push(' ');
self.0.push_str(&width.to_string());
self.0.push('w');
}
Some(Descriptor::Density(density)) => {
self.0.push(' ');
self.0.push_str(&density.to_string());
self.0.push('x');
}
None => {}
}
Ok(self)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Srcset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for Srcset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Srcset({:?})", self.0)
}
}
#[diagnostic::do_not_recommend]
impl SrcsetValue for Srcset {}