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 Clone for ErasedJson #2142

Merged
merged 2 commits into from
Aug 2, 2023
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
4 changes: 3 additions & 1 deletion axum-extra/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ and this project adheres to [Semantic Versioning].

# Unreleased

- **added:** Added `TypedHeader` which used to be in `axum` ([#1850])
- **added:** `TypedHeader` which used to be in `axum` ([#1850])
- **added:** `Clone` implementation for `ErasedJson` ([#2142])

[#1850]: https://github.com/tokio-rs/axum/pull/1850
[#2142]: https://github.com/tokio-rs/axum/pull/2142

# 0.7.4 (18. April, 2023)

Expand Down
18 changes: 14 additions & 4 deletions axum-extra/src/response/erased_json.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use axum::{
http::{header, HeaderValue, StatusCode},
response::{IntoResponse, Response},
Expand Down Expand Up @@ -29,21 +31,29 @@ use serde::Serialize;
/// }
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "erased-json")))]
#[derive(Debug)]
#[derive(Clone, Debug)]
#[must_use]
pub struct ErasedJson(serde_json::Result<Bytes>);
pub struct ErasedJson(Result<Bytes, Arc<serde_json::Error>>);

impl ErasedJson {
/// Create an `ErasedJson` by serializing a value with the compact formatter.
pub fn new<T: Serialize>(val: T) -> Self {
let mut bytes = BytesMut::with_capacity(128);
Self(serde_json::to_writer((&mut bytes).writer(), &val).map(|_| bytes.freeze()))
let result = match serde_json::to_writer((&mut bytes).writer(), &val) {
Ok(()) => Ok(bytes.freeze()),
Err(e) => Err(Arc::new(e)),
};
Self(result)
}

/// Create an `ErasedJson` by serializing a value with the pretty formatter.
pub fn pretty<T: Serialize>(val: T) -> Self {
let mut bytes = BytesMut::with_capacity(128);
Self(serde_json::to_writer_pretty((&mut bytes).writer(), &val).map(|_| bytes.freeze()))
let result = match serde_json::to_writer_pretty((&mut bytes).writer(), &val) {
Ok(()) => Ok(bytes.freeze()),
Err(e) => Err(Arc::new(e)),
};
Self(result)
}
}

Expand Down