OwnedJsonb

Struct OwnedJsonb 

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

Represents a JSONB data that owns its underlying data.

This struct provides ownership over the binary JSONB representation. OwnedJsonb is primarily used to create JSONB data from other data types (such as JSON String). However, for most operations, it’s necessary to convert an OwnedJsonb to a RawJsonb using the as_raw() method to avoid unnecessary copying and to take advantage of the performance benefits of the read-only access of the RawJsonb.

Implementations§

Source§

impl OwnedJsonb

Source

pub fn new(data: Vec<u8>) -> OwnedJsonb

Creates a new OwnedJsonb from a Vec.

§Arguments
  • data - The Vec<u8> containing the JSONB data.
§Returns

A new OwnedJsonb instance.

Source

pub fn as_raw(&self) -> RawJsonb<'_>

Creates a RawJsonb view of the owned data. This is useful for passing the data to functions that expect a RawJsonb. This does not transfer ownership.

§Returns

A RawJsonb instance referencing the owned data.

Source

pub fn to_vec(self) -> Vec<u8>

Consumes the OwnedJsonb and returns the underlying Vec.

§Returns

The underlying Vec<u8> containing the JSONB data.

Source

pub fn is_empty(&self) -> bool

Checks if the JSONB data is empty.

§Returns

true if the data is empty, false otherwise.

Source

pub fn len(&self) -> usize

Returns the length of the JSONB data in bytes.

§Returns

The length of the data in bytes.

Source

pub fn build_array<'a>( raw_jsonbs: impl IntoIterator<Item = RawJsonb<'a>>, ) -> Result<OwnedJsonb, Error>

Builds a JSONB array from a collection of RawJsonb values.

This function constructs a new JSONB array from an iterator of RawJsonb values. The resulting OwnedJsonb represents the binary encoding of the array.

§Arguments
  • items - An iterator of RawJsonb values representing the elements of the array.
§Returns
  • Ok(OwnedJsonb) - The newly created JSONB array.
  • Err(Error) - If any of the input RawJsonb values are invalid or if an error occurs during array construction.
§Examples
use jsonb::OwnedJsonb;
use jsonb::RawJsonb;

// Create some RawJsonb values
let owned_num = "1".parse::<OwnedJsonb>().unwrap();
let owned_str = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let owned_arr = "[1,2,3]".parse::<OwnedJsonb>().unwrap();

// Build the array
let raw_jsonbs = vec![owned_num.as_raw(), owned_str.as_raw(), owned_arr.as_raw()];
let array_result = OwnedJsonb::build_array(raw_jsonbs.into_iter());
assert!(array_result.is_ok());
let array = array_result.unwrap();

// Convert to string for easy verification
assert_eq!(array.to_string(), "[1,\"hello\",[1,2,3]]");

// Example with an empty iterator
let empty_array =
    OwnedJsonb::build_array(<[RawJsonb<'_>; 0] as IntoIterator>::into_iter([])).unwrap();
assert_eq!(empty_array.to_string(), "[]");

// Example with invalid input (this will cause an error)
let invalid_data = OwnedJsonb::new(vec![1, 2, 3, 4]);
let result = OwnedJsonb::build_array([invalid_data.as_raw()].into_iter());
assert!(result.is_err());
Source

pub fn build_object<'a, K: AsRef<str>>( items: impl IntoIterator<Item = (K, RawJsonb<'a>)>, ) -> Result<OwnedJsonb, Error>

Builds a JSONB object from a collection of key-value pairs.

This function constructs a new JSONB object from an iterator of key-value pairs. The keys are strings, and the values are RawJsonb values. The resulting OwnedJsonb represents the binary encoding of the object.

§Arguments
  • items - An iterator of (K, &'a RawJsonb<'a>) tuples, where K is a type that can be converted into a string slice (AsRef<str>) representing the key, and the second element is a RawJsonb representing the value.
§Returns
  • Ok(OwnedJsonb) - The newly created JSONB object.
  • Err(Error) - If any of the input RawJsonb values are invalid, if contain duplicate keys, or if an error occurs during object construction.
§Examples
use jsonb::OwnedJsonb;
use jsonb::RawJsonb;

// Create some RawJsonb values
let owned_num = "1".parse::<OwnedJsonb>().unwrap();
let owned_str = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let owned_arr = "[1,2,3]".parse::<OwnedJsonb>().unwrap();

// Build the object
let raw_jsonbs = vec![
    ("a", owned_num.as_raw()),
    ("b", owned_str.as_raw()),
    ("c", owned_arr.as_raw()),
];
let object_result = OwnedJsonb::build_object(raw_jsonbs.into_iter());
assert!(object_result.is_ok());
let object = object_result.unwrap();

// Convert to string for easy verification
assert_eq!(object.to_string(), r#"{"a":1,"b":"hello","c":[1,2,3]}"#);

// Example with an empty iterator
let empty_object =
    OwnedJsonb::build_object(<[(&str, RawJsonb<'_>); 0] as IntoIterator>::into_iter([]))
        .unwrap();
assert_eq!(empty_object.to_string(), "{}");

// Example with invalid value
let invalid_data = OwnedJsonb::new(vec![1, 2, 3, 4]);
let result = OwnedJsonb::build_object([("a", invalid_data.as_raw())].into_iter());
assert!(result.is_err());

Trait Implementations§

Source§

impl AsRef<[u8]> for OwnedJsonb

Allows accessing the underlying byte slice as a reference. This enables easy integration with functions that expect a &[u8].

Source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for OwnedJsonb

Source§

fn clone(&self) -> OwnedJsonb

Returns a duplicate 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 Debug for OwnedJsonb

Source§

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

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

impl Display for OwnedJsonb

Implements the Display trait, allowing OwnedJsonb to be formatted as a string using the {} format specifier.

Source§

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

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

impl From<&[u8]> for OwnedJsonb

Creates an OwnedJsonb from a borrowed byte slice. The byte slice is copied into a new Vec<u8>.

Source§

fn from(data: &[u8]) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for OwnedJsonb

Creates an OwnedJsonb from a Vec<u8>. This is a simple ownership transfer.

Source§

fn from(data: Vec<u8>) -> Self

Converts to this type from the input type.
Source§

impl FromStr for OwnedJsonb

Parses a string into an OwnedJsonb. The string is parsed into a JSON value, then encoded into the binary JSONB format.

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Ord for OwnedJsonb

Implements Ord for OwnedJsonb, allowing comparison of two OwnedJsonb values using the total ordering. This implementation leverages the PartialOrd implementation, returning Ordering::Equal for incomparable values.

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 OwnedJsonb

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 OwnedJsonb

Implements PartialOrd for OwnedJsonb, allowing comparison of two OwnedJsonb values.

The comparison logic handles different JSONB types (scalar, array, object) and considers null values. The ordering is defined as follows:

  1. Null is considered greater than any other type.
  2. Scalars are compared based on their type and value (String > Number > Boolean).
  3. Arrays are compared element by element.
  4. Objects are compared based on their keys and values.
  5. Arrays are greater than objects and scalars.
  6. Objects are greater than scalars.
  7. If the types are incompatible, None is returned.
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 Eq for OwnedJsonb

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<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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 = 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V