sonic_rs

Struct LazyValue

Source
pub struct LazyValue<'a> { /* private fields */ }
Expand description

LazyValue wrappers a unparsed raw JSON text. It is borrowed from the origin JSON text.

LazyValue can be get, get_unchecked or deserialize from a JSON text.

§Examples

use sonic_rs::{get, JsonValueTrait, LazyValue, Value};

// get a lazyvalue from a json, the "a"'s value will not be parsed
let input = r#"{
 "a": "hello world",
 "b": true,
 "c": [0, 1, 2],
 "d": {
    "sonic": "rs"
  }
}"#;
let lv_a: LazyValue = get(input, &["a"]).unwrap();
let lv_c: LazyValue = get(input, &["c"]).unwrap();

// use as_raw_xx to get the unparsed JSON text
assert_eq!(lv_a.as_raw_str(), "\"hello world\"");
assert_eq!(lv_c.as_raw_str(), "[0, 1, 2]");

// use as_xx to get the parsed value
assert_eq!(lv_a.as_str().unwrap(), "hello world");
assert_eq!(lv_c.as_str(), None);
assert!(lv_c.is_array());

§Serde Examples

LazyValue<'a> can only be deserialized with borrowed. If need to be owned, use OwnedLazyValue.

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct TestLazyValue<'a> {
    #[serde(borrow)]
    borrowed_lv: LazyValue<'a>,
}

let input = r#"{ "borrowed_lv": "hello"}"#;

let data: TestLazyValue = sonic_rs::from_str(input).unwrap();
assert_eq!(data.borrowed_lv.as_raw_str(), "\"hello\"");

§Convert to serde_json::Value

LazyValue<'a> can convert into serde_json::Value from bytes slice.

 use sonic_rs::{pointer, JsonValueTrait};

 let json: &str = r#"{
     "bool": true,
     "int": -1,
     "uint": 0,
     "float": 1.1,
     "string": "hello",
     "string_escape": "\"hello\"",
     "array": [1,2,3],
     "object": {"a":"aaa"},
     "strempty": "",
     "objempty": {},
     "arrempty": []
 }"#;
 let lazy_value = sonic_rs::get(json, pointer![].iter()).unwrap();

 for (key, expect_value) in [
     ("bool", serde_json::json!(true)),
     ("int", serde_json::json!(-1)),
     ("uint", serde_json::json!(0)),
     ("float", serde_json::json!(1.1)),
     ("string", serde_json::json!("hello")),
     ("string_escape", serde_json::json!("\"hello\"")),
     ("array", serde_json::json!([1, 2, 3])),
     ("object", serde_json::json!({"a":"aaa"})),
     ("strempty", serde_json::json!("")),
     ("objempty", serde_json::json!({})),
     ("arrempty", serde_json::json!([])),
 ] {
     let value = lazy_value.get(key);

     let trans_value =
         serde_json::from_slice::<serde_json::Value>(value.unwrap().as_raw_str().as_bytes())
             .unwrap();
     assert_eq!(trans_value, expect_value);
     println!("checked {key} with {trans_value:?}");
 }

Implementations§

Source§

impl<'a> LazyValue<'a>

Source

pub fn as_raw_str(&self) -> &str

Export the raw JSON text as str.

§Examples
use sonic_rs::{get, LazyValue};

