rinja-0.3.5/.cargo_vcs_info.json0000644000000001430000000000100121420ustar { "git": { "sha1": "f6acf786b09359688907fc7634dd84824f017258" }, "path_in_vcs": "rinja" }rinja-0.3.5/Cargo.toml0000644000000045750000000000100101550ustar # 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 = "2021" rust-version = "1.71" name = "rinja" version = "0.3.5" build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Type-safe, compiled Jinja-like templates for Rust" homepage = "https://rinja.readthedocs.io/" documentation = "https://docs.rs/rinja" readme = "README.md" keywords = [ "markup", "template", "jinja2", "html", ] categories = ["template-engine"] license = "MIT OR Apache-2.0" repository = "https://github.com/rinja-rs/rinja" [package.metadata.docs.rs] features = ["full"] rustdoc-args = [ "--generate-link-to-definition", "--cfg=docsrs", ] [lib] name = "rinja" path = "src/lib.rs" [[bench]] name = "escape" path = "benches/escape.rs" harness = false [[bench]] name = "to-json" path = "benches/to-json.rs" harness = false required-features = ["serde_json"] [dependencies.humansize] version = "2" optional = true [dependencies.itoa] version = "1.0.11" [dependencies.num-traits] version = "0.2.6" optional = true [dependencies.percent-encoding] version = "2.1.0" optional = true [dependencies.rinja_derive] version = "=0.3.5" [dependencies.serde] version = "1.0" optional = true [dependencies.serde_json] version = "1.0" optional = true [dev-dependencies.criterion] version = "0.5" [features] code-in-doc = ["rinja_derive/code-in-doc"] config = ["rinja_derive/config"] default = [ "config", "humansize", "urlencode", ] full = [ "default", "code-in-doc", "serde_json", ] humansize = [ "rinja_derive/humansize", "dep:humansize", ] serde_json = [ "rinja_derive/serde_json", "dep:serde", "dep:serde_json", ] urlencode = [ "rinja_derive/urlencode", "dep:percent-encoding", ] with-actix-web = ["rinja_derive/with-actix-web"] with-axum = ["rinja_derive/with-axum"] with-rocket = ["rinja_derive/with-rocket"] with-warp = ["rinja_derive/with-warp"] [badges.maintenance] status = "actively-developed" rinja-0.3.5/Cargo.toml.orig000064400000000000000000000033551046102023000136310ustar 00000000000000[package] name = "rinja" version = "0.3.5" description = "Type-safe, compiled Jinja-like templates for Rust" documentation = "https://docs.rs/rinja" keywords = ["markup", "template", "jinja2", "html"] categories = ["template-engine"] homepage = "https://rinja.readthedocs.io/" repository = "https://github.com/rinja-rs/rinja" license = "MIT OR Apache-2.0" workspace = ".." readme = "../README.md" edition = "2021" rust-version = "1.71" [package.metadata.docs.rs] features = ["full"] rustdoc-args = ["--generate-link-to-definition", "--cfg=docsrs"] [badges] maintenance = { status = "actively-developed" } [features] default = ["config", "humansize", "urlencode"] full = ["default", "code-in-doc", "serde_json"] code-in-doc = ["rinja_derive/code-in-doc"] config = ["rinja_derive/config"] humansize = ["rinja_derive/humansize", "dep:humansize"] serde_json = ["rinja_derive/serde_json", "dep:serde", "dep:serde_json"] urlencode = ["rinja_derive/urlencode", "dep:percent-encoding"] # Please do not depend on the following features manually. # Depend on the relevant integration crate instead! with-actix-web = ["rinja_derive/with-actix-web"] with-axum = ["rinja_derive/with-axum"] with-rocket = ["rinja_derive/with-rocket"] with-warp = ["rinja_derive/with-warp"] [dependencies] rinja_derive = { version = "=0.3.5", path = "../rinja_derive" } humansize = { version = "2", optional = true } num-traits = { version = "0.2.6", optional = true } percent-encoding = { version = "2.1.0", optional = true } serde = { version = "1.0", optional = true } serde_json = { version = "1.0", optional = true } itoa = "1.0.11" [dev-dependencies] criterion = "0.5" [[bench]] name = "to-json" harness = false required-features = ["serde_json"] [[bench]] name = "escape" harness = false rinja-0.3.5/LICENSE-APACHE000064400000000000000000000251301046102023000126610ustar 00000000000000 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. rinja-0.3.5/LICENSE-MIT000064400000000000000000000020501046102023000123650ustar 00000000000000Copyright (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. rinja-0.3.5/README.md000064400000000000000000000062111046102023000122130ustar 00000000000000# rinja [![Crates.io](https://img.shields.io/crates/v/rinja?logo=rust&style=flat-square&logoColor=white "Crates.io")](https://crates.io/crates/rinja) [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/rinja-rs/rinja/rust.yml?branch=master&logo=github&style=flat-square&logoColor=white "GitHub Workflow Status")](https://github.com/rinja-rs/rinja/actions/workflows/rust.yml) [![Book](https://img.shields.io/readthedocs/rinja?label=book&logo=readthedocs&style=flat-square&logoColor=white "Book")](https://rinja.readthedocs.io/) [![docs.rs](https://img.shields.io/docsrs/rinja?logo=docsdotrs&style=flat-square&logoColor=white "docs.rs")](https://docs.rs/rinja/) **Rinja** implements a template rendering engine based on [Jinja](https://jinja.palletsprojects.com/), and generates type-safe Rust code from your templates at compile time based on a user-defined `struct` to hold the template's context. See below for an example. It is a fork of [Askama](https://crates.io/crates/askama). All feedback welcome! Feel free to file bugs, requests for documentation and any other feedback to the [issue tracker][issues]. You can find the documentation about our syntax, features, configuration in our book: [rinja.readthedocs.io](https://rinja.readthedocs.io/). Have a look at our [*Rinja Playground*](https://rinja-rs.github.io/play-rinja/), if you want to try out rinja's code generation online. ### Feature highlights * Construct templates using a familiar, easy-to-use syntax * Benefit from the safety provided by Rust's type system * Template code is compiled into your crate for optimal performance * Optional built-in support for Actix, Axum, Rocket, and warp web frameworks * Debugging features to assist you in template development * Templates must be valid UTF-8 and produce UTF-8 when rendered * Works on stable Rust ### Supported in templates * Template inheritance * Loops, if/else statements and include support * Macro support * Variables (no mutability allowed) * Some built-in filters, and the ability to use your own * Whitespace suppressing with '-' markers * Opt-out HTML escaping * Syntax customization [issues]: https://github.com/rinja-rs/rinja/issues How to get started ------------------ First, add the rinja dependency to your crate's `Cargo.toml`: ```sh cargo add rinja ``` Now create a directory called `templates` in your crate root. In it, create a file called `hello.html`, containing the following: ```jinja Hello, {{ name }}! ``` In any Rust file inside your crate, add the following: ```rust use rinja::Template; // bring trait in scope #[derive(Template)] // this will generate the code... #[template(path = "hello.html")] // using the template in this path, relative // to the `templates` dir in the crate root struct HelloTemplate<'a> { // the name of the struct can be anything name: &'a str, // the field name should match the variable name // in your template } fn main() { let hello = HelloTemplate { name: "world" }; // instantiate your struct println!("{}", hello.render().unwrap()); // then render it. } ``` You should now be able to compile and run this code. rinja-0.3.5/benches/escape.rs000064400000000000000000000007631046102023000141570ustar 00000000000000use criterion::{Criterion, black_box, criterion_group, criterion_main}; use rinja::filters::{Html, escape}; criterion_main!(benches); criterion_group!(benches, functions); fn functions(c: &mut Criterion) { c.bench_function("Escaping", escaping); } fn escaping(b: &mut criterion::Bencher<'_>) { b.iter(|| { for &s in black_box(STRINGS) { let _ = black_box(format!("{}", escape(s, Html).unwrap())); } }); } const STRINGS: &[&str] = include!("strings.inc"); rinja-0.3.5/benches/strings.inc000064400000000000000000000101601046102023000145250ustar 00000000000000{ const STRING_LONG: &str = 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.

