Skip to main content

Metadata

Struct Metadata 

Source
pub struct Metadata(/* private fields */);
Expand description

A structured, key-sorted, typed key-value store for metadata fields.

Metadata stores values as qubit_value::Value, preserving concrete Rust scalar types such as i64, u32, f64, String, and bool. This avoids the ambiguity of a single JSON number type while still allowing callers to store explicit Value::Json values when they really need JSON payloads. Value::Unset retains a declared type but represents no concrete metadata value: typed reads report MetadataError::ValueAccess. When the optional schema or filter features are enabled, their validation and matching APIs treat it as a missing concrete value.

Use Metadata::with for fluent construction and Metadata::set when mutating an existing object. The typed Metadata::get and Metadata::get_ref accessors read strictly; Metadata::convert explicitly converts stored values. Use Metadata::get_raw when the stored runtime qubit_value::Value must be inspected without conversion.

§Examples

use qubit_metadata::Metadata;

let metadata = Metadata::new().with("tenant", "acme");
assert_eq!(metadata.get_ref::<str>("tenant")?, "acme");

Implementations§

Source§

impl Metadata

Source

pub fn new() -> Self

Creates an empty metadata object.

§Returns

An empty metadata object.

Source

pub fn decode_json_slice(input: &[u8]) -> Result<Self, MetadataWireDecodeError>

Decodes a strict metadata JSON envelope using the metadata profile.

§Parameters
  • input - Complete untrusted JSON input.
§Returns

The decoded metadata object.

§Errors

Returns crate::MetadataWireDecodeError::Budget when the document exceeds a shared JSON limit, or InvalidJson for syntax and envelope failures. Domain limits return Domain; unsupported versions return UnsupportedVersion.

Source

pub fn decode_json_slice_with_limits( input: &[u8], limits: MetadataLimits, ) -> Result<Self, MetadataWireDecodeError>

Decodes a strict metadata JSON envelope after applying limits.

§Parameters
  • input - Complete untrusted JSON input.
  • limits - Shared JSON limits for this decoding session.
§Returns

The decoded metadata object.

§Errors

Returns a structured budget error before or during decoding, Domain for entry/key limits, UnsupportedVersion for a version mismatch, or redacted JSON errors for syntax, envelope, and scalar wire failures.

Source

pub fn to_json_vec(&self) -> Result<Vec<u8>, MetadataWireEncodeError>

Encodes this metadata object with the default JSON budget profile.

§Returns

Compact JSON bytes accepted by the strict metadata wire format.

§Errors

Returns crate::MetadataWireEncodeError when the JSON value or output exceeds a configured budget, serialization fails, or the destination writer rejects bytes.

Source

pub fn to_json_vec_with_limits( &self, limits: JsonEncodeLimits, ) -> Result<Vec<u8>, MetadataWireEncodeError>

Encodes this metadata object with caller-provided JSON budgets.

§Parameters
  • limits - Output and JSON-value budgets for this operation.
§Returns

Compact JSON bytes accepted by the strict metadata wire format.

§Errors

Returns crate::MetadataWireEncodeError when the JSON value or output exceeds a configured budget, or serialization fails.

Source

pub fn to_json_writer<W>( &self, writer: W, ) -> Result<(), MetadataWireEncodeError>
where W: Write,

Encodes this metadata object to a writer with the default JSON budget.

§Parameters
  • writer - Destination receiving the complete compact JSON document.
§Errors

Returns crate::MetadataWireEncodeError when encoding exceeds a budget, serialization fails, or writer rejects the output.

Source

pub fn to_json_writer_with_limits<W>( &self, writer: W, limits: JsonEncodeLimits, ) -> Result<(), MetadataWireEncodeError>
where W: Write,

Encodes this metadata object to a writer with caller-provided budgets.

§Parameters
  • writer - Destination receiving the complete compact JSON document.
  • limits - Output and JSON-value budgets for this operation.
§Errors

Returns crate::MetadataWireEncodeError when encoding exceeds a budget, serialization fails, or writer rejects the output.

Source

pub fn is_empty(&self) -> bool

Returns true if there are no entries.

§Returns

true when this object contains no entries.

Source

pub fn len(&self) -> usize

Returns the number of key-value pairs.

§Returns

The number of stored entries.

Source

pub fn contains_key(&self, key: &str) -> bool

Returns true if the given key exists, including when it stores Value::Unset.

§Parameters
  • key - Metadata key to inspect.
§Returns

true when an entry exists for key.

Source

pub fn get<T: StrictValueRead>(&self, key: &str) -> MetadataResult<T>

Strictly reads key as T, without coercing the stored runtime type.

§Errors

Returns MissingKey for an absent key, or ValueAccess preserving type mismatch and unset facts. Use Self::convert for coercing reads.

Source

