pub struct PreparedJson<T> { /* private fields */ }Expand description
A JSON response body the operation encoded itself.
Json<T> is encoded after the operation has returned, so the value it
wraps has to own everything it prints. An operation that reads from a lock
guard, an arena, or a shared corpus therefore has to clone every string it
wants to include, and those clones are freed again a few microseconds later
once the body has been written.
PreparedJson<T> moves the encode step inside the operation, where those
borrows are still alive, and carries the finished bytes to the transport
untouched. A listing operation can build a borrowed view over the store,
encode it while it still holds the read guard, and never allocate an owned
mirror of the data at all.
The type parameter carries the documented schema and nothing else: the
operation still advertises T in OpenAPI, MCP, and compatibility
analysis, exactly as Json<T> would.
§Contract
The framework does not re-parse the bytes, so it cannot check them against
T. The operation asserts that the body it encoded is a valid instance of
the schema it declares. Use PreparedJson::encode with a value whose
serialized shape matches T; PreparedJson::from_bytes hands the same
obligation to the caller for bytes produced some other way.
§Examples
use blazingly_core::{ApiSchema, PreparedJson, SchemaKind, TypeDescriptor};
use serde::Serialize;
#[derive(Serialize)]
struct BorrowedPage<'store> {
items: Vec<&'store str>,
}
let store = vec![String::from("first"), String::from("second")];
let view = BorrowedPage {
items: store.iter().map(String::as_str).collect(),
};
let body = PreparedJson::<Page>::encode(&view).expect("the view encodes");
assert_eq!(body.as_bytes(), br#"{"items":["first","second"]}"#);Implementations§
Source§impl<T> PreparedJson<T>
impl<T> PreparedJson<T>
Sourcepub const fn from_bytes(body: Vec<u8>) -> Self
pub const fn from_bytes(body: Vec<u8>) -> Self
Adopts bytes the caller has already encoded.
The bytes are sent verbatim; see the type-level contract note.
pub fn as_bytes(&self) -> &[u8] ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
pub const fn len(&self) -> usize
pub const fn is_empty(&self) -> bool
Sourcepub fn encode<V>(value: &V) -> Result<Self, Error>
pub fn encode<V>(value: &V) -> Result<Self, Error>
Encodes value into the response body now.
value may borrow from anything alive at the call site, which is the
whole point: it is encoded before the borrow ends.
§Errors
Returns the blazingly_json failure when value cannot be encoded, for
instance because a map key is not a string.