diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
commit | 36d22d82aa202bb199967e9512281e9a53db42c9 (patch) | |
tree | 105e8c98ddea1c1e4784a60a5a6410fa416be2de /third_party/rust/askama_escape | |
parent | Initial commit. (diff) | |
download | firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.tar.xz firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.zip |
Adding upstream version 115.7.0esr.upstream/115.7.0esr
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/askama_escape')
-rw-r--r-- | third_party/rust/askama_escape/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/askama_escape/Cargo.toml | 33 | ||||
-rw-r--r-- | third_party/rust/askama_escape/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/askama_escape/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/askama_escape/README.md | 9 | ||||
-rw-r--r-- | third_party/rust/askama_escape/benches/all.rs | 77 | ||||
-rw-r--r-- | third_party/rust/askama_escape/src/lib.rs | 239 |
7 files changed, 585 insertions, 0 deletions
diff --git a/third_party/rust/askama_escape/.cargo-checksum.json b/third_party/rust/askama_escape/.cargo-checksum.json new file mode 100644 index 0000000000..b4c6a0e725 --- /dev/null +++ b/third_party/rust/askama_escape/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"a140f9df40d83c3f3c39864df0e272bde3e210ad9d37cf90342c45f137c5b1aa","LICENSE-APACHE":"87cb0d734c723c083e51c825930ff42bce28596b52dee15567f6b28f19c195e3","LICENSE-MIT":"df20e0180764bf5bd76f74d47bc9e8c0069a666401629c390003a1d5eba99c92","README.md":"f1c057bd94aff0d98bcd7267655bb8af4c9c81a643423c5948f711e199945905","benches/all.rs":"0e0458780fa24e55402b11fdbc6ef2191b399459461a9f909a516363e824c838","src/lib.rs":"5f96ad55ac916b63ef051373994c08a0bfaa3b85a5bf031a579dc23163c47267"},"package":"619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341"}
\ No newline at end of file diff --git a/third_party/rust/askama_escape/Cargo.toml b/third_party/rust/askama_escape/Cargo.toml new file mode 100644 index 0000000000..d4944ed6ea --- /dev/null +++ b/third_party/rust/askama_escape/Cargo.toml @@ -0,0 +1,33 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "askama_escape" +version = "0.10.3" +description = "Optimized HTML escaping code, extracted from Askama" +homepage = "https://github.com/djc/askama" +documentation = "https://docs.rs/askama_escape" +readme = "README.md" +keywords = ["html", "escaping"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/djc/askama" + +[[bench]] +name = "all" +harness = false +[dev-dependencies.criterion] +version = "0.3" + +[features] +json = [] +[badges.maintenance] +status = "actively-developed" diff --git a/third_party/rust/askama_escape/LICENSE-APACHE b/third_party/rust/askama_escape/LICENSE-APACHE new file mode 100644 index 0000000000..b7ca568694 --- /dev/null +++ b/third_party/rust/askama_escape/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2017-2020 Dirkjan Ochtman + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/askama_escape/LICENSE-MIT b/third_party/rust/askama_escape/LICENSE-MIT new file mode 100644 index 0000000000..c765f2e75a --- /dev/null +++ b/third_party/rust/askama_escape/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017-2020 Dirkjan Ochtman + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/askama_escape/README.md b/third_party/rust/askama_escape/README.md new file mode 100644 index 0000000000..8c6796d83b --- /dev/null +++ b/third_party/rust/askama_escape/README.md @@ -0,0 +1,9 @@ +# askama_escape: escaping utilities for the Askama templating engine + +[![Documentation](https://docs.rs/askama_escape/badge.svg)](https://docs.rs/askama_escape/) +[![Latest version](https://img.shields.io/crates/v/askama_escape.svg)](https://crates.io/crates/askama_escape) +[![Build Status](https://github.com/djc/askama/workflows/CI/badge.svg)](https://github.com/djc/askama/actions?query=workflow%3ACI) +[![Chat](https://badges.gitter.im/gitterHQ/gitter.svg)](https://gitter.im/djc/askama) + +This crate contains helper code for HTML escaping used by the +[Askama](https://github.com/djc/askama) templating engine. diff --git a/third_party/rust/askama_escape/benches/all.rs b/third_party/rust/askama_escape/benches/all.rs new file mode 100644 index 0000000000..e0ef11f123 --- /dev/null +++ b/third_party/rust/askama_escape/benches/all.rs @@ -0,0 +1,77 @@ +#[macro_use] +extern crate criterion; + +use askama_escape::{Html, MarkupDisplay}; +use criterion::Criterion; + +criterion_main!(benches); +criterion_group!(benches, functions); + +fn functions(c: &mut Criterion) { + c.bench_function("Escaping", escaping); +} + +fn escaping(b: &mut criterion::Bencher<'_>) { + let string_long = r#" + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat tellus sit + amet ornare fermentum. Etiam nec erat ante. In at metus a orci mollis scelerisque. + Sed eget ultrices turpis, at sollicitudin erat. Integer hendrerit nec magna quis + venenatis. Vivamus non dolor hendrerit, vulputate velit sed, varius nunc. Quisque + in pharetra mi. Sed ullamcorper nibh malesuada commodo porttitor. Ut scelerisque + sodales felis quis dignissim. Morbi aliquam finibus justo, sit amet consectetur + mauris efficitur sit amet. Donec posuere turpis felis, eu lacinia magna accumsan + quis. Fusce egestas lacus vel fermentum tincidunt. Phasellus a nulla eget lectus + placerat commodo at eget nisl. Fusce cursus dui quis purus accumsan auctor. + Donec iaculis felis quis metus consectetur porttitor. +<p> + Etiam nibh mi, <b>accumsan</b> quis purus sed, posuere fermentum lorem. In pulvinar porta + maximus. Fusce tincidunt lacinia tellus sit amet tincidunt. Aliquam lacus est, pulvinar + non metus a, <b>facilisis</b> ultrices quam. Nulla feugiat leo in cursus eleifend. Suspendisse + eget nisi ac justo sagittis interdum id a ipsum. Nulla mauris justo, scelerisque ac + rutrum vitae, consequat vel ex. +</p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p></p> +<p> + Sed sollicitudin <b>sem</b> mauris, at rutrum nibh egestas vel. Ut eu nisi tellus. Praesent dignissim + orci elementum, mattis turpis eget, maximus ante. Suspendisse luctus eu felis a tempor. Morbi + ac risus vitae sem molestie ullamcorper. Curabitur ligula augue, sollicitudin quis maximus vel, + facilisis sed nibh. Aenean auctor magna sem, id rutrum metus convallis quis. Nullam non arcu + dictum, lobortis erat quis, rhoncus est. Suspendisse venenatis, mi sed venenatis vehicula, + tortor dolor egestas lectus, et efficitur turpis odio non augue. Integer velit sapien, dictum + non egestas vitae, hendrerit sed quam. Phasellus a nunc eu erat varius imperdiet. Etiam id + sollicitudin turpis, vitae molestie orci. Quisque ornare magna quis metus rhoncus commodo. + Phasellus non mauris velit. +</p> +<p> + Etiam dictum tellus ipsum, nec varius quam ornare vel. Cras vehicula diam nec sollicitudin + ultricies. Pellentesque rhoncus sagittis nisl id facilisis. Nunc viverra convallis risus ut + luctus. Aliquam vestibulum <b>efficitur massa</b>, id tempus nisi posuere a. Aliquam scelerisque + elit justo. Nullam a ante felis. Cras vitae lorem eu nisi feugiat hendrerit. Maecenas vitae + suscipit leo, lacinia dignissim lacus. Sed eget volutpat mi. In eu bibendum neque. Pellentesque + finibus velit a fermentum rhoncus. Maecenas leo purus, eleifend eu lacus a, condimentum sagittis + justo. +</p>"#; + let string_short = "Lorem ipsum dolor sit amet,<foo>bar&foo\"bar\\foo/bar"; + let empty = ""; + let no_escape = "Lorem ipsum dolor sit amet,"; + let no_escape_long = r#" +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin scelerisque eu urna in aliquet. +Phasellus ac nulla a urna sagittis consequat id quis est. Nullam eu ex eget erat accumsan dictum +ac lobortis urna. Etiam fermentum ut quam at dignissim. Curabitur vestibulum luctus tellus, sit +amet lobortis augue tempor faucibus. Nullam sed felis eget odio elementum euismod in sit amet massa. +Vestibulum sagittis purus sit amet eros auctor, sit amet pharetra purus dapibus. Donec ornare metus +vel dictum porta. Etiam ut nisl nisi. Nullam rutrum porttitor mi. Donec aliquam ac ipsum eget +hendrerit. Cras faucibus, eros ut pharetra imperdiet, est tellus aliquet felis, eget convallis +lacus ipsum eget quam. Vivamus orci lorem, maximus ac mi eget, bibendum vulputate massa. In +vestibulum dui hendrerit, vestibulum lacus sit amet, posuere erat. Vivamus euismod massa diam, +vulputate euismod lectus vestibulum nec. Donec sit amet massa magna. Nunc ipsum nulla, euismod +quis lacus at, gravida maximus elit. Duis tristique, nisl nullam. + "#; + + b.iter(|| { + format!("{}", MarkupDisplay::new_unsafe(string_long, Html)); + format!("{}", MarkupDisplay::new_unsafe(string_short, Html)); + format!("{}", MarkupDisplay::new_unsafe(empty, Html)); + format!("{}", MarkupDisplay::new_unsafe(no_escape, Html)); + format!("{}", MarkupDisplay::new_unsafe(no_escape_long, Html)); + }); +} diff --git a/third_party/rust/askama_escape/src/lib.rs b/third_party/rust/askama_escape/src/lib.rs new file mode 100644 index 0000000000..1788843086 --- /dev/null +++ b/third_party/rust/askama_escape/src/lib.rs @@ -0,0 +1,239 @@ +#![cfg_attr(not(any(feature = "json", test)), no_std)] +#![deny(elided_lifetimes_in_paths)] +#![deny(unreachable_pub)] + +use core::fmt::{self, Display, Formatter, Write}; +use core::str; + +#[derive(Debug)] +pub struct MarkupDisplay<E, T> +where + E: Escaper, + T: Display, +{ + value: DisplayValue<T>, + escaper: E, +} + +impl<E, T> MarkupDisplay<E, T> +where + E: Escaper, + T: Display, +{ + pub fn new_unsafe(value: T, escaper: E) -> Self { + Self { + value: DisplayValue::Unsafe(value), + escaper, + } + } + + pub fn new_safe(value: T, escaper: E) -> Self { + Self { + value: DisplayValue::Safe(value), + escaper, + } + } + + #[must_use] + pub fn mark_safe(mut self) -> MarkupDisplay<E, T> { + self.value = match self.value { + DisplayValue::Unsafe(t) => DisplayValue::Safe(t), + _ => self.value, + }; + self + } +} + +impl<E, T> Display for MarkupDisplay<E, T> +where + E: Escaper, + T: Display, +{ + fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { + match self.value { + DisplayValue::Unsafe(ref t) => write!( + EscapeWriter { + fmt, + escaper: &self.escaper + }, + "{}", + t + ), + DisplayValue::Safe(ref t) => t.fmt(fmt), + } + } +} + +#[derive(Debug)] +pub struct EscapeWriter<'a, E, W> { + fmt: W, + escaper: &'a E, +} + +impl<E, W> Write for EscapeWriter<'_, E, W> +where + W: Write, + E: Escaper, +{ + fn write_str(&mut self, s: &str) -> fmt::Result { + self.escaper.write_escaped(&mut self.fmt, s) + } +} + +pub fn escape<E>(string: &str, escaper: E) -> Escaped<'_, E> +where + E: Escaper, +{ + Escaped { string, escaper } +} + +#[derive(Debug)] +pub struct Escaped<'a, E> +where + E: Escaper, +{ + string: &'a str, + escaper: E, +} + +impl<E> Display for Escaped<'_, E> +where + E: Escaper, +{ + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + self.escaper.write_escaped(fmt, self.string) + } +} + +pub struct Html; + +macro_rules! escaping_body { + ($start:ident, $i:ident, $fmt:ident, $bytes:ident, $quote:expr) => {{ + if $start < $i { + $fmt.write_str(unsafe { str::from_utf8_unchecked(&$bytes[$start..$i]) })?; + } + $fmt.write_str($quote)?; + $start = $i + 1; + }}; +} + +impl Escaper for Html { + fn write_escaped<W>(&self, mut fmt: W, string: &str) -> fmt::Result + where + W: Write, + { + let bytes = string.as_bytes(); + let mut start = 0; + for (i, b) in bytes.iter().enumerate() { + if b.wrapping_sub(b'"') <= FLAG { + match *b { + b'<' => escaping_body!(start, i, fmt, bytes, "<"), + b'>' => escaping_body!(start, i, fmt, bytes, ">"), + b'&' => escaping_body!(start, i, fmt, bytes, "&"), + b'"' => escaping_body!(start, i, fmt, bytes, """), + b'\'' => escaping_body!(start, i, fmt, bytes, "'"), + _ => (), + } + } + } + if start < bytes.len() { + fmt.write_str(unsafe { str::from_utf8_unchecked(&bytes[start..]) }) + } else { + Ok(()) + } + } +} + +pub struct Text; + +impl Escaper for Text { + fn write_escaped<W>(&self, mut fmt: W, string: &str) -> fmt::Result + where + W: Write, + { + fmt.write_str(string) + } +} + +#[derive(Debug, PartialEq)] +enum DisplayValue<T> +where + T: Display, +{ + Safe(T), + Unsafe(T), +} + +pub trait Escaper { + fn write_escaped<W>(&self, fmt: W, string: &str) -> fmt::Result + where + W: Write; +} + +const FLAG: u8 = b'>' - b'"'; + +/// Escape chevrons, ampersand and apostrophes for use in JSON +#[cfg(feature = "json")] +#[derive(Debug, Clone, Default)] +pub struct JsonEscapeBuffer(Vec<u8>); + +#[cfg(feature = "json")] +impl JsonEscapeBuffer { + pub fn new() -> Self { + Self(Vec::new()) + } + + pub fn finish(self) -> String { + unsafe { String::from_utf8_unchecked(self.0) } + } +} + +#[cfg(feature = "json")] +impl std::io::Write for JsonEscapeBuffer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { + macro_rules! push_esc_sequence { + ($start:ident, $i:ident, $self:ident, $bytes:ident, $quote:expr) => {{ + if $start < $i { + $self.0.extend_from_slice(&$bytes[$start..$i]); + } + $self.0.extend_from_slice($quote); + $start = $i + 1; + }}; + } + + self.0.reserve(bytes.len()); + let mut start = 0; + for (i, b) in bytes.iter().enumerate() { + match *b { + b'&' => push_esc_sequence!(start, i, self, bytes, br#"\u0026"#), + b'\'' => push_esc_sequence!(start, i, self, bytes, br#"\u0027"#), + b'<' => push_esc_sequence!(start, i, self, bytes, br#"\u003c"#), + b'>' => push_esc_sequence!(start, i, self, bytes, br#"\u003e"#), + _ => (), + } + } + if start < bytes.len() { + self.0.extend_from_slice(&bytes[start..]); + } + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::string::ToString; + + #[test] + fn test_escape() { + assert_eq!(escape("", Html).to_string(), ""); + assert_eq!(escape("<&>", Html).to_string(), "<&>"); + assert_eq!(escape("bla&", Html).to_string(), "bla&"); + assert_eq!(escape("<foo", Html).to_string(), "<foo"); + assert_eq!(escape("bla&h", Html).to_string(), "bla&h"); + } +} |