Skip to main content

Parser

Struct Parser 

Source
pub struct Parser { /* private fields */ }
Expand description

A configured parser: Limits and a DuplicateKeys policy.

parse is Parser::new().parse. Build a Parser to change a budget or the duplicate-key policy; it is a small Copy value that can be kept in a const or a struct and reused for any number of documents.

§Examples

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

// Messages from the network: small and shallow.
const WIRE: Parser = Parser::new()
    .limits(Limits::new().with_max_input_bytes(1 << 20).with_max_depth(32))
    .duplicate_keys(DuplicateKeys::Error);

assert!(WIRE.parse(r#"{"ok": true}"#).is_ok());
let deep = "[".repeat(33);
assert_eq!(WIRE.parse(&deep).unwrap_err().kind(), ErrorKind::DepthLimitExceeded);

Implementations§

Source§

impl Parser

Source

pub fn decode<'de, T: FromJson<'de>>( &self, text: &'de str, ) -> Result<T, DecodeError>

Reads text as one T with this parser’s budgets and duplicate-key policy; see from_str.

§Errors

As from_str.

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

let shallow = Parser::new().limits(Limits::new().with_max_depth(1));
assert_eq!(shallow.decode::<Vec<u8>>("[1]")?, [1]);
let err = shallow.decode::<Vec<Vec<u8>>>("[[1]]").unwrap_err();
assert_eq!(err.syntax_error().map(|e| e.kind()), Some(ErrorKind::DepthLimitExceeded));
Source

pub fn decode_bytes<'de, T: FromJson<'de>>( &self, bytes: &'de [u8], ) -> Result<T, DecodeError>

Reads bytes, which must be UTF-8, as one T; see decode.

§Errors

As from_bytes.

§Examples
assert_eq!(jsonx_lib::Parser::new().decode_bytes::<&str>(b"\"x\"")?, "x");
Source§

impl Parser

Source

pub const fn new() -> Self

A parser with the default Limits and DuplicateKeys::Error.

§Examples
assert_eq!(jsonx_lib::Parser::new().parse("[]")?.to_string(), "[]");
Source

pub const fn limits(self, limits: Limits) -> Self

Replaces the budgets.

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

let p = Parser::new().limits(Limits::new().with_max_string_bytes(3));
assert_eq!(p.parse(r#""four""#).unwrap_err().kind(), ErrorKind::StringTooLong);
Source

pub const fn duplicate_keys(self, policy: DuplicateKeys) -> Self

Sets the duplicate-key policy.

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

let p = Parser::new().duplicate_keys(DuplicateKeys::Last);
assert_eq!(p.parse(r#"{"k": 1, "k": 2}"#)?["k"], 2);
Source

pub const fn numbers(self, numbers: Numbers) -> Self

Sets how typed reads take integers; see Numbers.

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

let p = Parser::new().numbers(Numbers::WholeValues);
assert_eq!(p.get_numbers(), Numbers::WholeValues);
Source

pub const fn get_numbers(&self) -> Numbers

The parser’s Numbers setting.

§Examples
assert_eq!(jsonx_lib::Parser::new().get_numbers(), jsonx_lib::Numbers::IntegerText);
Source

pub const fn get_limits(&self) -> Limits

The parser’s budgets.

§Examples
assert_eq!(jsonx_lib::Parser::new().get_limits().max_depth, 128);
Source

pub const fn get_duplicate_keys(&self) -> DuplicateKeys

The parser’s duplicate-key policy.

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

assert_eq!(Parser::new().get_duplicate_keys(), DuplicateKeys::Error);
Source

pub fn parse<'a>(&self, text: &'a str) -> Result<Value<'a>, Error>

Parses one JSON document.

The whole input must be exactly one value, with optional whitespace around it (space, tab, line feed, carriage return; nothing else, not even a byte-order mark). Strings without escapes and all numbers borrow from text.

§Errors

The first syntax error or exceeded budget, at its byte offset; see ErrorKind for every case.

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

let v = Parser::new().parse(" [1, \"two\"] ")?;
assert_eq!(v[1], "two");

let err = Parser::new().parse("[1] [2]").unwrap_err();
assert_eq!((err.kind(), err.offset()), (ErrorKind::TrailingCharacters, 4));
Source

pub fn parse_bytes<'a>(&self, bytes: &'a [u8]) -> Result<Value<'a>, Error>

Parses one JSON document from bytes, which must be UTF-8 (RFC 8259 §8.1). The size budget is checked first, then the encoding, then the syntax.

§Errors

ErrorKind::InputTooLarge, then ErrorKind::InvalidUtf8 at the first byte of the first invalid sequence, then as parse.

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

assert_eq!(Parser::new().parse_bytes(b"[\"\xC3\xA9\"]")?[0], "\u{e9}");
let err = Parser::new().parse_bytes(b"[\"\xC3\"]").unwrap_err();
assert_eq!((err.kind(), err.offset()), (ErrorKind::InvalidUtf8, 2));
Source

pub fn reader<'a>(&self, text: &'a str) -> Reader<'a> ⓘ

A Reader over text with this parser’s budgets and duplicate-key policy (which Reader::read_value applies).

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

let mut r = Parser::new().limits(Limits::new().with_max_depth(1)).reader("[[]]");
assert!(r.next_event().is_ok());
assert_eq!(r.next_event().unwrap_err().kind(), ErrorKind::DepthLimitExceeded);
Source

pub fn reader_bytes<'a>(&self, bytes: &'a [u8]) -> Result<Reader<'a>, Error>

A Reader over bytes, which must be UTF-8. The size budget and the encoding are checked here, before any event is read.

§Errors

ErrorKind::InputTooLarge or ErrorKind::InvalidUtf8.

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

let mut r = Parser::new().reader_bytes(b"null")?;
assert_eq!(r.next_event()?, Some(Event::Null));
Source§

impl Parser

Source

pub fn stream_reader(&self) -> StreamReader

A StreamReader with this parser’s budgets and duplicate-key policy (which StreamReader::read_value applies).

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

let mut r = Parser::new().limits(Limits::new().with_max_depth(1)).stream_reader();
r.feed(b"[[]]")?;
assert!(r.next_event().is_ok());
assert_eq!(r.next_event().unwrap_err().kind(), ErrorKind::DepthLimitExceeded);

Trait Implementations§

Source§

impl Clone for Parser

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 Parser

Source§

impl Debug for Parser

Source§

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

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

impl Default for Parser

Source§

fn default() -> Self

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

impl Eq for Parser

Source§

impl Hash for Parser

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 Parser

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 Parser

Auto Trait Implementations§

§

impl Forget for Parser

§

impl Freeze for Parser

§

impl Move for Parser

§

impl RefUnwindSafe for Parser

§

impl Send for Parser

§

impl Sync for Parser

§

impl Unpin for Parser

§

impl UnsafeUnpin for Parser

§

impl UnwindSafe for Parser

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.