Skip to main content

Limits

Struct Limits 

Source
#[non_exhaustive]
pub struct Limits { pub max_depth: usize, pub max_input_bytes: usize, pub max_string_bytes: usize, pub max_number_bytes: usize, pub max_elements: usize, }
Expand description

Budgets on the work and memory a document may cost.

Every budget is checked before the memory it guards is allocated, so a hostile document is refused while it is still cheap to refuse. None of them is there to protect the stack: the parser, the writer, and every operation on Value use a bounded amount of stack whatever the nesting depth (explicit stacks on the heap; drop recurses at most a fixed 32 levels). The depth budget exists for the code that consumes the value, which may well be recursive.

BudgetDefaultCounts
max_depth128nested arrays and objects; a scalar at the top is depth 0, [] is 1
max_input_bytes64 MiBbytes of input
max_string_bytes16 MiBsource bytes between a string’s quotes, keys included
max_number_bytes1 KiBbytes of a number’s text
max_elements4 Mivalues in the document: every scalar, array, and object counts one

The depth default matches serde_json’s recursion limit, so code moving from it sees the same behaviour. A string’s budget is measured in source bytes, which is never less than its decoded length, so the check can run before the string is decoded.

The struct is #[non_exhaustive]: start from Limits::default or Limits::unlimited and change the fields you care about, or chain the with_* methods.

§Examples

use jsonx_lib::{Limits, Parser, ErrorKind};

let strict = Parser::new().limits(Limits::default().with_max_depth(2));
assert!(strict.parse("[[1]]").is_ok());
let err = strict.parse("[[[1]]]").unwrap_err();
assert_eq!(err.kind(), ErrorKind::DepthLimitExceeded);
assert_eq!(err.offset(), 2);

let mut limits = Limits::default();
limits.max_string_bytes = 4;
assert!(Parser::new().limits(limits).parse(r#""abcde""#).is_err());

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§max_depth: usize

The deepest nesting of arrays and objects allowed. 0 allows only a scalar document.

§max_input_bytes: usize

The longest input accepted, in bytes.

§max_string_bytes: usize

The longest string or key accepted, in source bytes between the quotes (escape sequences count at their written length).

§max_number_bytes: usize

The longest number accepted, in bytes of its text.

§max_elements: usize

The most values a document may hold, counting every scalar, array, and object (keys are not counted separately).

Implementations§

Source§

impl Limits

Source

pub const fn new() -> Self

The default budgets (see the table on Limits): generous for real documents, small enough that a hostile one cannot exhaust memory.

§Examples
use jsonx_lib::Limits;

assert_eq!(Limits::new().max_depth, 128);
assert_eq!(Limits::new(), Limits::default());
Source

pub const fn unlimited() -> Self

No budgets at all: every limit is usize::MAX. For input you trust; even then the parser cannot overflow the stack, because nothing in this crate recurses on nesting depth.

§Examples
use jsonx_lib::{Limits, Parser};

let deep = format!("{}{}", "[".repeat(1000), "]".repeat(1000));
assert!(Parser::new().limits(Limits::unlimited()).parse(&deep).is_ok());
Source

pub const fn with_max_depth(self, depth: usize) -> Self

Sets max_depth.

§Examples
use jsonx_lib::Limits;

assert_eq!(Limits::new().with_max_depth(8).max_depth, 8);
Source

pub const fn with_max_input_bytes(self, bytes: usize) -> Self

Sets max_input_bytes.

§Examples
use jsonx_lib::{ErrorKind, Limits, Parser};

let p = Parser::new().limits(Limits::new().with_max_input_bytes(4));
assert!(p.parse("1234").is_ok());
assert_eq!(p.parse("12345").unwrap_err().kind(), ErrorKind::InputTooLarge);
Source

pub const fn with_max_string_bytes(self, bytes: usize) -> Self

Sets max_string_bytes.

§Examples
use jsonx_lib::{ErrorKind, Limits, Parser};

let p = Parser::new().limits(Limits::new().with_max_string_bytes(2));
assert!(p.parse(r#"{"ab": "cd"}"#).is_ok());
assert_eq!(p.parse(r#"{"abc": 1}"#).unwrap_err().kind(), ErrorKind::StringTooLong);
Source

pub const fn with_max_number_bytes(self, bytes: usize) -> Self

Sets max_number_bytes.

§Examples
use jsonx_lib::{ErrorKind, Limits, Parser};

let p = Parser::new().limits(Limits::new().with_max_number_bytes(3));
assert!(p.parse("-12").is_ok());
assert_eq!(p.parse("1e10").unwrap_err().kind(), ErrorKind::NumberTooLong);
Source

pub const fn with_max_elements(self, count: usize) -> Self

Sets max_elements.

§Examples
use jsonx_lib::{ErrorKind, Limits, Parser};

// The array itself is one value, so `[1, 2]` holds three.
let p = Parser::new().limits(Limits::new().with_max_elements(3));
assert!(p.parse("[1, 2]").is_ok());
assert_eq!(p.parse("[1, 2, 3]").unwrap_err().kind(), ErrorKind::TooManyElements);

Trait Implementations§

Source§

impl Clone for Limits

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Limits

Source§

impl Debug for Limits

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Limits

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for Limits

Source§

impl Hash for Limits

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Limits

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Limits

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.