Skip to main content

RawValue

Struct RawValue 

Source
pub struct RawValue<'a>(/* private fields */);
Expand description

One complete JSON value kept as its exact source text: validated once, then stored, compared, forwarded, or read later.

This is serde_json’s RawValue. A JSON-RPC server keeps params as a RawValue until the handler for the method knows what type to read it as; a proxy forwards a result without decoding it.

A RawValue always holds exactly one value with no whitespace around it. Every way of making one validates, or takes text this crate has just validated or written: new and from_string check the text, Reader::read_raw_value and FromJson take it from a read that checked it, and encode takes it from this crate’s writer. So writing one (ToJson) copies the text with no second check, and the output stays valid JSON. Under Format::html_safe or Format::ascii the characters those formats escape are escaped inside the text’s strings as well (see ValueWriter::raw); otherwise the text is copied unchanged, U+2028 and U+2029 inside its strings included (the strings the writers make have them escaped; for raw text, use html_safe where that matters).

Valid means grammatical JSON. A RawValue taken under DuplicateKeys::KeepAll, or made by encode from a ToJson that writes a key twice, can hold an object with a repeated key: decode (default policy) refuses that text, parse keeps every member.

§Examples

use jsonx_lib::{DecodeError, FromJson, RawValue, Reader};

struct Request<'a> { method: &'a str, params: RawValue<'a> }

impl<'de> FromJson<'de> for Request<'de> {
    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
        let (mut method, mut params) = (None, None);
        let mut o = reader.read_object()?;
        while let Some(key) = o.next_key()? {
            match &*key {
                "method" => o.field(&mut method)?,
                "params" => o.field(&mut params)?,
                _ => {}
            }
        }
        Ok(Request { method: o.required(method, "method")?, params: o.required(params, "params")? })
    }
}

let req: Request = jsonx_lib::from_str(r#"{"method": "add", "params": [2, 3]}"#)?;
assert_eq!(req.params.as_str(), "[2, 3]"); // not decoded yet
let (a, b): (i32, i32) = req.params.decode()?; // now, once the method is known
assert_eq!(a + b, 5);

Implementations§

Source§

impl<'a> RawValue<'a>

Source

pub fn new(text: &'a str) -> Result<Self, Error>

Validates text as one JSON value under the default Limits and keeps it, minus surrounding whitespace, as a borrowed slice.

§Errors

The parse error of text that is not exactly one JSON value.

§Examples
use jsonx_lib::RawValue;

assert_eq!(RawValue::new(" {\"a\": 1} ")?.as_str(), "{\"a\": 1}");
assert!(RawValue::new("[1,").is_err());
assert!(RawValue::new("1 2").is_err());
Source

pub fn from_string(text: String) -> Result<RawValue<'static>, Error>

Validates an owned string, as new, keeping its buffer when it has no surrounding whitespace.

§Errors

As new.

§Examples
let raw = jsonx_lib::RawValue::from_string(String::from("[true]"))?;
assert_eq!(raw.as_str(), "[true]");
Source

pub fn encode<T: ToJson + ?Sized>(value: &T) -> RawValue<'static>

Writes value as compact JSON and keeps the text.

§Examples
let raw = jsonx_lib::RawValue::encode(&[1, 2]);
assert_eq!(raw.as_str(), "[1,2]");
Source

pub fn as_str(&self) -> &str

The JSON text.

§Examples
assert_eq!(jsonx_lib::RawValue::new("null")?.as_str(), "null");
Source

pub fn into_owned(self) -> RawValue<'static>

Copies borrowed text so the value no longer borrows from the input.

§Examples
let owned = jsonx_lib::RawValue::new(&String::from("1"))?.into_owned();
assert_eq!(owned.as_str(), "1");
Source

pub fn parse(&self) -> Result<Value<'_>, Error>

Parses the text into a Value. The text was validated when the RawValue was made, so no budget applies, and every member is kept as written.

§Errors

None in practice: the text is valid JSON.

§Examples
let raw = jsonx_lib::RawValue::new(r#"{"line": 3}"#)?;
assert_eq!(raw.parse()?["line"], 3);
Source

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

Reads the text as a T (FromJson), with the default Limits (which bound a recursive type’s depth) and duplicate keys refused.

§Errors

The DecodeError of T; offsets count from the start of the raw text.

§Examples
let raw = jsonx_lib::RawValue::new("[1, 2, 3]")?;
assert_eq!(raw.decode::<Vec<u8>>()?, [1, 2, 3]);

Trait Implementations§

Source§

impl<'a> Clone for RawValue<'a>

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 Debug for RawValue<'_>

Source§

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

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

impl Display for RawValue<'_>

Source§

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

Writes the JSON text.

Source§

impl<'a> Eq for RawValue<'a>

Source§

impl<'de> FromJson<'de> for RawValue<'de>

Source§

fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError>

Reads one value from reader, which is positioned where a value comes next. Read more
Source§

fn absent() -> Option<Self>

The value for an object member that is absent, if absence is allowed: None (absence is an error) by default, Some(None) for Option<T>, and Some(Nullable::Absent) for Nullable<T>. Read more
Source§

impl<'a> Hash for RawValue<'a>

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<'a> PartialEq for RawValue<'a>

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<'a> StructuralPartialEq for RawValue<'a>

Source§

impl ToJson for RawValue<'_>

Source§

fn to_json(&self, out: ValueWriter<'_>) -> Written

Writes self as one JSON value.
Source§

fn is_absent(&self) -> bool

Whether ObjectWriter::optional leaves this member out. false, except for Option<T>, where it is is_none(), and the pointer types, which ask what they point to. Read more

Auto Trait Implementations§

§

impl<'a> Forget for RawValue<'a>

§

impl<'a> Freeze for RawValue<'a>

§

impl<'a> Move for RawValue<'a>

§

impl<'a> RefUnwindSafe for RawValue<'a>

§

impl<'a> Send for RawValue<'a>

§

impl<'a> Sync for RawValue<'a>

§

impl<'a> Unpin for RawValue<'a>

§

impl<'a> UnsafeUnpin for RawValue<'a>

§

impl<'a> UnwindSafe for RawValue<'a>

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.