#[non_exhaustive]pub enum Value {
Integer(Integer),
Bytes(Vec<u8>),
Float(f64),
Text(String),
Bool(bool),
Null,
Tag(u64, Box<Value>),
Array(Vec<Value>),
Map(Vec<(Value, Value)>),
}Expand description
A representation of any CBOR item that can be inspected and manipulated dynamically.
Maps are represented as Vec<(Value, Value)> rather than as an ordered
or hashed map type. This preserves the order of the pairs on the wire and
makes no assumptions about key uniqueness; convert with TryFrom —
HashMap and BTreeMap are supported directly — if you need a map type.
Value intentionally models the serde-visible CBOR data model, not every
byte-level spelling. For example, indefinite-length strings are decoded
into the same variants as definite-length strings, while unknown tags
remain as Value::Tag and oversized bignums stay as tagged byte
strings.
Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
Integer(Integer)
An integer (major type 0 or 1).
Bytes(Vec<u8>)
A byte string (major type 2).
Float(f64)
A floating-point value (major type 7).
Text(String)
A text string (major type 3).
Bool(bool)
A boolean (major type 7).
Null
Null (major type 7).
Tag(u64, Box<Value>)
A tagged value (major type 6).
Array(Vec<Value>)
An array (major type 4).
Map(Vec<(Value, Value)>)
A map (major type 5).
Implementations§
Source§impl Value
impl Value
Sourcepub fn canonicalize(&mut self) -> Result<(), Error>
pub fn canonicalize(&mut self) -> Result<(), Error>
Rewrites this value so that encoding it satisfies the core deterministic encoding requirements (RFC 8949 §4.2.1).
This is canonicalize_with using
KeyOrder::Bytewise.
use cbor2::{cbor, Value};
let mut value = cbor!({ "z": 1, "aa": 2 }).unwrap();
value.canonicalize().unwrap();
// "z" (0x617a) sorts before "aa" (0x626161).
let keys: Vec<_> = value.as_map().unwrap().iter().map(|(k, _)| k).collect();
assert_eq!(keys, [&Value::from("z"), &Value::from("aa")]);Sourcepub fn canonicalize_with(&mut self, order: KeyOrder) -> Result<(), Error>
pub fn canonicalize_with(&mut self, order: KeyOrder) -> Result<(), Error>
Rewrites this value so that encoding it is deterministic, sorting
map keys in the given KeyOrder.
The encoder already emits preferred (smallest lossless) serializations and never produces indefinite-length items, so the work left to this method is normalizing the data model:
- The entries of every map are sorted in
order. Duplicate keys are rejected with an error, since CBOR maps holding them are invalid (RFC 8949 §5.6) and have no unique encoding. - Bignums (tags 2 and 3) are reduced to their preferred form: leading zeros are stripped and values that fit in major type 0 or 1 become plain integers (RFC 8949 §3.4.3).
- Every NaN is replaced by the canonical quiet NaN, so a single floating-point value cannot have multiple encodings (RFC 8949 §4.2.2).
use cbor2::{cbor, KeyOrder, Value};
let mut value = cbor!({ "aa": 2, 100: 1, -1: 0 }).unwrap();
value.canonicalize_with(KeyOrder::LengthFirst).unwrap();
// -1 (0x20, one byte) sorts before 100 (0x1864, two bytes).
let keys: Vec<_> = value.as_map().unwrap().iter().map(|(k, _)| k).collect();
assert_eq!(keys, [&Value::from(-1), &Value::from(100), &Value::from("aa")]);Source§impl Value
impl Value
Sourcepub fn deserialized<'de, T: Deserialize<'de>>(&self) -> Result<T, Error>
pub fn deserialized<'de, T: Deserialize<'de>>(&self) -> Result<T, Error>
Deserializes this Value into any T: Deserialize.
Tags are preserved for cbor2::tag wrappers and skipped in typed
positions where this crate’s streaming deserializer also skips them.
Integer map keys and struct tags use the same #[derive(Cbor)]
marker protocol as byte-level decoding.
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
struct Event {
level: String,
count: u64,
}
let value = cbor2::cbor!({ "level": "info", "count": 2 }).unwrap();
let event: Event = value.deserialized().unwrap();
assert_eq!(event, Event { level: "info".into(), count: 2 });Source§impl Value
impl Value
Sourcepub fn serialized<T: ?Sized + Serialize>(value: &T) -> Result<Self, Error>
pub fn serialized<T: ?Sized + Serialize>(value: &T) -> Result<Self, Error>
Serializes any T: Serialize into a Value.
This uses the same CBOR-oriented serde data model as to_vec:
structs become maps, enum unit variants become text strings, other
enum variants become single-entry maps, u128/i128 may become
bignum tags, and cbor2::tag wrappers become Value::Tag.
use serde::Serialize;
#[derive(Serialize)]
struct Event<'a> {
level: &'a str,
count: u64,
}
let value = cbor2::Value::serialized(&Event { level: "info", count: 2 }).unwrap();
assert_eq!(value.to_string(), r#"{"level": "info", "count": 2}"#);Source§impl Value
impl Value
Sourcepub fn as_bytes(&self) -> Option<&Vec<u8>>
pub fn as_bytes(&self) -> Option<&Vec<u8>>
If the value is a byte string, returns a reference to it. Returns None otherwise.
Sourcepub fn into_bytes(self) -> Result<Vec<u8>, Self>
pub fn into_bytes(self) -> Result<Vec<u8>, Self>
If the value is a byte string, returns it as Ok. Returns Err(self) otherwise.
Sourcepub fn as_array(&self) -> Option<&Vec<Value>>
pub fn as_array(&self) -> Option<&Vec<Value>>
If the value is an array, returns a reference to it. Returns None otherwise.
Sourcepub fn into_array(self) -> Result<Vec<Value>, Self>
pub fn into_array(self) -> Result<Vec<Value>, Self>
If the value is an array, returns it as Ok. Returns Err(self) otherwise.
Sourcepub fn as_map(&self) -> Option<&Vec<(Value, Value)>>
pub fn as_map(&self) -> Option<&Vec<(Value, Value)>>
If the value is a map, returns a reference to it. Returns None otherwise.
Sourcepub fn into_map(self) -> Result<Vec<(Value, Value)>, Self>
pub fn into_map(self) -> Result<Vec<(Value, Value)>, Self>
If the value is a map, returns it as Ok. Returns Err(self) otherwise.
Sourcepub fn is_integer(&self) -> bool
pub fn is_integer(&self) -> bool
Returns true if the value is an integer.
Sourcepub fn as_integer(&self) -> Option<Integer>
pub fn as_integer(&self) -> Option<Integer>
If the value is an integer, returns it. Returns None otherwise.
Sourcepub fn into_integer(self) -> Result<Integer, Self>
pub fn into_integer(self) -> Result<Integer, Self>
If the value is an integer, returns it as Ok. Returns Err(self)
otherwise.
Sourcepub fn as_float(&self) -> Option<f64>
pub fn as_float(&self) -> Option<f64>
If the value is a float, returns it. Returns None otherwise.
Sourcepub fn into_float(self) -> Result<f64, Self>
pub fn into_float(self) -> Result<f64, Self>
If the value is a float, returns it as Ok. Returns Err(self)
otherwise.
Sourcepub fn as_text(&self) -> Option<&str>
pub fn as_text(&self) -> Option<&str>
If the value is a text string, returns a reference to it. Returns
None otherwise.
Sourcepub fn into_text(self) -> Result<String, Self>
pub fn into_text(self) -> Result<String, Self>
If the value is a text string, returns it as Ok. Returns
Err(self) otherwise.
Sourcepub fn as_bool(&self) -> Option<bool>
pub fn as_bool(&self) -> Option<bool>
If the value is a boolean, returns it. Returns None otherwise.
Sourcepub fn into_bool(self) -> Result<bool, Self>
pub fn into_bool(self) -> Result<bool, Self>
If the value is a boolean, returns it as Ok. Returns Err(self)
otherwise.
Sourcepub fn as_tag(&self) -> Option<(u64, &Value)>
pub fn as_tag(&self) -> Option<(u64, &Value)>
If the value is a tag, returns the tag number and a reference to the
inner value. Returns None otherwise.
Sourcepub fn into_tag(self) -> Result<(u64, Box<Value>), Self>
pub fn into_tag(self) -> Result<(u64, Box<Value>), Self>
If the value is a tag, returns the pair of the tag number and the
inner value as Ok. Returns Err(self) otherwise.
Sourcepub fn as_bytes_mut(&mut self) -> Option<&mut Vec<u8>>
pub fn as_bytes_mut(&mut self) -> Option<&mut Vec<u8>>
If the value is a byte string, returns a mutable reference to it.
Returns None otherwise.
Sourcepub fn as_text_mut(&mut self) -> Option<&mut String>
pub fn as_text_mut(&mut self) -> Option<&mut String>
If the value is a text string, returns a mutable reference to it.
Returns None otherwise.
Sourcepub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>>
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>>
If the value is an array, returns a mutable reference to it. Returns
None otherwise.
Sourcepub fn as_map_mut(&mut self) -> Option<&mut Vec<(Value, Value)>>
pub fn as_map_mut(&mut self) -> Option<&mut Vec<(Value, Value)>>
If the value is a map, returns a mutable reference to it. Returns
None otherwise.
Sourcepub fn as_tag_mut(&mut self) -> Option<(&mut u64, &mut Value)>
pub fn as_tag_mut(&mut self) -> Option<(&mut u64, &mut Value)>
If the value is a tag, returns mutable references to the tag number
and the inner value. Returns None otherwise.
Trait Implementations§
Source§impl Debug for Value
Formats the value as indented CBOR diagnostic notation (RFC 8949 §8).
impl Debug for Value
Formats the value as indented CBOR diagnostic notation (RFC 8949 §8).
This is the multi-line counterpart of the Display
implementation: arrays and maps spread one element per line, nested
levels are indented by two spaces, and scalars render exactly as in
the compact form.
use cbor2::cbor;
let value = cbor!({ "a": [1, 2] }).unwrap();
assert_eq!(
format!("{value:?}"),
"{\n \"a\": [\n 1,\n 2\n ]\n}"
);Source§impl<'de> Deserialize<'de> for Value
impl<'de> Deserialize<'de> for Value
Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Source§impl Display for Value
Formats the value in CBOR diagnostic notation (RFC 8949 §8).
impl Display for Value
Formats the value in CBOR diagnostic notation (RFC 8949 §8).
Byte strings appear as h'..', text is escaped to pure ASCII in the
style of RFC 8949 Appendix A, floats always carry a decimal point or
exponent and bignum tags (2 and 3) are written as plain integers.
use cbor2::{cbor, Value};
let value = cbor!({ "k": [1, -2.5, null] }).unwrap();
assert_eq!(value.to_string(), r#"{"k": [1, -2.5, null]}"#);Source§impl<'a> From<&'a Value> for Unexpected<'a>
impl<'a> From<&'a Value> for Unexpected<'a>
Source§impl<K: Into<Value>, V: Into<Value>> From<BTreeMap<K, V>> for Value
Converts to Value::Map in the map’s order: ascending by key.
impl<K: Into<Value>, V: Into<Value>> From<BTreeMap<K, V>> for Value
Converts to Value::Map in the map’s order: ascending by key.
Source§impl<K: Into<Value>, V: Into<Value>> From<HashMap<K, V>> for Value
Available on crate feature std only.Converts to Value::Map, keeping the map’s iteration order — which
a HashMap randomizes. Encode with the to_canonical_* functions (or
canonicalize first) when a deterministic
order matters.
impl<K: Into<Value>, V: Into<Value>> From<HashMap<K, V>> for Value
std only.Converts to Value::Map, keeping the map’s iteration order — which
a HashMap randomizes. Encode with the to_canonical_* functions (or
canonicalize first) when a deterministic
order matters.
use std::collections::HashMap;
use cbor2::Value;
let map: HashMap<&str, u64> = [("a", 1)].into();
assert_eq!(Value::from(map), cbor2::cbor!({ "a": 1 }).unwrap());Source§impl<T: Into<Value>> From<Option<T>> for Value
Converts Some to the inner value and None to Value::Null.
impl<T: Into<Value>> From<Option<T>> for Value
Converts Some to the inner value and None to Value::Null.
Source§impl<T: Into<Value>> FromIterator<T> for Value
Collects an iterator of values into Value::Array.
impl<T: Into<Value>> FromIterator<T> for Value
Collects an iterator of values into Value::Array.
use cbor2::Value;
let value: Value = (1..=3).collect();
assert_eq!(value, cbor2::cbor!([1, 2, 3]).unwrap());Source§fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
Source§impl PartialOrd for Value
impl PartialOrd for Value
impl StructuralPartialEq for Value
Source§impl TryFrom<&RawValue> for Value
Decodes the raw item into a dynamic Value, like
deserialized.
impl TryFrom<&RawValue> for Value
Decodes the raw item into a dynamic Value, like
deserialized.
This decodes: byte-level spellings the dynamic form cannot represent (indefinite lengths, non-preferred widths) are not preserved.
Source§impl TryFrom<RawValue> for Value
Decodes the raw item into a dynamic Value, like
deserialized.
impl TryFrom<RawValue> for Value
Decodes the raw item into a dynamic Value, like
deserialized.
This decodes: byte-level spellings the dynamic form cannot represent (indefinite lengths, non-preferred widths) are not preserved.
Source§impl TryFrom<Value> for Integer
Converts from Value::Integer; any other variant is an "invalid type" error.
impl TryFrom<Value> for Integer
Converts from Value::Integer; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for Vec<u8>
Converts from Value::Bytes; any other variant is an "invalid type" error.
impl TryFrom<Value> for Vec<u8>
Converts from Value::Bytes; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for f64
Converts from Value::Float; any other variant is an "invalid type" error.
impl TryFrom<Value> for f64
Converts from Value::Float; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for String
Converts from Value::Text; any other variant is an "invalid type" error.
impl TryFrom<Value> for String
Converts from Value::Text; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for bool
Converts from Value::Bool; any other variant is an "invalid type" error.
impl TryFrom<Value> for bool
Converts from Value::Bool; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for Vec<Value>
Converts from Value::Array; any other variant is an "invalid type" error.
impl TryFrom<Value> for Vec<Value>
Converts from Value::Array; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for Vec<(Value, Value)>
Converts from Value::Map; any other variant is an "invalid type" error.
impl TryFrom<Value> for Vec<(Value, Value)>
Converts from Value::Map; any other variant is an "invalid type" error.
The Value::into_* accessors are the
non-consuming-on-failure alternative: they hand the original
value back instead of an error message.
Source§impl TryFrom<Value> for usize
Available on 32-bit or 64-bit only.Converts from a Value::Integer in usize range.
impl TryFrom<Value> for usize
Converts from a Value::Integer in usize range.
Source§impl TryFrom<Value> for isize
Available on 32-bit or 64-bit only.Converts from a Value::Integer in isize range.
impl TryFrom<Value> for isize
Converts from a Value::Integer in isize range.
Source§impl TryFrom<Value> for u128
Converts from any integer representation that fits, including the
bignum form (tag 2 or 3) that From<u128>
produces for values beyond 64 bits.
impl TryFrom<Value> for u128
Converts from any integer representation that fits, including the
bignum form (tag 2 or 3) that From<u128>
produces for values beyond 64 bits.
Source§impl TryFrom<Value> for i128
Converts from any integer representation that fits, including the
bignum form (tag 2 or 3) that From<i128>
produces for values beyond 64 bits.
impl TryFrom<Value> for i128
Converts from any integer representation that fits, including the
bignum form (tag 2 or 3) that From<i128>
produces for values beyond 64 bits.
Source§impl<K, V> TryFrom<Value> for HashMap<K, V>
Available on crate feature std only.Converts from Value::Map, converting every key and value in turn;
later duplicate keys overwrite earlier ones. For deep, typed
extraction with detailed errors prefer
Value::deserialized.
impl<K, V> TryFrom<Value> for HashMap<K, V>
std only.Converts from Value::Map, converting every key and value in turn;
later duplicate keys overwrite earlier ones. For deep, typed
extraction with detailed errors prefer
Value::deserialized.
use std::collections::HashMap;
use cbor2::Value;
let value = cbor2::cbor!({ "a": 1, "b": 2 }).unwrap();
let map: HashMap<String, u64> = value.try_into().unwrap();
assert_eq!(map["a"], 1);