let lv: LazyValue = sonic_rs::get(r#"{"a": "hello world"}"#, &["a"]).unwrap();
assert_eq!(lv.as_raw_str(), "\"hello world\"");
Source

pub fn as_raw_cow(&self) -> Cow<'a, str>

Export the raw JSON text as Cow<'de, str>. The lifetime 'de is the origin JSON.

§Examples
use sonic_rs::{get, LazyValue};

let lv: LazyValue = sonic_rs::get(r#"{"a": "hello world"}"#, &["a"]).unwrap();
assert_eq!(lv.as_raw_cow(), "\"hello world\"");
Source

pub fn as_raw_faststr(&self) -> FastStr

Export the raw json text as faststr.

§Note

If the input json is not bytes or faststr, there will be a string copy.

§Examples
use faststr::FastStr;
use sonic_rs::LazyValue;

let lv: LazyValue = sonic_rs::get(r#"{"a": "hello world"}"#, &["a"]).unwrap();
// will copy the raw_str into a new faststr
assert_eq!(lv.as_raw_faststr(), "\"hello world\"");

let fs = FastStr::new(r#"{"a": "hello world"}"#);
let lv: LazyValue = sonic_rs::get(&fs, &["a"]).unwrap();
assert_eq!(lv.as_raw_faststr(), "\"hello world\""); // zero-copy

Trait Implementations§

Source§

impl<'a> Clone for LazyValue<'a>

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for LazyValue<'a>

Source§

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

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

impl Default for LazyValue<'_>

Source§

fn default() -> Self

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

impl<'de: 'a, 'a> Deserialize<'de> for LazyValue<'a>

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<'a> Display for LazyValue<'a>

Source§

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

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

impl<'de> From<LazyValue<'de>> for OwnedLazyValue

Source§

fn from(lv: LazyValue<'de>) -> Self

Converts to this type from the input type.
Source§

impl<'a> Hash for LazyValue<'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> JsonValueTrait for LazyValue<'a>

Source§

type ValueType<'v> = LazyValue<'v> where Self: 'v

Source§

fn as_bool(&self) -> Option<bool>

Returns the bool if self is a boolean. Read more
Source§

fn as_number(&self) -> Option<Number>

Returns the Number if self is a Number. Read more
Source§

fn as_raw_number(&self) -> Option<RawNumber>

Returns the RawNumber without precision loss if self is a Number.
Source§

fn as_str(&self) -> Option<&str>

Returns the str if self is a string. Read more
Source§

fn get_type(&self) -> JsonType

Gets the type of the value. Returns JsonType::Null as default if self is Option::None or Result::Err(_). Read more
Source§

fn get<I: Index>(&self, index: I) -> Option<LazyValue<'_>>

Index into a JSON array or map. A string-like index can be used to access a value in a map, and a usize index can be used to access an element of an array. Read more
Source§

fn pointer<P: IntoIterator>(&self, path: P) -> Option<LazyValue<'_>>
where P::Item: Index,

Looks up a value by a path. Read more
Source§

fn is_boolean(&self) -> bool

Returns true if the value is a bool. Read more
Source§

fn is_true(&self) -> bool

Returns true if the value is true. Read more
Source§

fn is_false(&self) -> bool

Returns true if the value is false. Read more
Source§

fn is_null(&self) -> bool

Returns true if the self value is null. Read more
Source§

fn is_number(&self) -> bool

Returns true if the value is a number. Read more
Source§

fn is_str(&self) -> bool

Returns true if the value is a string. Read more
Source§

fn is_array(&self) -> bool

Returns true if the value is an array. Read more
Source§

fn is_object(&self) -> bool

Returns true if the value is an object. Read more
Source§

fn is_f64(&self) -> bool

Returns true if the value is a number and it is an f64. It will returns false if the value is a u64 or i64. Read more
Source§

fn is_i64(&self) -> bool

Returns true if the value is a integer number and it between i64::MIN and i64::MAX Read more
Source§

fn is_u64(&self) -> bool

Returns true if the value is a integer number and it between 0 and i64::MAX Read more
Source§

fn as_i64(&self) -> Option<i64>

If self meets is_i64, represent it as i64 if possible. Returns None otherwise. Read more
Source§

fn as_u64(&self) -> Option<u64>

If self meets is_i64, represent it as u64 if possible. Returns None otherwise. Read more
Source§

fn as_f64(&self) -> Option<f64>

If self is a number, represent it as f64 if possible. Returns None otherwise. The integer number will be converted to f64. Read more
Source§

impl<'a> Ord for LazyValue<'a>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for LazyValue<'_>

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for LazyValue<'_>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a> Serialize for LazyValue<'a>

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<'de> TryFrom<LazyValue<'de>> for Value

Try parse a LazyValue into a Value. LazyValue is always a valid JSON, at least it is followed the JSON syntax.

However, in some cases, the parse will failed and return errors, such as the float number in JSON is inifity.

Source§

type Error = Error

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

fn try_from(value: LazyValue<'de>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<'a> Eq for LazyValue<'a>

Auto Trait Implementations§

§

impl<'a> !Freeze for LazyValue<'a>

§

impl<'a> RefUnwindSafe for LazyValue<'a>

§

impl<'a> Send for LazyValue<'a>

§

impl<'a> Sync for LazyValue<'a>

§

impl<'a> Unpin for LazyValue<'a>

§

impl<'a> UnwindSafe for LazyValue<'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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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§

default 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,