Skip to content

Commit

Permalink
use trait to avoid escaping numbers and bools at runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
Pitasi committed Sep 9, 2023
1 parent 459756e commit 593a36c
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 8 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ members = [
]

[workspace.package]
version = "0.1.5"
version = "0.1.6"

[workspace.dependencies]
rscx = { path = "./rscx", version = "0.1.5" }
rscx-macros = { path = "./rscx-macros", version = "0.1.5" }
rscx = { path = "./rscx", version = "0.1.6" }
rscx-macros = { path = "./rscx-macros", version = "0.1.6" }
31 changes: 31 additions & 0 deletions benches/benches/benchmark.rs

Large diffs are not rendered by default.

26 changes: 21 additions & 5 deletions rscx-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,14 +251,30 @@ fn walk_attribute(attribute: &KeyedAttribute) -> (String, Option<proc_macro2::To
html_escape::encode_unquoted_attribute(&value.value())
));
}
Some(Expr::Lit(ExprLit {
lit: syn::Lit::Bool(value),
..
})) => {
static_format.push_str(&format!(r#"="{}""#, value.value()));
}
Some(Expr::Lit(ExprLit {
lit: syn::Lit::Int(value),
..
})) => {
static_format.push_str(&format!(r#"="{}""#, value.token()));
}
Some(Expr::Lit(ExprLit {
lit: syn::Lit::Float(value),
..
})) => {
static_format.push_str(&format!(r#"="{}""#, value.token()));
}
Some(value) => {
static_format.push_str(r#"="{}""#);
format_value = Some(
quote! {
::rscx::html_escape::encode_double_quoted_attribute(
&format!("{}", #value)
)
}
quote! {{
(#value).escape_attribute()
}}
.into_token_stream(),
);
}
Expand Down
35 changes: 35 additions & 0 deletions rscx/src/attributes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::borrow::Cow;

use html_escape::encode_unquoted_attribute;

pub trait EscapeAttribute {
fn escape_attribute(&self) -> Cow<str>;
}

impl EscapeAttribute for str {
fn escape_attribute(&self) -> Cow<str> {
encode_unquoted_attribute(self)
}
}

impl EscapeAttribute for String {
fn escape_attribute(&self) -> Cow<str> {
encode_unquoted_attribute(self)
}
}

macro_rules! impl_escape_attribute_literal {
($($t:ty),*) => {
$(
impl EscapeAttribute for $t {
fn escape_attribute(&self) -> Cow<str> {
Cow::Owned(self.to_string())
}
}
)*
};
}

impl_escape_attribute_literal!(
u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, bool
);
3 changes: 3 additions & 0 deletions rscx/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
pub mod attributes;
pub use attributes::*;

#[cfg(feature = "axum")]
pub mod axum;
pub mod context;
Expand Down

0 comments on commit 593a36c

Please sign in to comment.