pub fn get_ref<'a, T: ?Sized>(&'a self, key: &str) -> MetadataResult<&'a T>
where &'a T: TryFrom<&'a Value, Error = ValueError>,

Borrows the concrete payload under key without copying it.

§Errors

Returns MissingKey or ValueAccess for unset storage or a type mismatch. The returned reference borrows this metadata object, not the key.

Source

pub fn get_optional<T: StrictValueRead>( &self, key: &str, ) -> MetadataResult<Option<T>>

Strictly reads key, returning None only for absent or matching unset storage.

§Errors

Preserves type mismatches, including unset storage of a different type.

Source

pub fn get_or<T: StrictValueRead>( &self, key: &str, default: impl IntoValueDefault<T>, ) -> MetadataResult<T>

Strictly reads key, adapting default only for absent or matching unset storage.

§Errors

Returns the original read error for a type mismatch; never hides invalid data.

Source

pub fn convert<T: DataConversionTarget>(&self, key: &str) -> MetadataResult<T>

Converts key to T using the default conversion policy and limits.

§Errors

Returns MissingKey or ValueAccess with the original missing, invalid, unsupported, precision-loss or resource error and its source chain.

Source

pub fn convert_with<T: DataConversionTarget>( &self, key: &str, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<T>

Converts key to T with explicit policy and limits.

Each call owns one conversion budget and leaves stored data unchanged.

§Errors

Returns MissingKey or ValueAccess preserving conversion facts and limits.

Source

pub fn convert_optional_with<T: DataConversionTarget>( &self, key: &str, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<Option<T>>

Converts key, returning None for absent, unset, or policy-missing scalars.

§Errors

All other conversion errors propagate with their source and key.

Source

pub fn convert_or_with<T: DataConversionTarget>( &self, key: &str, default: impl IntoValueDefault<T>, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<T>

Converts key, adapting default only for a defaultable missing scalar.

§Errors

Invalid, unsupported, precision-loss and resource errors never default.

Source

pub fn get_raw(&self, key: &str) -> Option<&Value>

Returns a reference to the stored Value for key, or None if absent.

§Parameters
  • key - Metadata key to retrieve.
§Returns

The stored value, or None when key is absent.

Source

pub fn data_type(&self, key: &str) -> Option<DataType>

Returns the concrete data type of the value stored under key.

§Parameters
  • key - Metadata key to inspect.
§Returns

The stored value’s data type, or None when key is absent.

Source

pub fn insert<T>(&mut self, key: &str, value: T) -> Option<Value>
where T: Into<Value>,

Inserts a typed value and returns the previous value.

§Parameters
  • key - Metadata key to replace.
  • value - Typed value to store.
§Returns

The previous value when the key was already present, or None.

Source

pub fn set<T>(&mut self, key: &str, value: T) -> &mut Self
where T: Into<Value>,

Sets a typed value and returns this metadata object for chaining.

§Parameters
  • key - Metadata key to replace.
  • value - Typed value to store.
§Returns

A mutable reference to this metadata object.

Source

pub fn with<T>(self, key: &str, value: T) -> Self
where T: Into<Value>,

Returns a new metadata object with key set to value.

§Parameters
  • key - Metadata key to replace.
  • value - Typed value to store.
§Returns

This metadata object after inserting the value.

Source

pub fn insert_checked<T>( &mut self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<Option<Value>>
where T: Into<Value>,

Inserts a typed value after validating it against schema and returns the previous value.

§Parameters
  • schema - Schema used to validate the entry.
  • key - Metadata key to replace.
  • value - Typed value to validate and store.
§Returns

The previous value when the key was already present, or None.

§Errors

Returns MetadataError::UnknownField when key is rejected by the schema, MetadataError::MissingRequiredField when a required field is assigned Value::Unset, or MetadataError::TypeMismatch when the constructed value’s concrete type does not match the schema field type.

Source

pub fn set_checked<T>( &mut self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<&mut Self>
where T: Into<Value>,

Sets a typed value after schema validation and returns this metadata object for chaining.

§Parameters
  • schema - Schema used to validate the entry.
  • key - Metadata key to replace.
  • value - Typed value to validate and store.
§Returns

A mutable reference to this metadata object.

§Errors

Returns MetadataError::UnknownField when key is rejected by the schema, MetadataError::MissingRequiredField when a required field is assigned Value::Unset, or MetadataError::TypeMismatch when the constructed value’s concrete type does not match the schema field type.

Source

pub fn with_checked<T>( self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<Self>
where T: Into<Value>,

Returns a new metadata object with a typed value validated and inserted.

§Parameters
  • schema - Schema used to validate the entry.
  • key - Metadata key to replace.
  • value - Typed value to validate and store.
§Returns

This metadata object after inserting the validated value.

§Errors

Returns MetadataError::UnknownField when key is rejected by the schema, MetadataError::MissingRequiredField when a required field is assigned Value::Unset, or MetadataError::TypeMismatch when the constructed value’s concrete type does not match the schema field type.

Source

pub fn remove(&mut self, key: &str) -> Option<Value>

Removes the entry for key and returns the stored Value if it existed.

§Parameters
  • key - Metadata key to remove.
§Returns

The removed value, or None when key was absent.

Source

pub fn clear(&mut self)

Removes all entries.

Source

pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)>

Returns an iterator over (&str, &Value) pairs in key-sorted order.

§Returns

A borrowing iterator over entries in key order.

Source

pub fn keys(&self) -> impl Iterator<Item = &str>

Returns an iterator over the keys in sorted order.

§Returns

A borrowing iterator over keys in sorted order.

Source

pub fn values(&self) -> impl Iterator<Item = &Value>

Returns an iterator over the values in key-sorted order.

§Returns

A borrowing iterator over values in key order.

Source

pub fn merge(&mut self, other: Metadata)

Merges all entries from other into self, overwriting existing keys.

§Parameters
  • other - Metadata entries to consume and merge.
Source

pub fn merged(&self, other: &Metadata) -> Metadata

Returns a new Metadata that contains entries from self and other.

Entries from other take precedence on key conflicts.

§Parameters
  • other - Metadata entries to merge.
§Returns

A merged copy without modifying either input.

Source

pub fn retain<F>(&mut self, predicate: F)
where F: FnMut(&str, &Value) -> bool,

Retains only the entries for which predicate returns true.

§Parameters
  • predicate - Callback invoked for each key and value; returning false removes that entry.
Source

pub fn into_inner(self) -> BTreeMap<String, Value>

Converts this metadata object into its underlying map.

§Returns

The owned, key-sorted map of metadata values.

Source

pub fn validate_wire_contract(&self) -> MetadataResult<()>

Validates that this metadata object fits the strict V1 wire contract.

This preflight checks the same entry-count and key-byte limits enforced by Serialize::serialize, allowing callers to reject invalid metadata at the write boundary instead of discovering the error during encoding.

§Returns

Ok(()) when every entry can satisfy the metadata map limits.

§Errors

Returns MetadataError::WireLimitExceeded when the entry count or a key exceeds the strict V1 limit.

Trait Implementations§

Source§

impl Clone for Metadata

Source§

fn clone(&self) -> Metadata

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 Metadata

Source§

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

Writes the strict-policy redacted representation.

Source§

impl Default for Metadata

Source§

fn default() -> Metadata

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

impl<'de> Deserialize<'de> for Metadata

Source§

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

Deserializes only the strict v1 envelope.

Source§

impl Display for Metadata

Source§

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

Writes a bounded, strict-policy redacted representation as single-line diagnostic text.

The strict policy redacts values according to the diagnostic policy, but this output is not a confidentiality boundary for arbitrary user-defined keys or error text.

Source§

impl Extend<(String, Value)> for Metadata

Source§

fn extend<I: IntoIterator<Item = (String, Value)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<BTreeMap<String, Value>> for Metadata

Source§

fn from(map: BTreeMap<String, Value>) -> Self

Converts to this type from the input type.
Source§

impl From<Metadata> for BTreeMap<String, Value>

Source§

fn from(meta: Metadata) -> Self

Converts to this type from the input type.
Source§

impl FromIterator<(String, Value)> for Metadata

Source§

fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl IntoIterator for Metadata

Source§

type IntoIter = IntoIter<String, Value>

Which kind of iterator are we turning this into?
Source§

type Item = (String, Value)

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a Metadata

Source§

type IntoIter = Iter<'a, String, Value>

Which kind of iterator are we turning this into?
Source§

type Item = (&'a String, &'a Value)

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Metadata

Source§

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

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

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

Inequality operator !=. Read more
Source§

impl Redact for Metadata

Source§

fn write_redacted(&self, writer: &mut RedactionWriter<'_>)

Writes a policy-redacted metadata representation.

Metadata is pure domain structure, so this traversal consumes nodes, collection items, and output bytes but no diagnostic input bytes. The metadata node and its map field are admitted before the stored map is accessed. The map writer then enters exactly one map node and admits each exact remaining entry before iterator advancement. Its admitted- item path classifies entries without charging duplicate keyed root and field nodes; pass-through values still enter their legitimate nested value scopes.

§Parameters
  • session - Shared policy and cumulative diagnostic budgets.
  • formatter - Destination formatting context.
§Returns

The formatter result for the admitted safe map representation.

§Errors

Returns fmt::Error when the destination rejects safe output.

Source§

impl Serialize for Metadata

Source§

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

Serializes metadata as the strict v1 envelope.

Source§

impl StructuralPartialEq for Metadata

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> IntoValueDefault<T> for T

Source§

fn into_value_default(self) -> T

Converts this argument into the default value. Read more
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.