Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement FastWritable for |json #124

Merged
merged 2 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions rinja/benches/to-json.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use criterion::{criterion_group, criterion_main, Criterion};
use rinja::filters::{escape, json, json_pretty, Html};
use rinja::Template;

criterion_main!(benches);
criterion_group!(benches, functions);
Expand All @@ -12,34 +12,58 @@ fn functions(c: &mut Criterion) {
}

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 STRINGS {
format!("{}", json(s).unwrap());
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 STRINGS {
format!("{}", json_pretty(s, 2).unwrap());
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 STRINGS {
format!("{}", escape(json(s).unwrap(), Html).unwrap());
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 STRINGS {
format!("{}", escape(json_pretty(s, 2).unwrap(), Html).unwrap(),);
len += Tmpl(s).to_string().len();
}
len
});
}

Expand Down
46 changes: 36 additions & 10 deletions rinja/src/filters/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use std::{fmt, io, str};
use serde::Serialize;
use serde_json::ser::{to_writer, PrettyFormatter, Serializer};

use super::FastWritable;

/// Serialize to JSON (requires `json` feature)
///
/// The generated string does not contain ampersands `&`, chevrons `< >`, or apostrophes `'`.
Expand Down Expand Up @@ -119,26 +121,50 @@ impl<T: AsIndent + ?Sized> AsIndent for std::sync::Arc<T> {
}
}

impl<S: Serialize> FastWritable for ToJson<S> {
#[inline]
fn write_into<W: fmt::Write + ?Sized>(&self, f: &mut W) -> fmt::Result {
fmt_json(f, &self.value)
}
}

impl<S: Serialize> fmt::Display for ToJson<S> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
to_writer(JsonWriter(f), &self.value).map_err(|_| fmt::Error)
fmt_json(f, &self.value)
}
}

impl<S: Serialize, I: AsIndent> FastWritable for ToJsonPretty<S, I> {
#[inline]
fn write_into<W: fmt::Write + ?Sized>(&self, f: &mut W) -> fmt::Result {
fmt_json_pretty(f, &self.value, self.indent.as_indent())
}
}

impl<S: Serialize, I: AsIndent> fmt::Display for ToJsonPretty<S, I> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let indent = self.indent.as_indent();
let formatter = PrettyFormatter::with_indent(indent.as_bytes());
let mut serializer = Serializer::with_formatter(JsonWriter(f), formatter);
self.value
.serialize(&mut serializer)
.map_err(|_| fmt::Error)
fmt_json_pretty(f, &self.value, self.indent.as_indent())
}
}

struct JsonWriter<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>);
fn fmt_json<S: Serialize, W: fmt::Write + ?Sized>(dest: &mut W, value: &S) -> fmt::Result {
to_writer(JsonWriter(dest), value).map_err(|_| fmt::Error)
}

fn fmt_json_pretty<S: Serialize, W: fmt::Write + ?Sized>(
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<'_, '_> {
impl<W: fmt::Write + ?Sized> io::Write for JsonWriter<'_, W> {
#[inline]
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.write_all(bytes)?;
Expand All @@ -156,7 +182,7 @@ impl io::Write for JsonWriter<'_, '_> {
}
}

fn write(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
fn write<W: fmt::Write + ?Sized>(f: &mut W, bytes: &[u8]) -> fmt::Result {
let mut last = 0;
for (index, byte) in bytes.iter().enumerate() {
let escaped = match byte {
Expand Down