Etiam nibh mi, accumsan quis purus sed, posuere fermentum lorem. In pulvinar porta maximus. Fusce tincidunt lacinia tellus sit amet tincidunt. Aliquam lacus est, pulvinar non metus a, facilisis 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.

Sed sollicitudin sem 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.

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 efficitur massa, 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.

"; const STRING_SHORT: &str = "Lorem ipsum dolor sit amet,bar&foo\"bar\\foo/bar"; const EMPTY: &str = ""; const NO_ESCAPE: &str = "Lorem ipsum dolor sit amet,"; const NO_ESCAPE_LONG: &str = 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. "; const STRINGS: &[&str] = &[ STRING_LONG, STRING_SHORT, EMPTY, NO_ESCAPE, NO_ESCAPE_LONG, ]; STRINGS } rinja-0.3.5/benches/to-json.rs000064400000000000000000000034721046102023000143100ustar 00000000000000use criterion::{Criterion, black_box, criterion_group, criterion_main}; use rinja::Template; criterion_main!(benches); criterion_group!(benches, functions); fn functions(c: &mut Criterion) { c.bench_function("escape JSON", escape_json); c.bench_function("escape JSON (pretty)", escape_json_pretty); c.bench_function("escape JSON for HTML", escape_json_for_html); c.bench_function("escape JSON for HTML (pretty)", escape_json_for_html_pretty); } fn escape_json(b: &mut criterion::Bencher<'_>) { #[derive(Template)] #[template(ext = "html", source = "{{self.0|json|safe}}")] struct Tmpl(&'static str); b.iter(|| { let mut len = 0; for &s in black_box(STRINGS) { len += Tmpl(s).to_string().len(); } len }); } fn escape_json_pretty(b: &mut criterion::Bencher<'_>) { #[derive(Template)] #[template(ext = "html", source = "{{self.0|json(2)|safe}}")] struct Tmpl(&'static str); b.iter(|| { let mut len = 0; for &s in black_box(STRINGS) { len += Tmpl(s).to_string().len(); } len }); } fn escape_json_for_html(b: &mut criterion::Bencher<'_>) { #[derive(Template)] #[template(ext = "html", source = "{{self.0|json}}")] struct Tmpl(&'static str); b.iter(|| { let mut len = 0; for &s in black_box(STRINGS) { len += Tmpl(s).to_string().len(); } len }); } fn escape_json_for_html_pretty(b: &mut criterion::Bencher<'_>) { #[derive(Template)] #[template(ext = "html", source = "{{self.0|json(2)}}")] struct Tmpl(&'static str); b.iter(|| { let mut len = 0; for &s in black_box(STRINGS) { len += Tmpl(s).to_string().len(); } len }); } const STRINGS: &[&str] = include!("strings.inc"); rinja-0.3.5/src/error.rs000064400000000000000000000046351046102023000132320ustar 00000000000000use std::convert::Infallible; use std::fmt::{self, Display}; /// The [`Result`](std::result::Result) type with [`Error`] as default error type pub type Result = std::result::Result; /// rinja error type /// /// # Feature Interaction /// /// If the feature `serde_json` is enabled an /// additional error variant `Json` is added. /// /// # Why not `failure`/`error-chain`? /// /// Error from `error-chain` are not `Sync` which /// can lead to problems e.g. when this is used /// by a crate which use `failure`. Implementing /// `Fail` on the other hand prevents the implementation /// of `std::error::Error` until specialization lands /// on stable. While errors impl. `Fail` can be /// converted to a type impl. `std::error::Error` /// using a adapter the benefits `failure` would /// bring to this crate are small, which is why /// `std::error::Error` was used. #[non_exhaustive] #[derive(Debug)] pub enum Error { /// formatting error Fmt, /// an error raised by using `?` in a template Custom(Box), /// json conversion error #[cfg(feature = "serde_json")] Json(serde_json::Error), } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { Error::Fmt => None, Error::Custom(ref err) => Some(err.as_ref()), #[cfg(feature = "serde_json")] Error::Json(ref err) => Some(err), } } } impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Fmt => write!(formatter, "formatting error"), Error::Custom(err) => write!(formatter, "{err}"), #[cfg(feature = "serde_json")] Error::Json(err) => write!(formatter, "json conversion error: {err}"), } } } impl From for Error { #[inline] fn from(_: fmt::Error) -> Self { Error::Fmt } } #[cfg(feature = "serde_json")] impl From for Error { #[inline] fn from(err: serde_json::Error) -> Self { Error::Json(err) } } impl From for Error { #[inline] fn from(value: Infallible) -> Self { match value {} } } #[cfg(test)] mod tests { use super::Error; #[allow(dead_code)] trait AssertSendSyncStatic: Send + Sync + 'static {} impl AssertSendSyncStatic for Error {} } rinja-0.3.5/src/filters/builtin.rs000064400000000000000000000757401046102023000152240ustar 00000000000000use std::cell::Cell; use std::convert::Infallible; use std::fmt::{self, Write}; use std::ops::Deref; use std::pin::Pin; use super::escape::{FastWritable, HtmlSafeOutput}; use crate::{Error, Result}; // MAX_LEN is maximum allowed length for filters. const MAX_LEN: usize = 10_000; /// Formats arguments according to the specified format /// /// The *second* argument to this filter must be a string literal (as in normal /// Rust). The two arguments are passed through to the `format!()` /// [macro](https://doc.rust-lang.org/stable/std/macro.format.html) by /// the Rinja code generator, but the order is swapped to support filter /// composition. /// /// ```ignore /// {{ value|fmt("{:?}") }} /// ``` /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ value|fmt("{:?}") }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example { /// value: (usize, usize), /// } /// /// assert_eq!( /// Example { value: (3, 4) }.to_string(), /// "
(3, 4)
" /// ); /// # } /// ``` /// /// Compare with [format](./fn.format.html). pub fn fmt() {} /// Formats arguments according to the specified format /// /// The first argument to this filter must be a string literal (as in normal /// Rust). All arguments are passed through to the `format!()` /// [macro](https://doc.rust-lang.org/stable/std/macro.format.html) by /// the Rinja code generator. /// /// ```ignore /// {{ "{:?}{:?}"|format(value, other_value) }} /// ``` /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ "{:?}"|format(value) }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example { /// value: (usize, usize), /// } /// /// assert_eq!( /// Example { value: (3, 4) }.to_string(), /// "
(3, 4)
" /// ); /// # } /// ``` /// /// Compare with [fmt](./fn.fmt.html). pub fn format() {} /// Replaces line breaks in plain text with appropriate HTML /// /// A single newline becomes an HTML line break `
` and a new line /// followed by a blank line becomes a paragraph break `

`. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///

{{ example|linebreaks }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "Foo\nBar\n\nBaz" }.to_string(), /// "

Foo
Bar

Baz

" /// ); /// # } /// ``` #[inline] pub fn linebreaks(s: impl fmt::Display) -> Result, fmt::Error> { fn linebreaks(s: String) -> String { let linebroken = s.replace("\n\n", "

").replace('\n', "
"); format!("

{linebroken}

") } Ok(HtmlSafeOutput(linebreaks(try_to_string(s)?))) } /// Converts all newlines in a piece of plain text to HTML line breaks /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ lines|linebreaksbr }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// lines: &'a str, /// } /// /// assert_eq!( /// Example { lines: "a\nb\nc" }.to_string(), /// "
a
b
c
" /// ); /// # } /// ``` #[inline] pub fn linebreaksbr(s: impl fmt::Display) -> Result, fmt::Error> { fn linebreaksbr(s: String) -> String { s.replace('\n', "
") } Ok(HtmlSafeOutput(linebreaksbr(try_to_string(s)?))) } /// Replaces only paragraph breaks in plain text with appropriate HTML /// /// A new line followed by a blank line becomes a paragraph break `

`. /// Paragraph tags only wrap content; empty paragraphs are removed. /// No `
` tags are added. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// /// {{ lines|paragraphbreaks }} /// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// lines: &'a str, /// } /// /// assert_eq!( /// Example { lines: "Foo\nBar\n\nBaz" }.to_string(), /// "

Foo\nBar

Baz

" /// ); /// # } /// ``` #[inline] pub fn paragraphbreaks(s: impl fmt::Display) -> Result, fmt::Error> { fn paragraphbreaks(s: String) -> String { let linebroken = s.replace("\n\n", "

").replace("

", ""); format!("

{linebroken}

