use super::*;
use alloc::borrow::Cow;
use alloc::string::String;
use core::borrow::Borrow;
#[inline]
fn cow_to_mut_reserve<'a>(cow: &'a mut Cow<'static, str>, additional: usize) -> &'a mut String {
match cow {
Cow::Borrowed(s) => {
let mut owned = String::with_capacity(s.len().saturating_add(additional));
owned.push_str(s);
*cow = Cow::Owned(owned);
}
Cow::Owned(s) => s.reserve(additional),
}
cow.to_mut()
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeHtml {
html: Cow<'static, str>,
}
impl SafeHtml {
pub const fn empty() -> Self {
SafeHtml {
html: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
SafeHtml {
html: Cow::Borrowed(val),
}
}
pub const fn nbsp() -> Self {
SafeHtml {
html: Cow::Borrowed(" "),
}
}
pub const fn html5_doctype_declaration() -> Self {
SafeHtml {
html: Cow::Borrowed("<!DOCTYPE html>"),
}
}
pub fn escape(text: &str) -> Self {
let mut html = String::with_capacity(text.len());
let _ = escape_html_and_coerce_to(text, &mut html);
SafeHtml {
html: Cow::Owned(html),
}
}
pub fn escape_allow_character_references(text: &str) -> Self {
let mut html = String::with_capacity(text.len());
let _ = escape_allow_character_references_to(text, &mut html);
SafeHtml {
html: Cow::Owned(html),
}
}
pub fn comment(text: &str) -> Self {
let mut html = String::with_capacity(text.len() + 7);
html.push_str("<!--");
let _ = escape_html_and_coerce_to(text, &mut html);
html.push_str("-->");
SafeHtml {
html: Cow::Owned(html),
}
}
pub unsafe fn from_string_unchecked(html: String) -> Self {
SafeHtml {
html: Cow::Owned(html),
}
}
pub fn append(&mut self, other: &SafeHtml) -> &mut Self {
cow_to_mut_reserve(&mut self.html, other.html.len()).push_str(&other.html);
self
}
pub fn escape_and_append(&mut self, text: &str) -> &mut Self {
let buf = cow_to_mut_reserve(&mut self.html, text.len());
let _ = escape_html_and_coerce_to(text, buf);
self
}
pub fn as_str(&self) -> &str {
&self.html
}
pub fn into_string(self) -> String {
self.html.into_owned()
}
pub fn to_proto(&self) -> SafeHtmlProto {
SafeHtmlProto {
private_do_not_access_or_else_safe_html_wrapped_value: alloc::string::String::from(
self.as_str(),
),
}
}
pub fn from_proto(proto: Option<&SafeHtmlProto>) -> Self {
match proto {
Some(p) => unsafe {
SafeHtml::from_string_unchecked(
p.private_do_not_access_or_else_safe_html_wrapped_value
.clone(),
)
},
None => SafeHtml::empty(),
}
}
pub fn concat<I>(iter: I) -> Self
where
I: IntoIterator,
I::Item: core::borrow::Borrow<SafeHtml>,
{
let mut html = String::new();
for item in iter {
html.push_str(item.borrow().as_str());
}
SafeHtml {
html: Cow::Owned(html),
}
}
pub fn join<I>(iter: I, separator: &SafeHtml) -> Self
where
I: IntoIterator,
I::Item: core::borrow::Borrow<SafeHtml>,
{
let mut html = String::new();
let mut first = true;
for item in iter {
if !first {
html.push_str(separator.as_str());
}
first = false;
html.push_str(item.borrow().as_str());
}
SafeHtml {
html: Cow::Owned(html),
}
}
}
impl core::fmt::Display for SafeHtml {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.html)
}
}
impl AsRef<str> for SafeHtml {
fn as_ref(&self) -> &str {
&self.html
}
}
impl core::ops::Deref for SafeHtml {
type Target = crate::SafeHtmlStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::SafeHtmlStr::from_str_unchecked(self.as_str()) }
}
}
impl From<SafeHtml> for String {
fn from(value: SafeHtml) -> Self {
value.html.into_owned()
}
}
impl<T: core::borrow::Borrow<SafeHtml>> FromIterator<T> for SafeHtml {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
SafeHtml::concat(iter)
}
}
impl core::ops::AddAssign<&SafeHtml> for SafeHtml {
fn add_assign(&mut self, rhs: &SafeHtml) {
self.append(rhs);
}
}
impl core::ops::AddAssign<SafeHtml> for SafeHtml {
fn add_assign(&mut self, rhs: SafeHtml) {
self.append(&rhs);
}
}
impl core::ops::Add<&SafeHtml> for SafeHtml {
type Output = SafeHtml;
fn add(mut self, rhs: &SafeHtml) -> Self::Output {
self += rhs;
self
}
}
impl core::ops::Add<SafeHtml> for SafeHtml {
type Output = SafeHtml;
fn add(mut self, rhs: SafeHtml) -> Self::Output {
self += &rhs;
self
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeUrl {
url: Cow<'static, str>,
}
impl SafeUrl {
pub const fn empty() -> Self {
SafeUrl {
url: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
SafeUrl {
url: Cow::Borrowed(val),
}
}
pub fn sanitize_block_only_javascript(url: &str) -> Self {
if is_safe_url_block_javascript(url) {
SafeUrl {
url: Cow::Owned(String::from(url)),
}
} else {
SafeUrl {
url: Cow::Borrowed(INNOCUOUS_URL),
}
}
}
pub fn sanitize(url: &str) -> Self {
if is_safe_url_restrictive(url) {
SafeUrl {
url: Cow::Owned(String::from(url)),
}
} else {
SafeUrl {
url: Cow::Borrowed(INNOCUOUS_URL),
}
}
}
pub fn sanitize_with_schemes<S: AsRef<str>>(url: &str, extra_schemes: &[S]) -> Self {
if is_safe_url_restrictive_with_schemes(url, extra_schemes) {
SafeUrl {
url: Cow::Owned(String::from(url)),
}
} else {
SafeUrl {
url: Cow::Borrowed(INNOCUOUS_URL),
}
}
}
pub fn sanitize_for_css(url: &str) -> Self {
if !is_safe_url_restrictive(url) {
return SafeUrl {
url: Cow::Borrowed(INNOCUOUS_URL),
};
}
let mut escaped = String::with_capacity(url.len());
let _ = percent_escape_css_url_to(url, &mut escaped);
SafeUrl {
url: Cow::Owned(escaped),
}
}
pub unsafe fn from_string_unchecked(url: String) -> Self {
SafeUrl {
url: Cow::Owned(url),
}
}
pub fn push_query_param(&mut self, name: &str, value: &str) -> &mut Self {
push_query_param_impl(&mut self.url, name, value);
self
}
pub fn as_str(&self) -> &str {
&self.url
}
pub fn into_string(self) -> String {
self.url.into_owned()
}
pub fn to_proto(&self) -> SafeUrlProto {
SafeUrlProto {
private_do_not_access_or_else_safe_url_wrapped_value: alloc::string::String::from(
self.as_str(),
),
}
}
pub fn from_proto(proto: Option<&SafeUrlProto>) -> Self {
match proto {
Some(p) => unsafe {
SafeUrl::from_string_unchecked(
p.private_do_not_access_or_else_safe_url_wrapped_value
.clone(),
)
},
None => SafeUrl::empty(),
}
}
}
fn push_query_param_impl(url: &mut Cow<'static, str>, name: &str, value: &str) {
let extra = name.len().saturating_add(value.len()).saturating_add(2);
let url = cow_to_mut_reserve(url, extra);
match url.find('#') {
None => {
let has_query = url.contains('?');
url.push(if has_query { '&' } else { '?' });
let _ = url_encode_component_to(name, &mut *url);
url.push('=');
let _ = url_encode_component_to(value, &mut *url);
}
Some(insert_at) => {
let has_query = url.get(..insert_at).unwrap_or("").contains('?');
let mut param = String::with_capacity(extra);
param.push(if has_query { '&' } else { '?' });
let _ = url_encode_component_to(name, &mut param);
param.push('=');
let _ = url_encode_component_to(value, &mut param);
url.insert_str(insert_at, ¶m);
}
}
}
impl core::fmt::Display for SafeUrl {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.url)
}
}
impl AsRef<str> for SafeUrl {
fn as_ref(&self) -> &str {
&self.url
}
}
impl core::ops::Deref for SafeUrl {
type Target = crate::SafeUrlStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::SafeUrlStr::from_str_unchecked(self.as_str()) }
}
}
impl From<SafeUrl> for String {
fn from(value: SafeUrl) -> Self {
value.url.into_owned()
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeScript {
script: Cow<'static, str>,
}
impl SafeScript {
pub const fn empty() -> Self {
SafeScript {
script: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
SafeScript {
script: Cow::Borrowed(val),
}
}
pub fn from_escaped_json(json: &str) -> Self {
let mut script = String::with_capacity(json.len());
let _ = escape_json_for_script_to(json, &mut script);
SafeScript {
script: Cow::Owned(script),
}
}
pub unsafe fn from_string_unchecked(script: String) -> Self {
SafeScript {
script: Cow::Owned(script),
}
}
pub fn as_str(&self) -> &str {
&self.script
}
pub fn into_string(self) -> String {
self.script.into_owned()
}
pub fn to_proto(&self) -> SafeScriptProto {
SafeScriptProto {
private_do_not_access_or_else_safe_script_wrapped_value: alloc::string::String::from(
self.as_str(),
),
}
}
pub fn from_proto(proto: Option<&SafeScriptProto>) -> Self {
match proto {
Some(p) => unsafe {
SafeScript::from_string_unchecked(
p.private_do_not_access_or_else_safe_script_wrapped_value
.clone(),
)
},
None => SafeScript::empty(),
}
}
}
impl core::fmt::Display for SafeScript {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.script)
}
}
impl AsRef<str> for SafeScript {
fn as_ref(&self) -> &str {
&self.script
}
}
impl core::ops::Deref for SafeScript {
type Target = crate::SafeScriptStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::SafeScriptStr::from_str_unchecked(self.as_str()) }
}
}
impl From<SafeScript> for String {
fn from(value: SafeScript) -> Self {
value.script.into_owned()
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TrustedResourceUrl {
url: Cow<'static, str>,
}
impl TrustedResourceUrl {
pub const fn empty() -> Self {
TrustedResourceUrl {
url: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
TrustedResourceUrl {
url: Cow::Borrowed(val),
}
}
pub unsafe fn from_string_unchecked(url: String) -> Self {
TrustedResourceUrl {
url: Cow::Owned(url),
}
}
pub fn push_query_param(&mut self, name: &str, value: &str) -> &mut Self {
push_query_param_impl(&mut self.url, name, value);
self
}
pub fn as_str(&self) -> &str {
&self.url
}
pub fn into_string(self) -> String {
self.url.into_owned()
}
pub fn to_proto(&self) -> TrustedResourceUrlProto {
TrustedResourceUrlProto {
private_do_not_access_or_else_trusted_resource_url_wrapped_value:
alloc::string::String::from(self.as_str()),
}
}
pub fn from_proto(proto: Option<&TrustedResourceUrlProto>) -> Self {
match proto {
Some(p) => unsafe {
TrustedResourceUrl::from_string_unchecked(
p.private_do_not_access_or_else_trusted_resource_url_wrapped_value
.clone(),
)
},
None => TrustedResourceUrl::empty(),
}
}
}
impl core::fmt::Display for TrustedResourceUrl {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.url)
}
}
impl AsRef<str> for TrustedResourceUrl {
fn as_ref(&self) -> &str {
&self.url
}
}
impl core::ops::Deref for TrustedResourceUrl {
type Target = crate::TrustedResourceUrlStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::TrustedResourceUrlStr::from_str_unchecked(self.as_str()) }
}
}
impl From<TrustedResourceUrl> for String {
fn from(value: TrustedResourceUrl) -> Self {
value.url.into_owned()
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeStyle {
style: Cow<'static, str>,
}
impl SafeStyle {
pub const fn empty() -> Self {
SafeStyle {
style: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
SafeStyle {
style: Cow::Borrowed(val),
}
}
pub fn from_properties(properties: &[(&str, &str)]) -> Self {
let mut style = SafeStyle::empty();
for (name, value) in properties {
style.push_property(name, value);
}
style
}
pub fn push_property(&mut self, name: &str, value: &str) -> &mut Self {
if !is_safe_style_property_name(name) {
return self;
}
let value = value.trim();
let value = if is_safe_style_property_value(value) {
value
} else {
INNOCUOUS_PROPERTY_VALUE
};
let buf = cow_to_mut_reserve(&mut self.style, name.len() + value.len() + 2);
buf.push_str(name);
buf.push(':');
buf.push_str(value);
buf.push(';');
self
}
pub fn push_background_image_url(&mut self, url: &str) -> &mut Self {
let checked = if is_safe_url_restrictive(url) {
url
} else {
INNOCUOUS_URL
};
let buf = cow_to_mut_reserve(&mut self.style, checked.len() + 25);
buf.push_str("background-image:url(\"");
let _ = percent_escape_css_url_to(checked, &mut *buf);
buf.push_str("\");");
self
}
pub fn append(&mut self, other: &SafeStyle) -> &mut Self {
cow_to_mut_reserve(&mut self.style, other.style.len()).push_str(&other.style);
self
}
pub unsafe fn from_string_unchecked(style: String) -> Self {
SafeStyle {
style: Cow::Owned(style),
}
}
pub fn as_str(&self) -> &str {
&self.style
}
pub fn into_string(self) -> String {
self.style.into_owned()
}
pub fn to_proto(&self) -> SafeStyleProto {
SafeStyleProto {
private_do_not_access_or_else_safe_style_wrapped_value: alloc::string::String::from(
self.as_str(),
),
}
}
pub fn from_proto(proto: Option<&SafeStyleProto>) -> Self {
match proto {
Some(p) => unsafe {
SafeStyle::from_string_unchecked(
p.private_do_not_access_or_else_safe_style_wrapped_value
.clone(),
)
},
None => SafeStyle::empty(),
}
}
}
impl core::fmt::Display for SafeStyle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.style)
}
}
impl AsRef<str> for SafeStyle {
fn as_ref(&self) -> &str {
&self.style
}
}
impl core::ops::Deref for SafeStyle {
type Target = crate::SafeStyleStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::SafeStyleStr::from_str_unchecked(self.as_str()) }
}
}
impl From<SafeStyle> for String {
fn from(value: SafeStyle) -> Self {
value.style.into_owned()
}
}
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeStyleSheet {
sheet: Cow<'static, str>,
}
impl SafeStyleSheet {
pub const fn empty() -> Self {
SafeStyleSheet {
sheet: Cow::Borrowed(""),
}
}
pub const fn from_constant(val: &'static str) -> Self {
SafeStyleSheet {
sheet: Cow::Borrowed(val),
}
}
pub fn from_style_rule(selector: &str, style: &SafeStyle) -> Option<Self> {
if !is_safe_css_selector(selector) {
return None;
}
let mut sheet = String::with_capacity(selector.len() + style.as_str().len() + 2);
sheet.push_str(selector);
sheet.push('{');
sheet.push_str(style.as_str());
sheet.push('}');
Some(SafeStyleSheet {
sheet: Cow::Owned(sheet),
})
}
pub fn append(&mut self, other: &SafeStyleSheet) -> &mut Self {
cow_to_mut_reserve(&mut self.sheet, other.sheet.len()).push_str(&other.sheet);
self
}
pub unsafe fn from_string_unchecked(sheet: String) -> Self {
SafeStyleSheet {
sheet: Cow::Owned(sheet),
}
}
pub fn as_str(&self) -> &str {
&self.sheet
}
pub fn into_string(self) -> String {
self.sheet.into_owned()
}
pub fn to_proto(&self) -> SafeStyleSheetProto {
SafeStyleSheetProto {
private_do_not_access_or_else_safe_style_sheet_wrapped_value:
alloc::string::String::from(self.as_str()),
}
}
pub fn from_proto(proto: Option<&SafeStyleSheetProto>) -> Self {
match proto {
Some(p) => unsafe {
SafeStyleSheet::from_string_unchecked(
p.private_do_not_access_or_else_safe_style_sheet_wrapped_value
.clone(),
)
},
None => SafeStyleSheet::empty(),
}
}
}
impl core::fmt::Display for SafeStyleSheet {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.sheet)
}
}
impl AsRef<str> for SafeStyleSheet {
fn as_ref(&self) -> &str {
&self.sheet
}
}
impl core::ops::Deref for SafeStyleSheet {
type Target = crate::SafeStyleSheetStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::SafeStyleSheetStr::from_str_unchecked(self.as_str()) }
}
}
impl From<SafeStyleSheet> for String {
fn from(value: SafeStyleSheet) -> Self {
value.sheet.into_owned()
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Identifier {
id: Cow<'static, str>,
}
impl Identifier {
pub const fn from_constant(val: &'static str) -> Self {
assert!(
is_safe_identifier(val),
"Identifier::from_constant requires [A-Za-z][A-Za-z0-9_-]*"
);
Identifier {
id: Cow::Borrowed(val),
}
}
pub fn try_from_value(value: &str) -> Option<Identifier> {
if is_safe_identifier(value) {
Some(Identifier {
id: Cow::Owned(String::from(value)),
})
} else {
None
}
}
pub fn try_with_constant_prefix(prefix: &'static str, value: &str) -> Option<Identifier> {
if !is_safe_identifier(prefix)
|| value.is_empty()
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return None;
}
let mut id = String::with_capacity(prefix.len() + 1 + value.len());
id.push_str(prefix);
id.push('-');
id.push_str(value);
Some(Identifier { id: Cow::Owned(id) })
}
pub unsafe fn from_string_unchecked(id: String) -> Self {
Identifier { id: Cow::Owned(id) }
}
pub fn as_str(&self) -> &str {
&self.id
}
pub fn into_string(self) -> String {
self.id.into_owned()
}
}
impl core::fmt::Display for Identifier {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.id)
}
}
impl AsRef<str> for Identifier {
fn as_ref(&self) -> &str {
&self.id
}
}
impl core::ops::Deref for Identifier {
type Target = crate::IdentifierStr;
fn deref(&self) -> &Self::Target {
unsafe { crate::IdentifierStr::from_str_unchecked(self.as_str()) }
}
}
impl From<Identifier> for String {
fn from(value: Identifier) -> Self {
value.id.into_owned()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeHtmlProto {
pub private_do_not_access_or_else_safe_html_wrapped_value: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeUrlProto {
pub private_do_not_access_or_else_safe_url_wrapped_value: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeScriptProto {
pub private_do_not_access_or_else_safe_script_wrapped_value: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedResourceUrlProto {
pub private_do_not_access_or_else_trusted_resource_url_wrapped_value: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeStyleProto {
pub private_do_not_access_or_else_safe_style_wrapped_value: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeStyleSheetProto {
pub private_do_not_access_or_else_safe_style_sheet_wrapped_value: String,
}