From 031e0fd472a5163347baeb31252c267e06023192 Mon Sep 17 00:00:00 2001 From: Sabrina Jewson Date: Tue, 28 Dec 2021 10:41:21 +0000 Subject: [PATCH] Store Bytes in ErasedJson (#672) --- axum-extra/Cargo.toml | 1 + axum-extra/src/response/erased_json.rs | 11 +++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/axum-extra/Cargo.toml b/axum-extra/Cargo.toml index 2cb56340..87a5cb5c 100644 --- a/axum-extra/Cargo.toml +++ b/axum-extra/Cargo.toml @@ -15,6 +15,7 @@ erased-json = ["serde", "serde_json"] [dependencies] axum = { path = "../axum", version = "0.4" } +bytes = "1.1.0" http = "0.2" mime = "0.3" pin-project-lite = "0.2" diff --git a/axum-extra/src/response/erased_json.rs b/axum-extra/src/response/erased_json.rs index 6b50da7c..4a83cf30 100644 --- a/axum-extra/src/response/erased_json.rs +++ b/axum-extra/src/response/erased_json.rs @@ -3,6 +3,7 @@ use axum::{ http::{header, HeaderValue, StatusCode}, response::{IntoResponse, Response}, }; +use bytes::{BufMut, Bytes, BytesMut}; use serde::Serialize; /// A response type that holds a JSON in serialized form. @@ -30,17 +31,19 @@ use serde::Serialize; /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "erased-json")))] #[derive(Debug)] -pub struct ErasedJson(serde_json::Result>); +pub struct ErasedJson(serde_json::Result); impl ErasedJson { /// Create an `ErasedJson` by serializing a value with the compact formatter. pub fn new(val: T) -> Self { - Self(serde_json::to_vec(&val)) + let mut bytes = BytesMut::with_capacity(128); + Self(serde_json::to_writer((&mut bytes).writer(), &val).map(|_| bytes.freeze())) } /// Create an `ErasedJson` by serializing a value with the pretty formatter. pub fn pretty(val: T) -> Self { - Self(serde_json::to_vec_pretty(&val)) + let mut bytes = BytesMut::with_capacity(128); + Self(serde_json::to_writer_pretty((&mut bytes).writer(), &val).map(|_| bytes.freeze())) } } @@ -57,7 +60,7 @@ impl IntoResponse for ErasedJson { } }; - let mut res = Response::new(body::boxed(Full::from(bytes))); + let mut res = Response::new(body::boxed(Full::new(bytes))); res.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),