") } Ok(HtmlSafeOutput(paragraphbreaks(try_to_string(s)?))) } /// Converts to lowercase /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ word|lower }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// word: &'a str, /// } /// /// assert_eq!( /// Example { word: "FOO" }.to_string(), /// "
foo
" /// ); /// /// assert_eq!( /// Example { word: "FooBar" }.to_string(), /// "
foobar
" /// ); /// # } /// ``` #[inline] pub fn lower(s: impl fmt::Display) -> Result { fn lower(s: String) -> Result { Ok(s.to_lowercase()) } lower(try_to_string(s)?) } /// Converts to lowercase, alias for the `|lower` filter /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ word|lowercase }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// word: &'a str, /// } /// /// assert_eq!( /// Example { word: "FOO" }.to_string(), /// "
foo
" /// ); /// /// assert_eq!( /// Example { word: "FooBar" }.to_string(), /// "
foobar
" /// ); /// # } /// ``` #[inline] pub fn lowercase(s: impl fmt::Display) -> Result { lower(s) } /// Converts to uppercase /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ word|upper }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// word: &'a str, /// } /// /// assert_eq!( /// Example { word: "foo" }.to_string(), /// "
FOO
" /// ); /// /// assert_eq!( /// Example { word: "FooBar" }.to_string(), /// "
FOOBAR
" /// ); /// # } /// ``` #[inline] pub fn upper(s: impl fmt::Display) -> Result { fn upper(s: String) -> Result { Ok(s.to_uppercase()) } upper(try_to_string(s)?) } /// Converts to uppercase, alias for the `|upper` filter /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ word|uppercase }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// word: &'a str, /// } /// /// assert_eq!( /// Example { word: "foo" }.to_string(), /// "
FOO
" /// ); /// /// assert_eq!( /// Example { word: "FooBar" }.to_string(), /// "
FOOBAR
" /// ); /// # } /// ``` #[inline] pub fn uppercase(s: impl fmt::Display) -> Result { upper(s) } /// Strip leading and trailing whitespace /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|trim }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: " Hello\tworld\t" }.to_string(), /// "
Hello\tworld
" /// ); /// # } /// ``` pub fn trim(s: T) -> Result { struct Collector(String); impl fmt::Write for Collector { fn write_str(&mut self, s: &str) -> fmt::Result { match self.0.is_empty() { true => self.0.write_str(s.trim_start()), false => self.0.write_str(s), } } } let mut collector = Collector(String::new()); write!(collector, "{s}")?; let Collector(mut s) = collector; s.truncate(s.trim_end().len()); Ok(s) } /// Limit string length, appends '...' if truncated /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|truncate(2) }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "hello" }.to_string(), /// "
he...
" /// ); /// # } /// ``` #[inline] pub fn truncate( source: S, remaining: usize, ) -> Result, Infallible> { Ok(TruncateFilter { source, remaining }) } pub struct TruncateFilter { source: S, remaining: usize, } impl fmt::Display for TruncateFilter { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(TruncateWriter::new(f, self.remaining), "{}", self.source) } } impl FastWritable for TruncateFilter { #[inline] fn write_into(&self, dest: &mut W) -> fmt::Result { self.source .write_into(&mut TruncateWriter::new(dest, self.remaining)) } } struct TruncateWriter { dest: Option, remaining: usize, } impl TruncateWriter { fn new(dest: W, remaining: usize) -> Self { TruncateWriter { dest: Some(dest), remaining, } } } impl fmt::Write for TruncateWriter { fn write_str(&mut self, s: &str) -> fmt::Result { let Some(dest) = &mut self.dest else { return Ok(()); }; let mut rem = self.remaining; if rem >= s.len() { dest.write_str(s)?; self.remaining -= s.len(); } else { if rem > 0 { while !s.is_char_boundary(rem) { rem += 1; } if rem == s.len() { // Don't write "..." if the char bound extends to the end of string. self.remaining = 0; return dest.write_str(s); } dest.write_str(&s[..rem])?; } dest.write_str("...")?; self.dest = None; } Ok(()) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { match self.dest.is_some() { true => self.write_str(c.encode_utf8(&mut [0; 4])), false => Ok(()), } } #[inline] fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { match self.dest.is_some() { true => fmt::write(self, args), false => Ok(()), } } } /// Indent lines with `width` spaces /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|indent(4) }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "hello\nfoo\nbar" }.to_string(), /// "
hello\n foo\n bar
" /// ); /// # } /// ``` #[inline] pub fn indent(s: impl fmt::Display, width: usize) -> Result { fn indent(s: String, width: usize) -> Result { if width >= MAX_LEN || s.len() >= MAX_LEN { return Ok(s); } let mut indented = String::new(); for (i, c) in s.char_indices() { indented.push(c); if c == '\n' && i < s.len() - 1 { for _ in 0..width { indented.push(' '); } } } Ok(indented) } indent(try_to_string(s)?, width) } /// Joins iterable into a string separated by provided argument /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|join(", ") }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a [&'a str], /// } /// /// assert_eq!( /// Example { example: &["foo", "bar", "bazz"] }.to_string(), /// "
foo, bar, bazz
" /// ); /// # } /// ``` #[inline] pub fn join(input: I, separator: S) -> Result, Infallible> where I: IntoIterator, I::Item: fmt::Display, S: fmt::Display, { Ok(JoinFilter(Cell::new(Some((input, separator))))) } /// Result of the filter [`join()`]. /// /// ## Note /// /// This struct implements [`fmt::Display`], but only produces a string once. /// Any subsequent call to `.to_string()` will result in an empty string, because the iterator is /// already consumed. // The filter contains a [`Cell`], so we can modify iterator inside a method that takes `self` by // reference: [`fmt::Display::fmt()`] normally has the contract that it will produce the same result // in multiple invocations for the same object. We break this contract, because have to consume the // iterator, unless we want to enforce `I: Clone`, nor do we want to "memorize" the result of the // joined data. pub struct JoinFilter(Cell>); impl fmt::Display for JoinFilter where I: IntoIterator, I::Item: fmt::Display, S: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Some((iter, separator)) = self.0.take() else { return Ok(()); }; for (idx, token) in iter.into_iter().enumerate() { match idx { 0 => f.write_fmt(format_args!("{token}"))?, _ => f.write_fmt(format_args!("{separator}{token}"))?, } } Ok(()) } } /// Capitalize a value. The first character will be uppercase, all others lowercase. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|capitalize }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "hello" }.to_string(), /// "
Hello
" /// ); /// /// assert_eq!( /// Example { example: "hElLO" }.to_string(), /// "
Hello
" /// ); /// # } /// ``` #[inline] pub fn capitalize(s: impl fmt::Display) -> Result { fn capitalize(s: String) -> Result { match s.chars().next() { Some(c) => { let mut replacement: String = c.to_uppercase().collect(); replacement.push_str(&s[c.len_utf8()..].to_lowercase()); Ok(replacement) } _ => Ok(s), } } capitalize(try_to_string(s)?) } /// Centers the value in a field of a given width /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
-{{ example|center(5) }}-
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "a" }.to_string(), /// "
- a -
" /// ); /// # } /// ``` #[inline] pub fn center(src: T, width: usize) -> Result, Infallible> { Ok(Center { src, width }) } pub struct Center { src: T, width: usize, } impl fmt::Display for Center { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.width < MAX_LEN { write!(f, "{: ^1$}", self.src, self.width) } else { write!(f, "{}", self.src) } } } /// Count the words in that string. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|wordcount }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "rinja is sort of cool" }.to_string(), /// "
5
" /// ); /// # } /// ``` #[inline] pub fn wordcount(s: impl fmt::Display) -> Result { fn wordcount(s: String) -> Result { Ok(s.split_whitespace().count()) } wordcount(try_to_string(s)?) } /// Return a title cased version of the value. Words will start with uppercase letters, all /// remaining characters are lowercase. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|title }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "hello WORLD" }.to_string(), /// "
Hello World
" /// ); /// # } /// ``` pub fn title(s: impl fmt::Display) -> Result { let s = try_to_string(s)?; let mut need_capitalization = true; // Sadly enough, we can't mutate a string when iterating over its chars, likely because it could // change the size of a char, "breaking" the char indices. let mut output = String::with_capacity(s.len()); for c in s.chars() { if c.is_whitespace() { output.push(c); need_capitalization = true; } else if need_capitalization { match c.is_uppercase() { true => output.push(c), false => output.extend(c.to_uppercase()), } need_capitalization = false; } else { match c.is_lowercase() { true => output.push(c), false => output.extend(c.to_lowercase()), } } } Ok(output) } /// For a value of `±1` by default an empty string `""` is returned, otherwise `"s"`. /// /// # Examples /// /// ## With default arguments /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// /// I have {{dogs}} dog{{dogs|pluralize}} and {{cats}} cat{{cats|pluralize}}. /// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Pets { /// dogs: i8, /// cats: i8, /// } /// /// assert_eq!( /// Pets { dogs: 0, cats: 0 }.to_string(), /// "I have 0 dogs and 0 cats." /// ); /// assert_eq!( /// Pets { dogs: 1, cats: 1 }.to_string(), /// "I have 1 dog and 1 cat." /// ); /// assert_eq!( /// Pets { dogs: -1, cats: 99 }.to_string(), /// "I have -1 dog and 99 cats." /// ); /// # } /// ``` /// /// ## Overriding the singular case /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// /// I have {{dogs}} dog{{ dogs|pluralize("go") }}. /// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Dog { /// dogs: i8, /// } /// /// assert_eq!( /// Dog { dogs: 0 }.to_string(), /// "I have 0 dogs." /// ); /// assert_eq!( /// Dog { dogs: 1 }.to_string(), /// "I have 1 doggo." /// ); /// # } /// ``` /// /// ## Overriding singular and plural cases /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// /// I have {{mice}} {{ mice|pluralize("mouse", "mice") }}. /// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Mice { /// mice: i8, /// } /// /// assert_eq!( /// Mice { mice: 42 }.to_string(), /// "I have 42 mice." /// ); /// assert_eq!( /// Mice { mice: 1 }.to_string(), /// "I have 1 mouse." /// ); /// # } /// ``` /// /// ## Arguments get escaped /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// /// You are number {{ number|pluralize("ONE", number) }}! /// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Number { /// number: usize /// } /// /// assert_eq!( /// Number { number: 1 }.to_string(), /// "You are number <b>ONE</b>!", /// ); /// assert_eq!( /// Number { number: 9000 }.to_string(), /// "You are number 9000!", /// ); /// # } /// ``` #[inline] pub fn pluralize(count: C, singular: S, plural: P) -> Result, C::Error> where C: PluralizeCount, { match count.is_singular()? { true => Ok(Pluralize::Singular(singular)), false => Ok(Pluralize::Plural(plural)), } } /// An integer that can have the value `+1` and maybe `-1`. pub trait PluralizeCount { /// A possible error that can occur while checking the value. type Error: Into; /// Returns `true` if and only if the value is `±1`. fn is_singular(&self) -> Result; } const _: () = { crate::impl_for_ref! { impl PluralizeCount for T { type Error = T::Error; #[inline] fn is_singular(&self) -> Result { ::is_singular(self) } } } impl PluralizeCount for Pin where T: Deref, ::Target: PluralizeCount, { type Error = <::Target as PluralizeCount>::Error; #[inline] fn is_singular(&self) -> Result { self.as_ref().get_ref().is_singular() } } /// implement `PluralizeCount` for unsigned integer types macro_rules! impl_pluralize_for_unsigned_int { ($($ty:ty)*) => { $( impl PluralizeCount for $ty { type Error = Infallible; #[inline] fn is_singular(&self) -> Result { Ok(*self == 1) } } )* }; } impl_pluralize_for_unsigned_int!(u8 u16 u32 u64 u128 usize); /// implement `PluralizeCount` for signed integer types macro_rules! impl_pluralize_for_signed_int { ($($ty:ty)*) => { $( impl PluralizeCount for $ty { type Error = Infallible; #[inline] fn is_singular(&self) -> Result { Ok(*self == 1 || *self == -1) } } )* }; } impl_pluralize_for_signed_int!(i8 i16 i32 i64 i128 isize); /// implement `PluralizeCount` for non-zero integer types macro_rules! impl_pluralize_for_non_zero { ($($ty:ident)*) => { $( impl PluralizeCount for std::num::$ty { type Error = Infallible; #[inline] fn is_singular(&self) -> Result { self.get().is_singular() } } )* }; } impl_pluralize_for_non_zero! { NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize } }; pub enum Pluralize { Singular(S), Plural(P), } impl fmt::Display for Pluralize { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Pluralize::Singular(value) => write!(f, "{value}"), Pluralize::Plural(value) => write!(f, "{value}"), } } } impl FastWritable for Pluralize { #[inline] fn write_into(&self, dest: &mut W) -> fmt::Result { match self { Pluralize::Singular(value) => value.write_into(dest), Pluralize::Plural(value) => value.write_into(dest), } } } fn try_to_string(s: impl fmt::Display) -> Result { let mut result = String::new(); write!(result, "{s}")?; Ok(result) } #[cfg(test)] mod tests { use super::*; #[test] fn test_linebreaks() { assert_eq!( linebreaks("Foo\nBar Baz").unwrap().to_string(), "

