rinja-0.3.5/.cargo_vcs_info.json 0000644 00000000143 00000000001 0012142 0 ustar {
"git": {
"sha1": "f6acf786b09359688907fc7634dd84824f017258"
},
"path_in_vcs": "rinja"
} rinja-0.3.5/Cargo.toml 0000644 00000004575 00000000001 0010155 0 ustar # 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.orig 0000644 0000000 0000000 00000003355 10461020230 0013631 0 ustar 0000000 0000000 [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-APACHE 0000644 0000000 0000000 00000025130 10461020230 0012661 0 ustar 0000000 0000000 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-MIT 0000644 0000000 0000000 00000002050 10461020230 0012365 0 ustar 0000000 0000000 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.
rinja-0.3.5/README.md 0000644 0000000 0000000 00000006211 10461020230 0012213 0 ustar 0000000 0000000 # rinja
[](https://crates.io/crates/rinja)
[](https://github.com/rinja-rs/rinja/actions/workflows/rust.yml)
[](https://rinja.readthedocs.io/)
[](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.rs 0000644 0000000 0000000 00000000763 10461020230 0014157 0 ustar 0000000 0000000 use 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.inc 0000644 0000000 0000000 00000010160 10461020230 0014525 0 ustar 0000000 0000000 {
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.rs 0000644 0000000 0000000 00000003472 10461020230 0014310 0 ustar 0000000 0000000 use 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.rs 0000644 0000000 0000000 00000004635 10461020230 0013232 0 ustar 0000000 0000000 use 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.rs 0000644 0000000 0000000 00000075740 10461020230 0015224 0 ustar 0000000 0000000 use 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
/// ///
"
/// );
/// # }
/// ```
///
/// 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
/// ///
"
/// );
/// # }
/// ```
///
/// 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 `
")
}
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
/// ///
"
/// );
/// # }
/// ```
#[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 `
"
/// );
/// # }
/// ```
#[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