Skip to main content

JsonEncoder

Struct JsonEncoder 

Source
pub struct JsonEncoder<'budget, R = JsonResource, Q = usize>{ /* private fields */ }
Expand description

Encodes strict JSON text while owning cumulative accounting state.

Signed and unsigned 64-bit integers are supported in full. Serde i128 values are accepted only when they fit i64, or are non-negative and fit u64; u128 values must fit u64. Wider integers return a serialization error instead of being truncated or converted to strings. Floating-point values must be finite.

Nested serialization errors remain failures of the complete operation even when an enclosing custom Serialize implementation ignores them. Arbitrary custom error text is not retained. Incremental output may already contain an accepted prefix when an error is reported.

§Type Parameters

  • 'budget - Lifetime of the caller-provided cumulative encode session.
  • R - Resource identity tracked by the encode session.
  • Q - Quantity representation used for resource accounting.

§Examples

use qubit_json::encode::JsonEncoder;

let mut encoder = JsonEncoder::unlimited();
let bytes = encoder.to_vec(&serde_json::json!({"ok": true}))?;
assert_eq!(bytes, br#"{"ok":true}"#);

Implementations§

Source§

impl<R, Q> JsonEncoder<'static, R, Q>
where R: Clone + Debug, Q: ResourceQuantity,

Source

pub fn with_limits(limits: JsonEncodeLimits<R, Q>) -> Self

Creates an encoder with an owned session built from explicit limits.

§Parameters
  • limits - Resource limits used to construct the cumulative session.
§Returns

An encoder whose cumulative accounting starts empty and is constrained by limits.

Source§

impl JsonEncoder<'static, JsonResource, usize>

Source

pub fn unlimited() -> Self

Creates an encoder with an explicitly unlimited standard session.

§Returns

An encoder with no configured output or encoded-value limits.

Source§

impl<'budget, R, Q> JsonEncoder<'budget, R, Q>
where R: Clone + Debug, Q: ResourceQuantity,

Source

pub fn new(session: JsonEncodeSession<'budget, R, Q>) -> Self

Creates an encoder that owns a reusable cumulative session.

§Parameters
  • session - Session that receives committed output accounting.
§Returns

An encoder that retains session until Self::into_session is called or the encoder is dropped.

Source

pub const fn session(&self) -> &JsonEncodeSession<'budget, R, Q>

Returns the cumulative session for read-only inspection.

The reference exposes cumulative accounting state. Bytes accepted by an external destination remain charged even when the encode operation fails; value-resource charges commit only after the complete operation succeeds. The reference remains borrowed from this encoder.

§Returns

A shared reference to the cumulative encode session.

Source

pub const fn session_mut(&mut self) -> &mut JsonEncodeSession<'budget, R, Q>

Returns mutable access to the cumulative session.

Changes made through the reference affect the limits and accounting state used by subsequent encode operations.

§Returns

A mutable reference to the cumulative encode session.

Source

pub fn into_session(self) -> JsonEncodeSession<'budget, R, Q>

Returns the cumulative session and consumes the encoder.

No output is produced and no accounting is reset; ownership of the accumulated state is transferred to the caller.

§Returns

The session previously owned by this encoder.

Source

pub fn to_vec<T>(&mut self, value: &T) -> Result<Vec<u8>, JsonEncodeError<R, Q>>
where T: Serialize + ?Sized,

Encodes value into compact JSON and commits only complete success.

§Type Parameters
  • T - Source type serialized into JSON.
§Parameters
  • value - Value to serialize.
§Returns

The compact JSON bytes on success.

§Errors

Returns JsonEncodeErrorKind::Budget when accounting rejects the value or output, JsonEncodeErrorKind::InvalidRawJson when a RawValue or private raw payload fails this encoder’s strict JSON admission, or a serialization error when Serde rejects value. Inspect JsonEncodeError::syntax_error for the structured syntax reason.

Source

pub fn write_buffered<O, T>( &mut self, writer: &mut O, value: &T, ) -> Result<(), JsonEncodeError<R, Q>>
where O: ByteOutput + ?Sized, T: Serialize + ?Sized,

Buffers a complete document before writing it to writer.

Success means writer accepted the complete document and output/value accounting was committed. This method does not flush the writer. If the writer buffers output, call its Write::flush method after this call succeeds. The writer is borrowed mutably for this call. A later flush failure is outside this encoding transaction and does not roll back accounting already committed by this method. A successful flush only reports the writer’s result; it does not confirm persistence to disk or receipt by a remote peer.

§Examples
use std::io::{BufWriter, Write};
use qubit_budget::json::{JsonEncodeLimits, JsonResource};
use qubit_json::encode::JsonEncoder;
use serde_json::json;

let limits = JsonEncodeLimits::<JsonResource, usize>::builder()
    .max_output_bytes(64)
    .build();
let mut encoder = JsonEncoder::with_limits(limits);
let mut writer = BufWriter::new(Vec::new());
encoder.write_buffered(&mut writer, &json!({"ok": true}))?;
writer.flush()?;
let bytes = writer.into_inner().expect("flush already succeeded");
assert_eq!(bytes, br#"{"ok":true}"#);
§Type Parameters
  • O - Destination output type.
  • T - Source type serialized into JSON.
§Parameters
  • writer - Destination receiving the complete JSON document.
  • value - Value to serialize.
§Returns

Ok(()) after the complete document is written and accounting is committed.

§Errors

Returns JsonEncodeErrorKind::Budget when accounting rejects the value or output, JsonEncodeErrorKind::InvalidRawJson when a RawValue or private raw payload fails this encoder’s strict JSON admission, a serialization error when Serde rejects value, or a writer error when writing fails. Inspect JsonEncodeError::syntax_error for the structured syntax reason.

Source

pub fn write_incremental<O, T>( &mut self, writer: &mut O, value: &T, ) -> Result<(), JsonEncodeError<R, Q>>
where O: ByteOutput + ?Sized, T: Serialize + ?Sized,

Streams value directly to writer, retaining accepted prefixes.

After serialization succeeds, this method flushes writer before committing value-resource accounting. A flush failure is reported as a writer error, and bytes already accepted remain charged to the output budget while value-resource accounting is not committed. A successful flush only reports the writer’s result; it does not confirm persistence to disk or receipt by a remote peer. The writer is borrowed mutably for this call. Do not rely on Drop to flush buffered output.

§Type Parameters
  • O - Destination output type.
  • T - Source type serialized into JSON.
§Parameters
  • writer - Destination receiving streamed JSON bytes.
  • value - Value to serialize.
§Returns

Ok(()) after serialization and output accounting complete.

§Errors

Returns JsonEncodeErrorKind::Budget when accounting rejects value resources or output bytes, JsonEncodeErrorKind::InvalidRawJson when a RawValue or private raw payload fails this encoder’s strict JSON admission, a serialization error when Serde rejects value, or a writer error when writing or flushing fails. Inspect JsonEncodeError::syntax_error for the structured syntax reason. Accepted output prefixes remain written and charged when a later operation fails; value-resource charges commit only after the complete operation succeeds.

Auto Trait Implementations§

§

impl<'budget, R = JsonResource, Q = usize> !UnwindSafe for JsonEncoder<'budget, R, Q>

§

impl<'budget, R, Q> Freeze for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: Freeze,

§

impl<'budget, R, Q> RefUnwindSafe for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: RefUnwindSafe,

§

impl<'budget, R, Q> Send for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: Send,

§

impl<'budget, R, Q> Sync for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: Sync,

§

impl<'budget, R, Q> Unpin for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: Unpin,

§

impl<'budget, R, Q> UnsafeUnpin for JsonEncoder<'budget, R, Q>
where JsonEncodeSession<'budget, R, Q>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.