Foo
Bar Baz

" ); assert_eq!( linebreaks("Foo\nBar\n\nBaz").unwrap().to_string(), "

Foo
Bar

Baz

" ); } #[test] fn test_linebreaksbr() { assert_eq!(linebreaksbr("Foo\nBar").unwrap().to_string(), "Foo
Bar"); assert_eq!( linebreaksbr("Foo\nBar\n\nBaz").unwrap().to_string(), "Foo
Bar

Baz" ); } #[test] fn test_paragraphbreaks() { assert_eq!( paragraphbreaks("Foo\nBar Baz").unwrap().to_string(), "

Foo\nBar Baz

" ); assert_eq!( paragraphbreaks("Foo\nBar\n\nBaz").unwrap().to_string(), "

Foo\nBar

Baz

" ); assert_eq!( paragraphbreaks("Foo\n\n\n\n\nBar\n\nBaz") .unwrap() .to_string(), "

Foo

\nBar

Baz

" ); } #[test] fn test_lower() { assert_eq!(lower("Foo").unwrap().to_string(), "foo"); assert_eq!(lower("FOO").unwrap().to_string(), "foo"); assert_eq!(lower("FooBar").unwrap().to_string(), "foobar"); assert_eq!(lower("foo").unwrap().to_string(), "foo"); } #[test] fn test_upper() { assert_eq!(upper("Foo").unwrap().to_string(), "FOO"); assert_eq!(upper("FOO").unwrap().to_string(), "FOO"); assert_eq!(upper("FooBar").unwrap().to_string(), "FOOBAR"); assert_eq!(upper("foo").unwrap().to_string(), "FOO"); } #[test] fn test_trim() { assert_eq!(trim(" Hello\tworld\t").unwrap().to_string(), "Hello\tworld"); } #[test] fn test_truncate() { assert_eq!(truncate("hello", 2).unwrap().to_string(), "he..."); let a = String::from("您好"); assert_eq!(a.len(), 6); assert_eq!(String::from("您").len(), 3); assert_eq!(truncate("您好", 1).unwrap().to_string(), "您..."); assert_eq!(truncate("您好", 2).unwrap().to_string(), "您..."); assert_eq!(truncate("您好", 3).unwrap().to_string(), "您..."); assert_eq!(truncate("您好", 4).unwrap().to_string(), "您好"); assert_eq!(truncate("您好", 5).unwrap().to_string(), "您好"); assert_eq!(truncate("您好", 6).unwrap().to_string(), "您好"); assert_eq!(truncate("您好", 7).unwrap().to_string(), "您好"); let s = String::from("🤚a🤚"); assert_eq!(s.len(), 9); assert_eq!(String::from("🤚").len(), 4); assert_eq!(truncate("🤚a🤚", 1).unwrap().to_string(), "🤚..."); assert_eq!(truncate("🤚a🤚", 2).unwrap().to_string(), "🤚..."); assert_eq!(truncate("🤚a🤚", 3).unwrap().to_string(), "🤚..."); assert_eq!(truncate("🤚a🤚", 4).unwrap().to_string(), "🤚..."); assert_eq!(truncate("🤚a🤚", 5).unwrap().to_string(), "🤚a..."); assert_eq!(truncate("🤚a🤚", 6).unwrap().to_string(), "🤚a🤚"); assert_eq!(truncate("🤚a🤚", 6).unwrap().to_string(), "🤚a🤚"); assert_eq!(truncate("🤚a🤚", 7).unwrap().to_string(), "🤚a🤚"); assert_eq!(truncate("🤚a🤚", 8).unwrap().to_string(), "🤚a🤚"); assert_eq!(truncate("🤚a🤚", 9).unwrap().to_string(), "🤚a🤚"); assert_eq!(truncate("🤚a🤚", 10).unwrap().to_string(), "🤚a🤚"); } #[test] fn test_indent() { assert_eq!(indent("hello", 2).unwrap().to_string(), "hello"); assert_eq!(indent("hello\n", 2).unwrap().to_string(), "hello\n"); assert_eq!(indent("hello\nfoo", 2).unwrap().to_string(), "hello\n foo"); assert_eq!( indent("hello\nfoo\n bar", 4).unwrap().to_string(), "hello\n foo\n bar" ); assert_eq!( indent("hello", 267_332_238_858).unwrap().to_string(), "hello" ); } #[allow(clippy::needless_borrow)] #[test] fn test_join() { assert_eq!( join((&["hello", "world"]).iter(), ", ") .unwrap() .to_string(), "hello, world" ); assert_eq!( join((&["hello"]).iter(), ", ").unwrap().to_string(), "hello" ); let empty: &[&str] = &[]; assert_eq!(join(empty.iter(), ", ").unwrap().to_string(), ""); let input: Vec = vec!["foo".into(), "bar".into(), "bazz".into()]; assert_eq!(join(input.iter(), ":").unwrap().to_string(), "foo:bar:bazz"); let input: &[String] = &["foo".into(), "bar".into()]; assert_eq!(join(input.iter(), ":").unwrap().to_string(), "foo:bar"); let real: String = "blah".into(); let input: Vec<&str> = vec![&real]; assert_eq!(join(input.iter(), ";").unwrap().to_string(), "blah"); assert_eq!( join((&&&&&["foo", "bar"]).iter(), ", ") .unwrap() .to_string(), "foo, bar" ); } #[test] fn test_capitalize() { assert_eq!(capitalize("foo").unwrap().to_string(), "Foo".to_string()); assert_eq!(capitalize("f").unwrap().to_string(), "F".to_string()); assert_eq!(capitalize("fO").unwrap().to_string(), "Fo".to_string()); assert_eq!(capitalize("").unwrap().to_string(), String::new()); assert_eq!(capitalize("FoO").unwrap().to_string(), "Foo".to_string()); assert_eq!( capitalize("foO BAR").unwrap().to_string(), "Foo bar".to_string() ); assert_eq!( capitalize("äØÄÅÖ").unwrap().to_string(), "Äøäåö".to_string() ); assert_eq!(capitalize("ß").unwrap().to_string(), "SS".to_string()); assert_eq!(capitalize("ßß").unwrap().to_string(), "SSß".to_string()); } #[test] fn test_center() { assert_eq!(center("f", 3).unwrap().to_string(), " f ".to_string()); assert_eq!(center("f", 4).unwrap().to_string(), " f ".to_string()); assert_eq!(center("foo", 1).unwrap().to_string(), "foo".to_string()); assert_eq!( center("foo bar", 8).unwrap().to_string(), "foo bar ".to_string() ); assert_eq!( center("foo", 111_669_149_696).unwrap().to_string(), "foo".to_string() ); } #[test] fn test_wordcount() { assert_eq!(wordcount("").unwrap(), 0); assert_eq!(wordcount(" \n\t").unwrap(), 0); assert_eq!(wordcount("foo").unwrap(), 1); assert_eq!(wordcount("foo bar").unwrap(), 2); assert_eq!(wordcount("foo bar").unwrap(), 2); } #[test] fn test_title() { assert_eq!(&title("").unwrap(), ""); assert_eq!(&title(" \n\t").unwrap(), " \n\t"); assert_eq!(&title("foo").unwrap(), "Foo"); assert_eq!(&title(" foo").unwrap(), " Foo"); assert_eq!(&title("foo bar").unwrap(), "Foo Bar"); assert_eq!(&title("foo bar ").unwrap(), "Foo Bar "); assert_eq!(&title("fOO").unwrap(), "Foo"); assert_eq!(&title("fOo BaR").unwrap(), "Foo Bar"); } #[test] fn fuzzed_indent_filter() { let s = "hello\nfoo\nbar".to_string().repeat(1024); assert_eq!(indent(s.clone(), 4).unwrap().to_string(), s); } } rinja-0.3.5/src/filters/escape.rs000064400000000000000000000547571046102023000150230ustar 00000000000000use std::convert::Infallible; use std::fmt::{self, Formatter, Write}; use std::ops::Deref; use std::pin::Pin; use std::{borrow, str}; /// Marks a string (or other `Display` type) as safe /// /// Use this if you want to allow markup in an expression, or if you know /// that the expression's contents don't need to be escaped. /// /// Rinja will automatically insert the first (`Escaper`) argument, /// so this filter only takes a single argument of any type that implements /// `Display`. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|safe }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "

I'm Safe

" }.to_string(), /// "

I'm Safe

" /// ); /// # } /// ``` #[inline] pub fn safe(text: T, escaper: E) -> Result, Infallible> { let _ = escaper; // it should not be part of the interface that the `escaper` is unused Ok(Safe(text)) } /// Escapes strings according to the escape mode. /// /// Rinja will automatically insert the first (`Escaper`) argument, /// so this filter only takes a single argument of any type that implements /// `Display`. /// /// It is possible to optionally specify an escaper other than the default for /// the template's extension, like `{{ val|escape("txt") }}`. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|escape }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "Escape <>&" }.to_string(), /// "
Escape <>&
" /// ); /// # } /// ``` #[inline] pub fn escape(text: T, escaper: E) -> Result>, Infallible> { Ok(Safe(EscapeDisplay(text, escaper))) } pub struct EscapeDisplay(T, E); impl fmt::Display for EscapeDisplay { #[inline] fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { write!(EscapeWriter(fmt, self.1), "{}", &self.0) } } impl FastWritable for EscapeDisplay { #[inline] fn write_into(&self, dest: &mut W) -> fmt::Result { self.0.write_into(&mut EscapeWriter(dest, self.1)) } } struct EscapeWriter(W, E); impl Write for EscapeWriter { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.1.write_escaped_str(&mut self.0, s) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { self.1.write_escaped_char(&mut self.0, c) } } /// Alias for [`escape()`] /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
{{ example|e }}
/// /// ``` /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// example: &'a str, /// } /// /// assert_eq!( /// Example { example: "Escape <>&" }.to_string(), /// "
Escape <>&
" /// ); /// # } /// ``` #[inline] pub fn e(text: T, escaper: E) -> Result>, Infallible> { escape(text, escaper) } /// Escape characters in a safe way for HTML texts and attributes /// /// * `"` => `"` /// * `&` => `&` /// * `'` => `'` /// * `<` => `<` /// * `>` => `>` #[derive(Debug, Clone, Copy, Default)] pub struct Html; impl Escaper for Html { #[inline] fn write_escaped_str(&self, fmt: W, string: &str) -> fmt::Result { crate::html::write_escaped_str(fmt, string) } #[inline] fn write_escaped_char(&self, fmt: W, c: char) -> fmt::Result { crate::html::write_escaped_char(fmt, c) } } /// Don't escape the input but return in verbatim #[derive(Debug, Clone, Copy, Default)] pub struct Text; impl Escaper for Text { #[inline] fn write_escaped_str(&self, mut fmt: W, string: &str) -> fmt::Result { fmt.write_str(string) } #[inline] fn write_escaped_char(&self, mut fmt: W, c: char) -> fmt::Result { fmt.write_char(c) } } /// Escapers are used to make generated text safe for printing in some context. /// /// E.g. in an [`Html`] context, any and all generated text can be used in HTML/XML text nodes and /// attributes, without for for maliciously injected data. pub trait Escaper: Copy { /// Escaped the input string `string` into `fmt` fn write_escaped_str(&self, fmt: W, string: &str) -> fmt::Result; /// Escaped the input char `c` into `fmt` #[inline] fn write_escaped_char(&self, fmt: W, c: char) -> fmt::Result { self.write_escaped_str(fmt, c.encode_utf8(&mut [0; 4])) } } /// Used internally by rinja to select the appropriate escaper pub trait AutoEscape { /// The wrapped or converted result type type Escaped: fmt::Display; /// Early error testing for the input value, usually [`Infallible`] type Error: Into; /// Used internally by rinja to select the appropriate escaper fn rinja_auto_escape(&self) -> Result; } /// Used internally by rinja to select the appropriate escaper #[derive(Debug, Clone)] pub struct AutoEscaper<'a, T: ?Sized, E> { text: &'a T, escaper: E, } impl<'a, T: ?Sized, E> AutoEscaper<'a, T, E> { /// Used internally by rinja to select the appropriate escaper #[inline] pub fn new(text: &'a T, escaper: E) -> Self { Self { text, escaper } } } /// Use the provided escaper impl<'a, T: fmt::Display + ?Sized, E: Escaper> AutoEscape for &&AutoEscaper<'a, T, E> { type Escaped = EscapeDisplay<&'a T, E>; type Error = Infallible; #[inline] fn rinja_auto_escape(&self) -> Result { Ok(EscapeDisplay(self.text, self.escaper)) } } /// Types that implement this marker trait don't need to be HTML escaped /// /// Please note that this trait is only meant as speed-up helper. In some odd circumcises rinja /// might still decide to HTML escape the input, so if this must not happen, then you need to use /// the [`|safe`](super::safe) filter to prevent the auto escaping. /// /// If you are unsure if your type generates HTML safe output in all cases, then DON'T mark it. /// Better safe than sorry! pub trait HtmlSafe: fmt::Display {} /// Don't escape HTML safe types impl<'a, T: HtmlSafe + ?Sized> AutoEscape for &AutoEscaper<'a, T, Html> { type Escaped = &'a T; type Error = Infallible; #[inline] fn rinja_auto_escape(&self) -> Result { Ok(self.text) } } /// Mark the output of a filter as "maybe safe" /// /// This enum can be used as a transparent return type of custom filters that want to mark /// their output as "safe" depending on some circumstances, i.e. that their output maybe does not /// need to be escaped. /// /// If the filter is not used as the last element in the filter chain, then any assumption is void. /// Let the next filter decide if the output is safe or not. /// /// ## Example /// /// ```rust /// mod filters { /// use rinja::{filters::MaybeSafe, Result}; /// /// // Do not actually use this filter! It's an intentionally bad example. /// pub fn backdoor(s: T, enable: &bool) -> Result> { /// Ok(match *enable { /// true => MaybeSafe::Safe(s), /// false => MaybeSafe::NeedsEscaping(s), /// }) /// } /// } /// /// #[derive(rinja::Template)] /// #[template( /// source = "
", /// ext = "html" /// )] /// struct DivWithBackdoor<'a> { /// klass: &'a str, /// enable_backdoor: bool, /// } /// /// assert_eq!( /// DivWithBackdoor { klass: " /// ``` /// /// To use it in HTML attributes, you can either use it in quotation marks `"{{data|json}}"` as is, /// or in apostrophes with the (optional) safe filter `'{{data|json|safe}}'`. /// In HTML texts the output of e.g. `
{{data|json|safe}}
` is safe, too. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
  • Example
  • /// /// ``` /// /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// data: Vec<&'a str>, /// } /// /// assert_eq!( /// Example { data: vec!["foo", "bar"] }.to_string(), /// "
  • Example
  • " /// ); /// # } /// ``` #[inline] pub fn json(value: impl Serialize) -> Result { Ok(ToJson { value }) } /// Serialize to formatted/prettified JSON (requires `json` feature) /// /// This filter works the same as [`json()`], but it formats the data for human readability. /// It has an additional "indent" argument, which can either be an integer how many spaces to use /// for indentation (capped to 16 characters), or a string (e.g. `"\u{A0}\u{A0}"` for two /// non-breaking spaces). /// /// ### Note /// /// In rinja's template language, this filter is called `|json`, too. The right function is /// automatically selected depending on whether an `indent` argument was provided or not. /// /// ``` /// # #[cfg(feature = "code-in-doc")] { /// # use rinja::Template; /// /// ```jinja /// ///
    {{data|json(4)|safe}}
    /// /// ``` /// /// #[derive(Template)] /// #[template(ext = "html", in_doc = true)] /// struct Example<'a> { /// data: Vec<&'a str>, /// } /// /// assert_eq!( /// Example { data: vec!["foo", "bar"] }.to_string(), /// "
    [ /// \"foo\", /// \"bar\" /// ]
    " /// ); /// # } /// ``` #[inline] pub fn json_pretty( value: impl Serialize, indent: impl AsIndent, ) -> Result { Ok(ToJsonPretty { value, indent }) } #[derive(Debug, Clone)] struct ToJson { value: S, } #[derive(Debug, Clone)] struct ToJsonPretty { value: S, indent: I, } /// A prefix usable for indenting [prettified JSON data](json_pretty) /// /// ``` /// # use rinja::filters::AsIndent; /// assert_eq!(4.as_indent(), " "); /// assert_eq!(" -> ".as_indent(), " -> "); /// ``` pub trait AsIndent { /// Borrow `self` as prefix to use. fn as_indent(&self) -> &str; } impl AsIndent for str { #[inline] fn as_indent(&self) -> &str { self } } impl AsIndent for String { #[inline] fn as_indent(&self) -> &str { self } } impl AsIndent for usize { #[inline] fn as_indent(&self) -> &str { const MAX_SPACES: usize = 16; const SPACES: &str = match str::from_utf8(&[b' '; MAX_SPACES]) { Ok(spaces) => spaces, Err(_) => panic!(), }; &SPACES[..(*self).min(SPACES.len())] } } impl AsIndent for std::borrow::Cow<'_, T> { #[inline] fn as_indent(&self) -> &str { T::as_indent(self) } } crate::impl_for_ref! { impl AsIndent for T { #[inline] fn as_indent(&self) -> &str { ::as_indent(self) } } } impl AsIndent for Pin where T: Deref, ::Target: AsIndent, { #[inline] fn as_indent(&self) -> &str { self.as_ref().get_ref().as_indent() } } impl FastWritable for ToJson { #[inline] fn write_into(&self, f: &mut W) -> fmt::Result { fmt_json(f, &self.value) } } impl fmt::Display for ToJson { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt_json(f, &self.value) } } impl FastWritable for ToJsonPretty { #[inline] fn write_into(&self, f: &mut W) -> fmt::Result { fmt_json_pretty(f, &self.value, self.indent.as_indent()) } } impl fmt::Display for ToJsonPretty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt_json_pretty(f, &self.value, self.indent.as_indent()) } } fn fmt_json(dest: &mut W, value: &S) -> fmt::Result { to_writer(JsonWriter(dest), value).map_err(|_| fmt::Error) } fn fmt_json_pretty( dest: &mut W, value: &S, indent: &str, ) -> fmt::Result { let formatter = PrettyFormatter::with_indent(indent.as_bytes()); let mut serializer = Serializer::with_formatter(JsonWriter(dest), formatter); value.serialize(&mut serializer).map_err(|_| fmt::Error) } struct JsonWriter<'a, W: fmt::Write + ?Sized>(&'a mut W); impl io::Write for JsonWriter<'_, W> { #[inline] fn write(&mut self, bytes: &[u8]) -> io::Result { self.write_all(bytes)?; Ok(bytes.len()) } #[inline] fn write_all(&mut self, bytes: &[u8]) -> io::Result<()> { write(self.0, bytes).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } fn write(f: &mut W, bytes: &[u8]) -> fmt::Result { let mut last = 0; for (index, byte) in bytes.iter().enumerate() { let escaped = match byte { b'&' => Some(br"\u0026"), b'\'' => Some(br"\u0027"), b'<' => Some(br"\u003c"), b'>' => Some(br"\u003e"), _ => None, }; if let Some(escaped) = escaped { f.write_str(unsafe { str::from_utf8_unchecked(&bytes[last..index]) })?; f.write_str(unsafe { str::from_utf8_unchecked(escaped) })?; last = index + 1; } } f.write_str(unsafe { str::from_utf8_unchecked(&bytes[last..]) }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_ugly() { assert_eq!(json(true).unwrap().to_string(), "true"); assert_eq!(json("foo").unwrap().to_string(), r#""foo""#); assert_eq!(json(true).unwrap().to_string(), "true"); assert_eq!(json("foo").unwrap().to_string(), r#""foo""#); assert_eq!( json("