Implement encodeURIComponent filter.

This commit is contained in:
Tom Alexander 2020-05-23 19:10:02 -04:00
parent 46d4f50410
commit bd7866e973
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
2 changed files with 34 additions and 4 deletions

View File

@ -32,3 +32,9 @@ Special characters html escaping disabled and encodeURI: {special_characters|s|u
Special characters encodeURI and html escaping disabled: {special_characters|u|s}{~n}
Special characters encodeURI once: {special_characters|u}{~n}
Special characters encodeURI twice: {special_characters|u|u}{~n}
Special characters: {special_characters}{~n}
Special characters html escaping disabled and encodeURIComponent: {special_characters|s|uc}{~n}
Special characters encodeURIComponent and html escaping disabled: {special_characters|uc|s}{~n}
Special characters encodeURIComponent once: {special_characters|uc}{~n}
Special characters encodeURIComponent twice: {special_characters|uc|uc}{~n}

View File

@ -139,6 +139,26 @@ fn encode_uri(inp: &str) -> String {
output
}
fn encode_uri_component(inp: &str) -> String {
// Adding 10% space from the original to avoid re-allocations by
// leaving room for escaped sequences.
let mut output = String::with_capacity(((inp.len() as f64) * 1.1) as usize);
inp.chars().for_each(|c| match c {
'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e'
| 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's'
| 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G'
| 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U'
| 'V' | 'W' | 'X' | 'Y' | 'Z' | '-' | '_' | '.' | '!' | '~' | '*' | '\'' | '(' | ')' => {
output.push(c)
}
_ => {
output.push('%');
output.push_str(&get_utf8_hex(c));
}
});
output
}
fn apply_filter(
json_value: &serde_json::Value,
filter: &Filter,
@ -172,16 +192,20 @@ fn apply_filter(
(_, Filter::JavascriptStringEncode) => Ok(serde_json::Value::String(javascript_escape(
&json_value.render(&Vec::new())?,
))),
// EncodeUri filter
// EncodeURI filter
(serde_json::Value::String(string), Filter::EncodeUri) => {
Ok(serde_json::Value::String(encode_uri(string)))
}
(_, Filter::EncodeUri) => Ok(serde_json::Value::String(encode_uri(
&json_value.render(&Vec::new())?,
))),
// TODO: EncodeUriComponent
_ => panic!("Unimplemented"),
// EncodeURIComponent filter
(serde_json::Value::String(string), Filter::EncodeUriComponent) => {
Ok(serde_json::Value::String(encode_uri_component(string)))
}
(_, Filter::EncodeUriComponent) => Ok(serde_json::Value::String(encode_uri_component(
&json_value.render(&Vec::new())?,
))),
}
}