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
impl Metadata
Sourcepub fn decode_json_slice(input: &[u8]) -> Result<Self, MetadataWireDecodeError>
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 or
crate::MetadataWireDecodeError::Quantity when shared JSON traversal
exceeds a configured limit, crate::MetadataWireDecodeError::Syntax
for empty input or lexical JSON errors, and
crate::MetadataWireDecodeError::Decode for shared decoder failures
such as invalid UTF-8, unexpected top-level types, or deserialization
failures. Domain limits return
crate::MetadataWireDecodeError::Domain; invalid metadata
limit configuration returns
crate::MetadataWireDecodeError::InvalidLimits; unsupported
versions return
crate::MetadataWireDecodeError::UnsupportedVersion. A metadata
value conversion failure after wire materialization returns
crate::MetadataWireDecodeError::InvalidJson; such a failure may no
longer have source coordinates.
Sourcepub fn decode_json_slice_with_limits(
input: &[u8],
limits: MetadataLimits,
) -> Result<Self, MetadataWireDecodeError>
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 Budget or Quantity when shared JSON traversal exceeds a
configured limit, Domain for entry/key limits, UnsupportedVersion
for a version mismatch, and InvalidLimits for invalid metadata limits.
Empty input and lexical JSON errors return Syntax; shared decoder
failures such as invalid UTF-8, unexpected top-level types, or
deserialization failures return Decode. A metadata value conversion
failure after wire materialization returns InvalidJson and may no
longer have source coordinates.
Sourcepub fn to_json_vec(&self) -> Result<Vec<u8>, MetadataWireEncodeError>
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
metadata wire contract rejects the value, output exceeds a configured
budget, serialization fails, or the destination writer rejects bytes.
Wire-contract failures preserve their
MetadataError::WireLimitExceeded source in the Domain variant.
Sourcepub fn to_json_vec_with_limits(
&self,
limits: JsonEncodeLimits,
) -> Result<Vec<u8>, MetadataWireEncodeError>
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 metadata wire
contract rejects the value, the JSON value or output exceeds a
configured budget, or serialization fails. Wire-contract failures
preserve their MetadataError::WireLimitExceeded source in the
Domain variant. The outer metadata wire contract is checked before
value budgets.
Sourcepub fn validate_json_with_limits(
&self,
limits: JsonEncodeLimits,
) -> Result<(), MetadataWireEncodeError>
pub fn validate_json_with_limits( &self, limits: JsonEncodeLimits, ) -> Result<(), MetadataWireEncodeError>
Validates that this metadata object can be encoded within caller-provided JSON budgets.
This performs the same wire-contract, value-preflight, serialization,
and output-budget checks as Self::to_json_vec_with_limits
without retaining the encoded JSON bytes. Use it when validating
metadata before another operation encodes it.
§Parameters
limits- Output and JSON-value budgets for this operation.
§Returns
Ok(()) when the metadata can be encoded within the supplied budgets.
§Errors
Returns crate::MetadataWireEncodeError with the same structured
error categories and validation ordering as
Self::to_json_vec_with_limits. The metadata V1 wire contract
is checked before JSON value budgets; output byte limits apply to
compact encoded JSON.
Sourcepub fn to_json_writer<W>(
&self,
writer: W,
) -> Result<(), MetadataWireEncodeError>where
W: Write,
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
profile (crate::default_json_encode_limits).
§Parameters
writer- Destination receiving the complete compact JSON document.
The complete compact JSON document is buffered and validated before
the first write to writer. A budget or serialization failure leaves
the destination untouched by this operation. A destination I/O error
may leave a written prefix; this method does not provide atomic writes
or rollback. Applications own persistence and retry semantics.
Output budgets use the default encoding profile. Decode limits do not
affect them; use Self::to_json_writer_with_limits to provide
explicit output budgets.
§Returns
Ok(()) after the buffered document is written successfully.
§Errors
Returns crate::MetadataWireEncodeError when the metadata wire
contract rejects the value, encoding exceeds a budget, serialization
fails, or writer rejects the output. Wire-contract failures
preserve their MetadataError::WireLimitExceeded source in the
Domain variant. The outer metadata wire contract is checked before
value budgets.
§Type Parameters
W- Writer that receives the encoded document.
Sourcepub fn to_json_writer_with_limits<W>(
&self,
writer: W,
limits: JsonEncodeLimits,
) -> Result<(), MetadataWireEncodeError>where
W: Write,
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- Explicit output and JSON-value budgets for this operation.
The complete compact JSON document is buffered and validated before
the first write to writer. A budget or serialization failure leaves
the destination untouched by this operation. A destination I/O error
may leave a written prefix; this method does not provide atomic writes
or rollback. Applications own persistence and retry semantics. Output
budgets come only from the explicitly supplied limits; decode limits
do not affect them.
§Returns
Ok(()) after the buffered document is written successfully.
§Errors
Returns crate::MetadataWireEncodeError when the metadata wire
contract rejects the value, encoding exceeds a budget, serialization
fails, or writer rejects the output. Wire-contract failures
preserve their MetadataError::WireLimitExceeded source in the
Domain variant.
§Type Parameters
W- Writer that receives the encoded document.
Sourcepub fn contains_key(&self, key: &str) -> bool
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.
Sourcepub fn get<T: StrictValueRead>(&self, key: &str) -> MetadataResult<T>
pub fn get<T: StrictValueRead>(&self, key: &str) -> MetadataResult<T>
Strictly reads key as T without coercing the stored runtime type.
Use Self::convert when the stored value must be explicitly
converted.
§Type Parameters
T- The requested type, which must support strict value reads.
§Parameters
key- The metadata key to read.
§Returns
The owned value read as T.
§Errors
Returns MetadataError::MissingKey when key is absent, or
MetadataError::ValueAccess when the stored value is unset or its
runtime type does not match T. The value access error preserves the
underlying type and unset details.
§Examples
use qubit_metadata::Metadata;
use qubit_metadata::MetadataError;
let metadata = Metadata::new().with("port", "8080");
assert!(matches!(metadata.get::<u16>("port"),
Err(MetadataError::ValueAccess { .. })));
assert_eq!(metadata.convert::<u16>("port").unwrap(), 8080);
assert_eq!(metadata.get_ref::<str>("port").unwrap(), "8080");Sourcepub fn get_ref<'a, T: ?Sized>(&'a self, key: &str) -> MetadataResult<&'a T>
pub fn get_ref<'a, T: ?Sized>(&'a self, key: &str) -> MetadataResult<&'a T>
Borrows the concrete payload under key without copying it.
§Type Parameters
T- The borrowed payload type. Its reference conversion must accept a borrow of the stored value.
§Parameters
key- The metadata key to read.
§Returns
A reference to the payload. Its lifetime is tied to the borrow of
self, not to key.
§Errors
Returns MetadataError::MissingKey when key is absent, or
MetadataError::ValueAccess when the stored value is unset or cannot
be borrowed as T.
Sourcepub fn get_optional<T: StrictValueRead>(
&self,
key: &str,
) -> MetadataResult<Option<T>>
pub fn get_optional<T: StrictValueRead>( &self, key: &str, ) -> MetadataResult<Option<T>>
Strictly reads key, returning None only for an absent key or unset
storage declared as T.
§Type Parameters
T- The requested type, which must support strict value reads.
§Parameters
key- The metadata key to read.
§Returns
Some(value) when a concrete value is read as T; None when the key
is absent or stores an unset value declared as T.
§Errors
Returns MetadataError::ValueAccess when the stored concrete value
has a different runtime type, or when unset storage is declared as a
different type than T.
§Examples
use qubit_datatype::DataType;
use qubit_metadata::Metadata;
use qubit_value::Value;
let metadata = Metadata::new().with("count", Value::Unset(DataType::Int64));
assert_eq!(metadata.get_optional::<i64>("absent").unwrap(), None);
assert_eq!(metadata.get_optional::<i64>("count").unwrap(), None);
assert!(metadata.get_optional::<i32>("count").is_err());Sourcepub fn get_or<T: StrictValueRead>(
&self,
key: &str,
default: impl IntoValueDefault<T>,
) -> MetadataResult<T>
pub fn get_or<T: StrictValueRead>( &self, key: &str, default: impl IntoValueDefault<T>, ) -> MetadataResult<T>
Strictly reads key, adapting default only for an absent key or
unset storage declared as T.
The default adapter is invoked only when this read permits fallback. Rust still evaluates the argument expression before calling this method.
§Type Parameters
T- The requested type, which must support strict value reads.
§Parameters
key- The metadata key to read.default- A value or adapter that can provide a defaultT.
§Returns
The stored value read as T, or the adapted default when the key is
absent or contains matching unset storage.
§Errors
Returns MetadataError::ValueAccess for a type mismatch, including
unset storage declared as a different type. Such errors are propagated
without using the default.
§Examples
use qubit_datatype::DataType;
use qubit_metadata::Metadata;
use qubit_value::Value;
let metadata = Metadata::new()
.with("count", Value::Unset(DataType::Int64))
.with("text", "invalid");
assert_eq!(metadata.get_or::<i64>("count", 7_i64).unwrap(), 7);
assert_eq!(metadata.get_or::<i64>("absent", 7_i64).unwrap(), 7);
assert!(metadata.get_or::<i64>("text", 7_i64).is_err());Sourcepub fn convert<T: DataConversionTarget>(&self, key: &str) -> MetadataResult<T>
pub fn convert<T: DataConversionTarget>(&self, key: &str) -> MetadataResult<T>
Converts the stored value under key to T using the default
conversion policy and limits. For strict reads, see Self::get.
§Type Parameters
T- The conversion target type.
§Parameters
key- The metadata key to convert.
§Returns
The stored value converted to T.
§Errors
Returns MetadataError::MissingKey when key is absent, or
MetadataError::ValueAccess when conversion fails. The latter retains
the underlying missing, invalid, unsupported, precision-loss, or
resource-limit error and its source chain.
Sourcepub fn convert_with<T: DataConversionTarget>(
&self,
key: &str,
policy: &ConversionPolicy,
limits: &ConversionLimits,
) -> MetadataResult<T>
pub fn convert_with<T: DataConversionTarget>( &self, key: &str, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<T>
Converts the stored value under key to T with an explicit
ConversionPolicy and ConversionLimits. Each call has an
independent conversion budget and leaves the stored value unchanged.
For default policy and limits, see Self::convert.
§Type Parameters
T- The conversion target type.
§Parameters
key- The metadata key to convert.policy- The policy controlling which conversions are allowed.limits- The per-call resource limits and budget.
§Returns
The stored value converted to T.
§Errors
Returns MetadataError::MissingKey when key is absent, or
MetadataError::ValueAccess when conversion fails. The latter
preserves the underlying conversion facts and any exceeded limits.
Sourcepub fn convert_optional_with<T: DataConversionTarget>(
&self,
key: &str,
policy: &ConversionPolicy,
limits: &ConversionLimits,
) -> MetadataResult<Option<T>>
pub fn convert_optional_with<T: DataConversionTarget>( &self, key: &str, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<Option<T>>
Converts the value under key, returning None for an absent key,
unset storage, or a scalar classified as missing by policy.
§Type Parameters
T- The conversion target type.
§Parameters
key- The metadata key to convert.policy- The policy controlling conversion and missing-value handling.limits- The per-call resource limits and budget.
§Returns
Some(value) when conversion succeeds; None for an absent key, unset
storage, or a policy-missing scalar.
§Errors
Propagates all other errors as MetadataError::ValueAccess, retaining
the key and the underlying conversion error. See Self::convert_with
for explicit policy and budget behavior.
Sourcepub fn convert_or_with<T: DataConversionTarget>(
&self,
key: &str,
default: impl IntoValueDefault<T>,
policy: &ConversionPolicy,
limits: &ConversionLimits,
) -> MetadataResult<T>
pub fn convert_or_with<T: DataConversionTarget>( &self, key: &str, default: impl IntoValueDefault<T>, policy: &ConversionPolicy, limits: &ConversionLimits, ) -> MetadataResult<T>
Converts the value under key, adapting default only when the result
is a defaultable missing value. See Self::convert_optional_with for
the conditions that produce None.
The default adapter is invoked only when this conversion permits fallback. Rust still evaluates the argument expression before calling this method.
§Type Parameters
T- The conversion target type.
§Parameters
key- The metadata key to convert.default- A value or adapter that can provide a defaultT.policy- The policy controlling conversion and missing-value handling.limits- The per-call resource limits and budget.
§Returns
The converted value, or the adapted default when the conversion result is a defaultable missing value.
§Errors
Errors other than defaultable missing values propagate as
MetadataError::ValueAccess. Invalid values, unsupported conversions,
precision loss, and resource-limit errors never use the default.
Sourcepub fn insert_checked<T>(
&mut self,
schema: &MetadataSchema,
key: &str,
value: T,
) -> MetadataResult<Option<Value>>
pub fn insert_checked<T>( &mut self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<Option<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.
§Type Parameters
T- Input type convertible into a storedValue.
Sourcepub fn set_checked<T>(
&mut self,
schema: &MetadataSchema,
key: &str,
value: T,
) -> MetadataResult<&mut Self>
pub fn set_checked<T>( &mut self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<&mut Self>
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.
§Type Parameters
T- Input type convertible into a storedValue.
Sourcepub fn with_checked<T>(
self,
schema: &MetadataSchema,
key: &str,
value: T,
) -> MetadataResult<Self>
pub fn with_checked<T>( self, schema: &MetadataSchema, key: &str, value: T, ) -> MetadataResult<Self>
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.
§Type Parameters
T- Input type convertible into a storedValue.
Sourcepub fn iter(&self) -> impl Iterator<Item = (&str, &Value)>
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.
Sourcepub fn keys(&self) -> impl Iterator<Item = &str>
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.
Sourcepub fn values(&self) -> impl Iterator<Item = &Value>
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.
Sourcepub fn merge(&mut self, other: Metadata)
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.
Sourcepub fn into_inner(self) -> BTreeMap<String, Value>
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.
Sourcepub fn validate_wire_contract(&self) -> MetadataResult<()>
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<'de> Deserialize<'de> for Metadata
impl<'de> Deserialize<'de> for Metadata
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Deserializes only the strict v1 envelope.
§Type Parameters
D- Deserializer providing the wire envelope.
§Parameters
deserializer- Source of the serialized metadata envelope.
§Returns
The decoded metadata object.
§Errors
Returns the deserializer’s error if the envelope is malformed, unsupported, or contains invalid metadata values.
Source§impl Display for Metadata
impl Display for Metadata
Source§fn fmt(&self, formatter: &mut Formatter<'_>) -> Result
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.
§Parameters
formatter- Formatter receiving the redacted representation.
Source§impl Extend<(String, Value)> for Metadata
impl Extend<(String, Value)> for Metadata
Source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl From<BTreeMap<String, Value>> for Metadata
impl From<BTreeMap<String, Value>> for Metadata
Source§impl FromIterator<(String, Value)> for Metadata
impl FromIterator<(String, Value)> for Metadata
Source§fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self
Collects entries into metadata using BTreeMap duplicate-key
replacement. The resulting keys are sorted; collection does not
validate schema or wire limits.
§Type Parameters
I- Iterator type yielding owned metadata key-value pairs.
§Parameters
iter- Source of metadata key-value pairs.
§Returns
Metadata containing the collected entries.
Source§impl IntoIterator for Metadata
impl IntoIterator for Metadata
Source§impl<'a> IntoIterator for &'a Metadata
impl<'a> IntoIterator for &'a Metadata
Source§type Item = (&'a String, &'a Value)
type Item = (&'a String, &'a Value)
References to an entry’s key and value; neither is cloned.
Source§fn into_iter(self) -> Self::IntoIter
fn into_iter(self) -> Self::IntoIter
Borrows sorted entries for the lifetime of the metadata borrow without
cloning. This yields (&String, &Value), unlike Metadata::iter
which yields (&str, &Value).
§Parameters
self- Borrowed metadata whose entries are exposed by the iterator.
§Returns
A borrowed iterator over sorted metadata entries.
Source§impl Redact for Metadata
impl Redact for Metadata
Source§fn write_redacted(&self, writer: &mut RedactionWriter<'_>)
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
writer- Redaction writer receiving the metadata representation.
§Returns
Returns () after writing through the redaction writer.
Source§impl Serialize for Metadata
impl Serialize for Metadata
Source§fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where
S: Serializer,
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where
S: Serializer,
Serializes metadata as the strict v1 envelope.
§Type Parameters
S- Serializer used to produce the wire envelope.
§Parameters
serializer- Serializer receiving the metadata envelope.
§Returns
The serializer’s result containing the encoded envelope.
§Errors
Returns the serializer’s error if wire validation or serialization fails.