pub enum Value {
SimpleValue(SimpleValue),
Unsigned(u64),
Negative(u64),
Float(Float),
ByteString(Vec<u8>),
TextString(String),
Array(Vec<Value>),
Map(BTreeMap<Value, Value>),
Tag(u64, Box<Value>),
}Expand description
A single CBOR data item.
Value covers all CBOR major types: integers, floats, byte and text
strings, arrays, maps, tagged values, and simple values (null, booleans).
It encodes deterministically and decodes only canonical input.
§Creating values
Rust primitives convert via From:
use cbor_core::Value;
let n = Value::from(42);
let s = Value::from("hello");
let b = Value::from(true);The array! and map! macros build arrays and maps from literals:
use cbor_core::{Value, array, map};
let a = array![1, 2, 3];
let m = map! { "x" => 10, "y" => 20 };Arrays and maps can also be built from standard Rust collections.
Slices, Vecs, fixed-size arrays, BTreeMaps, HashMaps, and
slices of key-value pairs all convert automatically:
use cbor_core::Value;
use std::collections::HashMap;
// Array from a slice
let a = Value::array([1, 2, 3].as_slice());
// Map from a HashMap
let mut hm = HashMap::new();
hm.insert(1, 2);
let m = Value::map(&hm);
// Map from key-value pairs
let m = Value::map([("x", 10), ("y", 20)]);Use () to create empty arrays or maps without spelling out a type:
use cbor_core::Value;
let empty_array = Value::array(());
let empty_map = Value::map(());
assert_eq!(empty_array.len(), Some(0));
assert_eq!(empty_map.len(), Some(0));Named constructors are available for cases where From is ambiguous
or unavailable:
| Constructor | Builds |
|---|---|
Value::new(v) | Any variant via TryFrom, panicking on fallible failures |
Value::null() | Null simple value |
Value::simple_value(v) | Arbitrary simple value |
Value::float(v) | Float in shortest CBOR form |
Value::byte_string(v) | Byte string from impl Into<Vec<u8>> |
Value::text_string(v) | Text string from impl Into<String> |
Value::array(v) | Array from slice, Vec, or fixed-size array |
Value::map(v) | Map from BTreeMap, HashMap, slice of pairs, etc. |
Value::date_time(v) | Date/time string (tag 0) |
Value::epoch_time(v) | Epoch time (tag 1) |
Value::tag(n, v) | Tagged value |
§const constructors
Scalar variants can also be built in const context. These are the
const counterparts of the From<T> implementations. Use them for
const items; in non-const code the shorter Value::from(v) or
Value::new(v) spellings are preferred.
| Constructor | Builds |
|---|---|
Value::null() | Null simple value |
Value::simple_value(v) | Simple value from u8 |
Value::from_bool(v) | Boolean |
Value::from_u64(v) | Unsigned integer |
Value::from_i64(v) | Signed integer |
Value::from_f32(v) | Float from f32 |
Value::from_f64(v) | Float from f64 |
Value::from_payload(v) | Non-finite float from payload |
Narrower integer widths (u8..u32, i8..i32) are not provided
separately: as u64 / as i64 is lossless and yields the same
Value. u128 and i128 have no const constructor because
out-of-range values require the big-integer path, which allocates a
tagged byte string. Byte strings, text strings, arrays, maps, and
tags are heap-backed and likewise cannot be built in const context.
§Encoding and decoding
use cbor_core::Value;
let original = Value::from(-1000);
let bytes = original.encode();
let decoded = Value::decode(&bytes).unwrap();
assert_eq!(original, decoded);CBOR can be produced and consumed as binary bytes, as a hex string, or as diagnostic notation text:
| Direction | Binary | Hex string | Diagnostic text |
|---|---|---|---|
| Produce (owned) | encode → Vec<u8> | encode_hex → String | format!("{v:?}") (compact) or format!("{v:#?}") (pretty) via Debug; format!("{v}") via Display |
| Produce (streaming) | write_to(impl Write) | write_hex_to(impl Write) | — |
| Consume (owned) | decode(impl AsRef<[u8]>) | decode_hex(impl AsRef<[u8]>) | str::parse via FromStr |
| Consume (streaming) | read_from(impl Read) | read_hex_from(impl Read) | — |
Debug output follows CBOR::Core diagnostic notation (Section 2.3.6);
Display forwards to Debug so both produce the same text.
format!("{v:?}").parse::<Value>() always round-trips.
The four decoding methods above forward to a default
DecodeOptions. Use that type directly to
switch between binary and hex at runtime, or to adjust the recursion
limit, the declared-length cap, or the OOM-mitigation budget — for
example, to tighten limits on input from an untrusted source:
use cbor_core::DecodeOptions;
let strict = DecodeOptions::new()
.recursion_limit(16)
.length_limit(4096)
.oom_mitigation(64 * 1024);
let v = strict.decode([0x18, 42]).unwrap();
assert_eq!(v.to_u32().unwrap(), 42);§Accessors
Accessor methods extract or borrow the inner data of each variant.
All return Result<T>, yielding Err(Error::IncompatibleType) on a
type mismatch. The naming follows Rust conventions:
| Prefix | Meaning | Returns |
|---|---|---|
as_* | Borrow inner data | &T or &mut T (with _mut) |
to_* | Convert or narrow | Owned Copy type (u8, f32, …) |
into_* | Consume self, extract | Owned T |
| no prefix | Trivial property | Copy scalar |
§Simple values
In CBOR, booleans and null are not distinct types but specific simple
values: false is 20, true is 21, null is 22. This means a
boolean value is always also a simple value. to_bool
provides typed access to true/false, while
to_simple_value works on any simple value
including booleans and null.
| Method | Returns | Notes |
|---|---|---|
to_simple_value | Result<u8> | Raw simple value number |
to_bool | Result<bool> | Only for true/false |
use cbor_core::Value;
let v = Value::from(true);
assert_eq!(v.to_bool().unwrap(), true);
assert_eq!(v.to_simple_value().unwrap(), 21); // CBOR true = simple(21)
// null is also a simple value
let n = Value::null();
assert!(n.to_bool().is_err()); // not a boolean
assert_eq!(n.to_simple_value().unwrap(), 22); // but is simple(22)§Integers
CBOR has effectively four integer types (unsigned or negative, and normal or big integer) with different internal representations. This is handled transparently by the API.
The to_* accessors perform checked
narrowing into any Rust integer type, returning Err(Overflow) if
the value does not fit, or Err(NegativeUnsigned) when extracting a
negative value into an unsigned type.
use cbor_core::Value;
let v = Value::from(1000);
assert_eq!(v.to_u32().unwrap(), 1000);
assert_eq!(v.to_i64().unwrap(), 1000);
assert!(v.to_u8().is_err()); // overflow
let neg = Value::from(-5);
assert_eq!(neg.to_i8().unwrap(), -5);
assert!(neg.to_u32().is_err()); // negative unsigned§Floats
Floats are stored internally in their shortest CBOR encoding (f16,
f32, or f64). to_f64 always succeeds since every
float can widen to f64. to_f32 fails with
Err(Precision) if the value is stored as f64.
A float internally stored as f16 can always be converted to either
an f32 or f64 for obvious reasons.
use cbor_core::Value;
let v = Value::from(2.5);
assert_eq!(v.to_f64().unwrap(), 2.5);
assert_eq!(v.to_f32().unwrap(), 2.5);§Byte strings
Byte strings are stored as Vec<u8>. Use as_bytes
for a borrowed slice, or into_bytes to take
ownership without copying.
| Method | Returns |
|---|---|
as_bytes | Result<&[u8]> |
as_bytes_mut | Result<&mut Vec<u8>> |
into_bytes | Result<Vec<u8>> |
use cbor_core::Value;
let mut v = Value::from(vec![1, 2, 3]);
v.as_bytes_mut().unwrap().push(4);
assert_eq!(v.as_bytes().unwrap(), &[1, 2, 3, 4]);§Text strings
Text strings are stored as String (guaranteed valid UTF-8 by the
decoder). Use as_str for a borrowed &str, or
into_string to take ownership.
| Method | Returns |
|---|---|
as_str | Result<&str> |
as_string_mut | Result<&mut String> |
into_string | Result<String> |
use cbor_core::Value;
let v = Value::from("hello");
assert_eq!(v.as_str().unwrap(), "hello");
// Modify in place
let mut v = Value::from("hello");
v.as_string_mut().unwrap().push_str(" world");
assert_eq!(v.as_str().unwrap(), "hello world");§Arrays
Arrays are stored as Vec<Value>. Use as_array
to borrow the elements as a slice, or as_array_mut
to modify them in place. For element access by index, see
get, get_mut, remove,
and the Index/IndexMut
implementations — see the Indexing section below.
| Method | Returns |
|---|---|
as_array | Result<&[Value]> |
as_array_mut | Result<&mut Vec<Value>> |
into_array | Result<Vec<Value>> |
use cbor_core::{Value, array};
let v = array![10, 20, 30];
let items = v.as_array().unwrap();
assert_eq!(items[1].to_u32().unwrap(), 20);
// Modify in place
let mut v = array![1, 2];
v.append(3);
assert_eq!(v.len(), Some(3));§Maps
Maps are stored as BTreeMap<Value, Value>, giving canonical key
order. Use as_map for direct access to the
underlying BTreeMap, or get, get_mut,
remove, and the Index/
IndexMut implementations for key lookups — see the
Indexing section below.
| Method | Returns |
|---|---|
as_map | Result<&BTreeMap<Value, Value>> |
as_map_mut | Result<&mut BTreeMap<Value, Value>> |
into_map | Result<BTreeMap<Value, Value>> |
use cbor_core::{Value, map};
let v = map! { "name" => "Alice", "age" => 30 };
assert_eq!(v["name"].as_str().unwrap(), "Alice");
// Modify in place
let mut v = map! { "count" => 1 };
v.insert("count", 2);
assert_eq!(v["count"].to_u32().unwrap(), 2);§Indexing
Arrays and maps share a uniform interface for element access, summarized below. Entries with a shaded “Panics” cell never panic under any inputs.
| Method | Returns | Non-collection receiver | Invalid / missing key |
|---|---|---|---|
len | Option<usize> | None | — |
contains | bool | false | false |
get | Option<&Value> | None | None |
get_mut | Option<&mut Value> | None | None |
insert | Option<Value> (arrays: always None) | panics | array: panics; map: inserts |
remove | Option<Value> | panics | array: panics; map: None |
append | () | panics (maps included) | — |
v[key], v[key] = … | &Value, &mut Value | panics | panics |
The methods split into two flavors:
- Soft —
len,contains,get, andget_mut: never panic. They returnOption/booland treat a wrong-type receiver the same as a missing key. - Hard —
insert,remove,append, and the[]operators: panic when the receiver is not an array or map, when an array index is not a validusize(negative, non-integer key), or when the index is out of range. This mirrorsVecandBTreeMap.
All keyed methods accept any type implementing
Into<ValueKey>: integers (for array indices
and integer map keys), &str, &[u8], &Value, and the primitive
CBOR types.
insert takes Into<Value> for the key, since a
map insert has to own the key anyway.
All methods see through tags transparently — operating on a
Tag dispatches to the innermost tagged content.
§Arrays
The key is always a usize index. Valid ranges differ by method:
get,get_mut,contains,remove, andv[i]requireito be in0..len.get/get_mut/containsreturnNone/falsefor invalid or out-of-range indices;removeandv[i]panic.insertaccepts0..=len(appending atlenis allowed) and shifts subsequent elements right. It always returnsNone, and panics if the index is invalid or out of range.appendpushes to the end in O(1) and never cares about an index.insertandremoveshift elements, which is O(n) and can be slow for large arrays. Preferappendwhen order at the end is all you need.- To replace an element in place (O(1), no shift), assign through
get_mutorv[i] = ….
§Maps
The key is any CBOR-convertible value:
insertreturns the previous value if the key was already present, otherwiseNone— matchingBTreeMap::insert.removereturns the removed value, orNoneif the key was absent. It never panics on a missing key (maps have no notion of an out-of-range key).get,get_mut, andcontainsreturnNone/falsefor missing keys;v[key]panics.appendis an array-only operation and panics when called on a map.
§Example
use cbor_core::{Value, array, map};
// --- arrays ---
let mut a = array![10, 30];
a.insert(1, 20); // shift-insert at index 1
a.append(40); // push to end
assert_eq!(a.len(), Some(4));
a[0] = Value::from(99); // O(1) in-place replace
assert_eq!(a.remove(0).unwrap().to_u32().unwrap(), 99);
assert!(a.contains(0));
assert_eq!(a.get(5), None); // out of range: soft miss
// --- maps ---
let mut m = map! { "x" => 10 };
assert_eq!(m.insert("y", 20), None); // new key
assert_eq!(m.insert("x", 99).unwrap().to_u32().unwrap(), 10);
assert_eq!(m["x"].to_u32().unwrap(), 99);
assert_eq!(m.remove("missing"), None); // missing key: no panic
assert!(!m.contains("missing"));§Tags
A tag wraps another value with a numeric label (e.g. tag 1 for epoch timestamps, tag 32 for URIs). Tags can be nested.
| Method | Returns | Notes |
|---|---|---|
tag_number | Result<u64> | Tag number |
tag_content | Result<&Value> | Borrowed content |
tag_content_mut | Result<&mut Value> | Mutable content |
as_tag | Result<(u64, &Value)> | Both parts |
as_tag_mut | Result<(u64, &mut Value)> | Mutable content |
into_tag | Result<(u64, Value)> | Consuming |
Use untagged to look through tags without removing
them, remove_tag to strip the outermost tag, or
remove_all_tags to strip all layers at once.
use cbor_core::Value;
// Create a tagged value (tag 32 = URI)
let mut uri = Value::tag(32, "https://example.com");
// Inspect
let (tag_num, content) = uri.as_tag().unwrap();
assert_eq!(tag_num, 32);
assert_eq!(content.as_str().unwrap(), "https://example.com");
// Look through tags without removing them
assert_eq!(uri.untagged().as_str().unwrap(), "https://example.com");
// Strip the tag in place
let removed = uri.remove_tag();
assert_eq!(removed, Some(32));
assert_eq!(uri.as_str().unwrap(), "https://example.com");Accessor methods see through tags transparently: calling as_str()
on a tagged text string works without manually unwrapping the tag
first. This applies to all accessors (to_*, as_*, into_*).
use cbor_core::Value;
let uri = Value::tag(32, "https://example.com");
assert_eq!(uri.as_str().unwrap(), "https://example.com");
// Nested tags are also transparent
let nested = Value::tag(100, Value::tag(200, 42));
assert_eq!(nested.to_u32().unwrap(), 42);Big integers are internally represented as tagged byte strings
(tags 2 and 3). The integer accessors recognise these tags and
decode the bytes automatically, even when wrapped in additional
custom tags. Byte-level accessors like as_bytes() also see
through tags, so calling as_bytes() on a big integer returns
the raw payload bytes.
If a tag is removed via remove_tag, remove_all_tags, or by
consuming through into_tag, the value becomes a plain byte
string and can no longer be read as an integer.
§Type introspection
data_type returns a DataType enum for
lightweight type checks without matching on the full enum.
use cbor_core::Value;
let v = Value::from(3.14);
assert!(v.data_type().is_float());Variants§
SimpleValue(SimpleValue)
Simple value such as null, true, or false (major type 7).
In CBOR, booleans and null are simple values, not distinct types.
A Value::from(true) is stored as SimpleValue(21) and is
accessible through both to_bool and
to_simple_value.
let sv = Value::null();
assert!(sv.data_type().is_simple_value() && sv.data_type().is_null());
let sv = Value::new(false);
assert!(sv.data_type().is_simple_value() && sv.data_type().is_bool());Unsigned(u64)
Unsigned integer (major type 0). Stores values 0 through 2^64-1.
let v = Value::new(42);Negative(u64)
Negative integer (major type 1). The actual value is -1 - n, covering -1 through -2^64.
let v = Value::new(-42);Float(Float)
IEEE 754 floating-point number (major type 7, additional info 25-27).
let v = Value::new(1.234);ByteString(Vec<u8>)
Byte string (major type 2).
let v = Value::new(b"this is a byte string");TextString(String)
UTF-8 text string (major type 3).
let v = Value::new("Rust + CBOR::Core");Array(Vec<Value>)
Array of data items (major type 4).
use cbor_core::array;
let v = array![1, 2, 3, "text", b"bytes", true, 1.234, array![4,5,6]];Map(BTreeMap<Value, Value>)
Map of key-value pairs in canonical order (major type 5).
use cbor_core::{map, array};
let v = map!{"answer" => 42, array![1,2,3] => "arrays as keys" };Tag(u64, Box<Value>)
Tagged data item (major type 6). The first field is the tag number, the second is the enclosed content.
let v = Value::tag(0, "1955-11-12T22:04:00-08:00");Implementations§
Source§impl Value
Constructors
impl Value
Constructors
Sourcepub const fn null() -> Self
pub const fn null() -> Self
Create a CBOR null value.
In CBOR, null is the simple value 22.
use cbor_core::Value;
let v = Value::null();
assert!(v.data_type().is_null());
assert!(v.data_type().is_simple_value());
assert_eq!(v.to_simple_value(), Ok(22));Sourcepub const fn simple_value(value: u8) -> Self
pub const fn simple_value(value: u8) -> Self
Create a CBOR simple value. Usable in const context.
§Panics
Panics if the value is in the reserved range 24-31.
Use SimpleValue::from_u8 for a fallible alternative.
use cbor_core::Value;
const V: Value = Value::simple_value(42);
assert_eq!(V.to_simple_value(), Ok(42));Sourcepub const fn from_bool(value: bool) -> Self
pub const fn from_bool(value: bool) -> Self
Create a boolean Value, usable in const context.
const counterpart of Value::from(value) for booleans. In CBOR,
false is simple value 20 and true is simple value 21.
use cbor_core::Value;
const T: Value = Value::from_bool(true);
assert_eq!(T.to_bool(), Ok(true));Sourcepub const fn from_u64(value: u64) -> Value
pub const fn from_u64(value: u64) -> Value
Create an unsigned integer Value, usable in const context.
const counterpart of Value::from(value) for unsigned integers.
Smaller widths (u8, u16, u32) are intentionally not provided
as separate constructors: the as u64 widening is lossless and
the resulting Value is identical regardless of the source width.
u128 has no const constructor because values above u64::MAX
require the big-integer path, which allocates a tagged byte string.
use cbor_core::Value;
const V: Value = Value::from_u64(42);
assert_eq!(V.to_u64(), Ok(42));Sourcepub const fn from_i64(value: i64) -> Value
pub const fn from_i64(value: i64) -> Value
Create a signed integer Value, usable in const context.
const counterpart of Value::from(value) for signed integers.
Smaller widths (i8, i16, i32) are intentionally not provided
as separate constructors: the as i64 widening is lossless and
the resulting Value is identical regardless of the source width.
i128 has no const constructor for the same reason as
from_u64: out-of-i64-range values need the
big-integer path, which allocates.
use cbor_core::Value;
const V: Value = Value::from_i64(-42);
assert_eq!(V.to_i64(), Ok(-42));Sourcepub const fn from_f32(value: f32) -> Value
pub const fn from_f32(value: f32) -> Value
Create a float Value from f32, usable in const context.
const counterpart of Value::from(value) for f32. NaN
payloads are preserved. The result is stored in the shortest
CBOR form (f16, f32, or f64) that represents the value exactly.
Prefer this over Value::from_f64(x as f64) when x is already
an f32: the as f64 cast is lossless, but routing through
from_f32 is clearer about intent and preserves NaN payloads
without relying on hardware canonicalization.
use cbor_core::Value;
const V: Value = Value::from_f32(1.0);
assert_eq!(V.to_f32(), Ok(1.0));Sourcepub const fn from_f64(value: f64) -> Value
pub const fn from_f64(value: f64) -> Value
Create a float Value from f64, usable in const context.
const counterpart of Value::from(value) for f64. The result
is stored in the shortest CBOR form (f16, f32, or f64) that
represents the value exactly, NaN payloads included.
use cbor_core::Value;
const V: Value = Value::from_f64(1.5);
assert_eq!(V.to_f64(), Ok(1.5));Sourcepub const fn from_payload(payload: u64) -> Value
pub const fn from_payload(payload: u64) -> Value
Create a non-finite float Value from a 53-bit payload, usable
in const context.
Payloads encode the kind of non-finite float (Infinity, NaN) and
its signalling bits in a width-invariant layout. The typical use
is defining const sentinel values that signal application-level
conditions through NaN payloads. See Float::with_payload for
the payload layout and panic conditions.
use cbor_core::Value;
const INF: Value = Value::from_payload(0);
assert!(INF.to_f64().unwrap().is_infinite());Sourcepub fn new(value: impl TryInto<Value>) -> Self
pub fn new(value: impl TryInto<Value>) -> Self
Create a CBOR value, inferring the variant from the input type.
Equivalent to Value::try_from(value).unwrap().
Not every CBOR variant is reachable this way. Use the dedicated constructors for the remaining cases.
Whether this can panic depends on which conversion the input type provides:
- Types with
impl From<T> for Valuenever panic here.Fromis infallible by contract, and the standard blanketimpl<T, U: Into<T>> TryFrom<U> for Troutes through it without introducing a failure case. For these types,Value::fromis the more direct spelling. - Types with an explicit
impl TryFrom<T> for Value(mainly the date- and time-related ones) can fail.Value::newunwraps the error and panics. CallValue::try_frominstead to handle it.
§Panics
Panics if the input cannot be converted into a CBOR value.
Sourcepub fn byte_string(value: impl Into<Vec<u8>>) -> Self
pub fn byte_string(value: impl Into<Vec<u8>>) -> Self
Create a CBOR byte string (major type 2).
Accepts anything that converts into Vec<u8>:
- owned
Vec<u8>, borrowed&[u8]and fixed-size[u8; N](copied) Box<[u8]>, andCow<'_, [u8]>
Owned inputs are moved without copying.
use cbor_core::Value;
let v = Value::byte_string("ABC");
assert_eq!(v.as_bytes(), Ok([65, 66, 67].as_slice()));Sourcepub fn text_string(value: impl Into<String>) -> Self
pub fn text_string(value: impl Into<String>) -> Self
Create a CBOR text string (major type 3).
Accepts anything that converts into String:
- owned
String,&str(copied),Box<str> Cow<'_, str>, andchar.
Owned inputs are moved without reallocating.
use cbor_core::Value;
let v = Value::text_string('A'); // char
assert_eq!(v.as_str(), Ok("A")); // &strSourcepub fn date_time(value: impl TryInto<DateTime>) -> Self
pub fn date_time(value: impl TryInto<DateTime>) -> Self
Create a CBOR date/time string value (tag 0).
Accepts &str, String, and SystemTime via the
DateTime helper.
The date must be within
0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z.
§Panics
Panics if the input is not a valid RFC 3339 (ISO 8601 profile) UTC timestamp or is out of range.
use cbor_core::{DataType, Value};
let v = Value::date_time("2000-01-01T00:00:00.000+01:00");
assert!(v.data_type().is_date_time());
assert_eq!(v.as_str(), Ok("2000-01-01T00:00:00.000+01:00"));
use std::time::SystemTime;
let v = Value::date_time(SystemTime::UNIX_EPOCH);
assert!(v.data_type().is_date_time());
assert_eq!(v.as_str(), Ok("1970-01-01T00:00:00Z"));Sourcepub fn epoch_time(value: impl TryInto<EpochTime>) -> Self
pub fn epoch_time(value: impl TryInto<EpochTime>) -> Self
Create a CBOR epoch time value (tag 1).
Accepts integers, floats, and SystemTime via the
EpochTime helper. The value must be in the range 0 to
253402300799.
§Panics
Panics if the value is out of range or negative.
use std::time::{Duration, UNIX_EPOCH};
use cbor_core::Value;
let v = Value::epoch_time(1_000_000);
assert_eq!(v.to_system_time(), Ok(UNIX_EPOCH + Duration::from_secs(1_000_000)));Sourcepub fn float(value: impl Into<Float>) -> Self
pub fn float(value: impl Into<Float>) -> Self
Create a CBOR float.
Via the Float type floats can be created out of integers and booleans too.
use cbor_core::Value;
let f1 = Value::float(1.0);
assert!(f1.to_f64() == Ok(1.0));
let f2 = Value::float(2);
assert!(f2.to_f64() == Ok(2.0));
let f3 = Value::float(true);
assert!(f3.to_f64() == Ok(1.0));The value is stored in the shortest IEEE 754 form (f16, f32, or f64) that preserves it exactly.
Source§impl Value
Decoding and reading
impl Value
Decoding and reading
Sourcepub fn decode(bytes: impl AsRef<[u8]>) -> Result<Self>
pub fn decode(bytes: impl AsRef<[u8]>) -> Result<Self>
Decode a CBOR data item from binary bytes.
Accepts any byte source (&[u8], &str, String, Vec<u8>,
etc.). The input must contain exactly one CBOR item; any
trailing bytes cause Error::InvalidFormat.
Use DecodeOptions::sequence_decoder for
CBOR sequences.
Returns Err if the encoding is not canonical.
use cbor_core::Value;
let v = Value::decode([0x18, 42]).unwrap();
assert_eq!(v.to_u32().unwrap(), 42);Sourcepub fn decode_hex(hex: impl AsRef<[u8]>) -> Result<Self>
pub fn decode_hex(hex: impl AsRef<[u8]>) -> Result<Self>
Decode a CBOR data item from hex-encoded bytes.
Accepts any byte source (&[u8], &str, String, Vec<u8>,
etc.). Both uppercase and lowercase hex digits are accepted. The
input must contain exactly one CBOR item; any trailing hex
digits cause Error::InvalidFormat.
Returns Err if the encoding is not canonical.
use cbor_core::Value;
let v = Value::decode_hex("182a").unwrap();
assert_eq!(v.to_u32().unwrap(), 42);Sourcepub fn read_from(reader: impl Read) -> IoResult<Self>
pub fn read_from(reader: impl Read) -> IoResult<Self>
Read a single CBOR data item from a binary stream.
The reader is advanced only to the end of the item; any further bytes remain in the stream, so repeated calls pull successive items of a CBOR sequence.
use cbor_core::Value;
let mut bytes: &[u8] = &[0x18, 42];
let v = Value::read_from(&mut bytes).unwrap();
assert_eq!(v.to_u32().unwrap(), 42);Sourcepub fn read_hex_from(reader: impl Read) -> IoResult<Self>
pub fn read_hex_from(reader: impl Read) -> IoResult<Self>
Read a single CBOR data item from a hex-encoded stream.
Each byte of CBOR is expected as two hex digits (uppercase or lowercase). The reader is advanced only to the end of the item; any further hex digits remain in the stream, so repeated calls pull successive items of a CBOR sequence.
use cbor_core::Value;
let mut hex = "182a".as_bytes();
let v = Value::read_hex_from(&mut hex).unwrap();
assert_eq!(v.to_u32().unwrap(), 42);Source§impl Value
Encoding and writing
impl Value
Encoding and writing
Sourcepub fn encode(&self) -> Vec<u8> ⓘ
pub fn encode(&self) -> Vec<u8> ⓘ
Encode this value to binary CBOR bytes.
This is a convenience wrapper around write_to.
use cbor_core::Value;
let bytes = Value::from(42).encode();
assert_eq!(bytes, [0x18, 42]);Sourcepub fn encode_hex(&self) -> String
pub fn encode_hex(&self) -> String
Encode this value to a hex-encoded CBOR string.
This is a convenience wrapper around write_hex_to.
use cbor_core::Value;
let hex = Value::from(42).encode_hex();
assert_eq!(hex, "182a");Sourcepub fn write_to(&self, writer: impl Write) -> Result<()>
pub fn write_to(&self, writer: impl Write) -> Result<()>
Write this value as binary CBOR to a stream.
use cbor_core::Value;
let mut buf = Vec::new();
Value::from(42).write_to(&mut buf).unwrap();
assert_eq!(buf, [0x18, 42]);Sourcepub fn write_hex_to(&self, writer: impl Write) -> Result<()>
pub fn write_hex_to(&self, writer: impl Write) -> Result<()>
Write this value as hex-encoded CBOR to a stream.
Each binary byte is written as two lowercase hex digits. The adapter encodes on the fly without buffering the full output.
use cbor_core::Value;
let mut buf = Vec::new();
Value::from(42).write_hex_to(&mut buf).unwrap();
assert_eq!(buf, b"182a");Source§impl Value
Misc
impl Value
Misc
Sourcepub const fn data_type(&self) -> DataType
pub const fn data_type(&self) -> DataType
Return the DataType of this value for type-level dispatch.
Source§impl Value
Scalar accessors
impl Value
Scalar accessors
Sourcepub const fn to_bool(&self) -> Result<bool>
pub const fn to_bool(&self) -> Result<bool>
Extract a boolean. Returns Err for non-boolean values.
Sourcepub const fn to_simple_value(&self) -> Result<u8>
pub const fn to_simple_value(&self) -> Result<u8>
Extract the raw simple value number (0-255, excluding 24-31).
Sourcepub fn to_u8(&self) -> Result<u8>
pub fn to_u8(&self) -> Result<u8>
Narrow to u8. Returns Err(Overflow) or Err(NegativeUnsigned) on mismatch.
Sourcepub fn to_u128(&self) -> Result<u128>
pub fn to_u128(&self) -> Result<u128>
Narrow to u128. Handles big integers (tag 2) transparently.
Sourcepub fn to_i128(&self) -> Result<i128>
pub fn to_i128(&self) -> Result<i128>
Narrow to i128. Handles big integers (tags 2 and 3) transparently.
Sourcepub fn to_f32(&self) -> Result<f32>
pub fn to_f32(&self) -> Result<f32>
Convert to f32.
Returns Err(Precision) for f64-width values.
Sourcepub fn to_system_time(&self) -> Result<SystemTime>
pub fn to_system_time(&self) -> Result<SystemTime>
Convert a time value to SystemTime.
Accepts date/time strings (tag 0), epoch time values (tag 1), and untagged integers or floats. Numeric values must be non-negative and in the range 0 to 253402300799. Date/time strings may include a timezone offset, which is converted to UTC.
Returns Err(IncompatibleType) for values that are neither
numeric nor text, Err(InvalidValue) if a numeric value is out of
range, and Err(InvalidFormat) if a text string is not a
valid RFC 3339 timestamp. Leap seconds (:60) are rejected
because SystemTime cannot represent them.
use std::time::{Duration, UNIX_EPOCH};
use cbor_core::Value;
let v = Value::tag(1, 1_000_000);
let t = v.to_system_time().unwrap();
assert_eq!(t, UNIX_EPOCH + Duration::from_secs(1_000_000));Source§impl Value
Bytes and text strings
impl Value
Bytes and text strings
Sourcepub const fn as_bytes_mut(&mut self) -> Result<&mut Vec<u8>>
pub const fn as_bytes_mut(&mut self) -> Result<&mut Vec<u8>>
Borrow the byte string as a mutable Vec.
Sourcepub fn into_bytes(self) -> Result<Vec<u8>>
pub fn into_bytes(self) -> Result<Vec<u8>>
Take ownership of the byte string.
Sourcepub const fn as_string_mut(&mut self) -> Result<&mut String>
pub const fn as_string_mut(&mut self) -> Result<&mut String>
Borrow the text string as a mutable String.
Sourcepub fn into_string(self) -> Result<String>
pub fn into_string(self) -> Result<String>
Take ownership of the text string.
Source§impl Value
Arrays and maps
impl Value
Arrays and maps
Source§impl Value
Array and map helpers
impl Value
Array and map helpers
Sourcepub fn get<'a>(&self, index: impl Into<ValueKey<'a>>) -> Option<&Value>
pub fn get<'a>(&self, index: impl Into<ValueKey<'a>>) -> Option<&Value>
Look up an element by index (arrays) or key (maps).
Accepts anything convertible into ValueKey:
integers for array indices, and &str, &[u8], integers, &Value,
etc. for map keys. Transparent through tags.
Returns None if the value is not an array or map, the index is
out of bounds, the key is missing, or the key type does not match
the collection (e.g. a string index into an array).
use cbor_core::{Value, array, map};
let a = array![10, 20, 30];
assert_eq!(a.get(1).unwrap().to_u32().unwrap(), 20);
assert!(a.get(5).is_none());
let m = map! { "x" => 10 };
assert_eq!(m.get("x").unwrap().to_u32().unwrap(), 10);
assert!(m.get("missing").is_none());Sourcepub fn get_mut<'a>(
&mut self,
index: impl Into<ValueKey<'a>>,
) -> Option<&mut Value>
pub fn get_mut<'a>( &mut self, index: impl Into<ValueKey<'a>>, ) -> Option<&mut Value>
Mutable version of get.
use cbor_core::{Value, array};
let mut a = array![10, 20, 30];
*a.get_mut(1).unwrap() = Value::from(99);
assert_eq!(a[1].to_u32().unwrap(), 99);Sourcepub fn remove<'a>(&mut self, index: impl Into<ValueKey<'a>>) -> Option<Value>
pub fn remove<'a>(&mut self, index: impl Into<ValueKey<'a>>) -> Option<Value>
Remove and return an element by index (arrays) or key (maps).
For arrays, shifts subsequent elements down like
Vec::remove (O(n)) and returns the removed element. The key
must be a valid usize index in range 0..len; otherwise this
method panics, matching Vec::remove and the indexing
operator v[i].
For maps, removes and returns the entry for the given key,
or None if the key is missing — matching BTreeMap::remove.
Transparent through tags, matching get.
§Panics
- If the value is not an array or map.
- If the value is an array and the key is not a valid
usizeindex in range0..len.
use cbor_core::{array, map};
let mut a = array![10, 20, 30];
assert_eq!(a.remove(1).unwrap().to_u32().unwrap(), 20);
assert_eq!(a.len().unwrap(), 2);
let mut m = map! { "x" => 10, "y" => 20 };
assert_eq!(m.remove("x").unwrap().to_u32().unwrap(), 10);
assert!(m.remove("missing").is_none());Sourcepub fn insert(
&mut self,
key: impl Into<Value>,
value: impl Into<Value>,
) -> Option<Value>
pub fn insert( &mut self, key: impl Into<Value>, value: impl Into<Value>, ) -> Option<Value>
Insert an element into a map or array.
For maps, behaves like BTreeMap::insert: inserts the
key/value pair and returns the previous value if the key was
already present, otherwise None.
For arrays, the key is a usize index in range 0..=len.
The value is inserted at that position, shifting subsequent
elements right like Vec::insert (O(n)). Insertion into an
array always returns None.
Transparent through tags.
§Panics
- If the value is not an array or map.
- If the value is an array and the key is not a valid
usizeindex in range0..=len.
use cbor_core::{array, map};
let mut m = map! { "x" => 10 };
assert_eq!(m.insert("y", 20), None);
assert_eq!(m.insert("x", 99).unwrap().to_u32().unwrap(), 10);
assert_eq!(m["x"].to_u32().unwrap(), 99);
let mut a = array![10, 30];
assert_eq!(a.insert(1, 20), None); // always None for arrays
assert_eq!(a[1].to_u32().unwrap(), 20);
assert_eq!(a.len().unwrap(), 3);Sourcepub fn contains<'a>(&self, key: impl Into<ValueKey<'a>>) -> bool
pub fn contains<'a>(&self, key: impl Into<ValueKey<'a>>) -> bool
Test whether an array contains an index or a map contains a key.
For arrays, returns true if the key converts to a usize
in range 0..len. For maps, returns true if the key is
present. All other types return false. Transparent through tags.
use cbor_core::{Value, array, map};
let a = array![10, 20, 30];
assert!(a.contains(1));
assert!(!a.contains(5));
let m = map! { "x" => 10 };
assert!(m.contains("x"));
assert!(!m.contains("missing"));
assert!(!Value::from(42).contains(0));Sourcepub fn len(&self) -> Option<usize>
pub fn len(&self) -> Option<usize>
Number of elements in an array or map, or None for any other type.
Transparent through tags. For text and byte strings, use
as_str or as_bytes and call
len() on the slice.
use cbor_core::{Value, array, map};
assert_eq!(array![1, 2, 3].len(), Some(3));
assert_eq!(map! { "x" => 1, "y" => 2 }.len(), Some(2));
assert_eq!(Value::from("hello").len(), None);
assert_eq!(Value::from(42).len(), None);Source§impl Value
Tags
impl Value
Tags
Sourcepub const fn tag_number(&self) -> Result<u64>
pub const fn tag_number(&self) -> Result<u64>
Return the tag number.
Sourcepub const fn tag_content(&self) -> Result<&Self>
pub const fn tag_content(&self) -> Result<&Self>
Borrow the tag content.
Sourcepub const fn tag_content_mut(&mut self) -> Result<&mut Self>
pub const fn tag_content_mut(&mut self) -> Result<&mut Self>
Mutably borrow the tag content.
Sourcepub fn as_tag_mut(&mut self) -> Result<(u64, &mut Value)>
pub fn as_tag_mut(&mut self) -> Result<(u64, &mut Value)>
Borrow tag number and mutable content together.
Sourcepub fn remove_tag(&mut self) -> Option<u64>
pub fn remove_tag(&mut self) -> Option<u64>
Remove the outermost tag, returning its number. Returns None if
the value is not tagged.
Remove all nested tags, returning their numbers from outermost to innermost.
Sourcepub const fn untagged(&self) -> &Self
pub const fn untagged(&self) -> &Self
Borrow the innermost non-tag value, skipping all tag wrappers.
Sourcepub const fn untagged_mut(&mut self) -> &mut Self
pub const fn untagged_mut(&mut self) -> &mut Self
Mutable version of untagged.
Sourcepub fn into_untagged(self) -> Self
pub fn into_untagged(self) -> Self
Consuming version of untagged.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Value
Available on crate feature serde only.
impl<'de> Deserialize<'de> for Value
serde only.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<const LIMBS: usize> From<&Int<LIMBS>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<&Int<LIMBS>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<&NonZero<Int<LIMBS>>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<&NonZero<Int<LIMBS>>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<&NonZero<Uint<LIMBS>>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<&NonZero<Uint<LIMBS>>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<&Uint<LIMBS>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<&Uint<LIMBS>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<Int<LIMBS>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<Int<LIMBS>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<NonZero<Int<LIMBS>>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<NonZero<Int<LIMBS>>> for Value
crypto-bigint only.Source§impl<const LIMBS: usize> From<NonZero<Uint<LIMBS>>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<NonZero<Uint<LIMBS>>> for Value
crypto-bigint only.Source§impl From<SimpleValue> for Value
impl From<SimpleValue> for Value
Source§fn from(value: SimpleValue) -> Self
fn from(value: SimpleValue) -> Self
Source§impl<const LIMBS: usize> From<Uint<LIMBS>> for Value
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> From<Uint<LIMBS>> for Value
crypto-bigint only.Source§impl Ord for Value
impl Ord for Value
Source§impl PartialOrd for Value
impl PartialOrd for Value
Source§impl<const LIMBS: usize> TryFrom<&Value> for Int<LIMBS>
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> TryFrom<&Value> for Int<LIMBS>
crypto-bigint only.Source§impl TryFrom<&Value> for OffsetDateTime
Available on crate feature time only.
impl TryFrom<&Value> for OffsetDateTime
time only.Source§impl TryFrom<&Value> for SimpleValue
impl TryFrom<&Value> for SimpleValue
Source§impl<const LIMBS: usize> TryFrom<&Value> for Uint<LIMBS>
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> TryFrom<&Value> for Uint<LIMBS>
crypto-bigint only.Source§impl TryFrom<&Value> for UtcDateTime
Available on crate feature time only.
impl TryFrom<&Value> for UtcDateTime
time only.Source§impl TryFrom<Value> for DateTime<FixedOffset>
Available on crate feature chrono only.
impl TryFrom<Value> for DateTime<FixedOffset>
chrono only.Source§impl<const LIMBS: usize> TryFrom<Value> for Int<LIMBS>
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> TryFrom<Value> for Int<LIMBS>
crypto-bigint only.Source§impl TryFrom<Value> for OffsetDateTime
Available on crate feature time only.
impl TryFrom<Value> for OffsetDateTime
time only.Source§impl TryFrom<Value> for SimpleValue
impl TryFrom<Value> for SimpleValue
Source§impl TryFrom<Value> for Timestamp
Available on crate feature jiff only.
impl TryFrom<Value> for Timestamp
jiff only.Source§impl<const LIMBS: usize> TryFrom<Value> for Uint<LIMBS>
Available on crate feature crypto-bigint only.
impl<const LIMBS: usize> TryFrom<Value> for Uint<LIMBS>
crypto-bigint only.Source§impl TryFrom<Value> for UtcDateTime
Available on crate feature time only.
impl TryFrom<Value> for UtcDateTime
time only.Source§impl TryFrom<Value> for Zoned
Available on crate feature jiff only.
impl TryFrom<Value> for Zoned
jiff only.