Skip to main content

Item

Struct Item 

Source
pub struct Item<'a>(/* private fields */);
Expand description

A CBOR Item.

This represents an inner item as is contained in a CBOR array, map, tag, but also in a Sequence, or a StandaloneItem (to which it is identical in CBOR, but the standalone item also describes any comments or space before or after the top-level item).

It is mainly found in deeper interaction with CBOR items, for example:

let my_map = StandaloneItem::parse(r#"{1: "one", 2: "two"}"#).unwrap();
let my_toplevel: &Item = my_map.item();
for (key, value) in my_toplevel.get_map_items().unwrap() {
    let key: &Item = key;
    println!("Mapping {} to {}", key.serialize(), value.serialize());
}

By virtue of EDN’s expressiveness, this type is capable not only of expressing any well-formed CBOR, but also to preserve encoding details that are not preferred (eg. a small integer encoded in more bytes than necessary). Some transformations on the EDN may lose such details; components that perform a translation such as recoding (_ h'18', h'6402') into <<100, 2>> have a choice to either not perform the translation or to discard some encoding details.

Implementations§

Source§

impl<'a> Item<'a>

§Conversion between the in-memory format and serializations

Note that unlike StandaloneItem, this does not provide EDN parsing: Any standalone EDN CBOR item may contain outer blank space or comments, which can only be represented in a StandaloneItem.

Source

pub fn serialize(&self) -> String

Produce an EDN String from the item

Source

pub fn from_cbor(cbor: &[u8]) -> Result<Self, CborError>

Parse a complete CBOR item.

Providing excessive data results in an error.

Source

pub fn from_cbor_with_rest(cbor: &[u8]) -> Result<(Self, &[u8]), CborError>

Parse a complete CBOR item.

Any remaining byts are returned as part of the result.

Source

pub fn cloned<'any>(&self) -> Item<'any>

Clone the item, turning any Cow::Borrowed into owned versions, which can then satisfy any lifetime.

Source§

impl<'a> Item<'a>

§Creating items from data or by wrapping other items

Source

pub fn new_integer_decimal(value: impl Into<i128>) -> Self

Create a new item that is integer valued in CBOR and expressed in decimal in EDN.

Note that while values exceeding i65 are accepted, they can not be encoded into CBOR.

Source

pub fn new_float_decimal(value: f64) -> Self

Create a new item that is float valued in CBOR and expressed in decimal in EDN.

Source

pub fn new_integer_hex(value: impl Into<u64>) -> Self

Create a new item that is integer valued in CBOR and expressed in hexadecimal in EDN.

Negative values have not been implemented in this constructor.

Source

pub fn new_bytes_hex(value: &[u8]) -> Self

Create a new item that is a byte string in CBOR (identical to the passed in value) and expressed as a h'...' string in EDN.

Source

pub fn new_text(value: &str) -> Self

Create a new item that is a text string in CBOR (identical to the passed in value) and expressed as a single double-quoted string in EDN.

assert_eq!(
    Item::new_text("Hello \"World\"\0").serialize(),
    r#""Hello \"World\"\u{0}""#,
);
Source

pub fn new_application_literal( identifier: &str, value: &str, ) -> Result<Self, InconsistentEdn>

Source

pub fn new_array(items: impl Iterator<Item = Item<'a>>) -> Self

Create a CBOR array out of the items

Source

pub fn new_map(items: impl Iterator<Item = (Item<'a>, Item<'a>)>) -> Self

Create a CBOR map out of the keys-value pairs

Source

pub fn tagged(self, tag: u64) -> Item<'a>

Wrap the item into a CBOR tag.

Source§

impl<'a> Item<'a>

§Accessing and modifying an item in place

Source

pub fn get_application_literal(&self) -> Result<(String, String), TypeMismatch>

Access application-extension identifier and string value

This only succeeds if the item is expressed using a single application oriented literal.

Source

pub fn get_bytes(&self) -> Result<Vec<u8>, TypeMismatch>

Access a byte literal value

This only succeeds if the item is a single byte string on the CBOR level, no matter how many EDN concatenations or even chunks. The EDN standard byte encodings (hex, base64 etc.) are supported, other application-oriented literals need to be resolved first.

Source

pub fn get_string(&self) -> Result<String, TypeMismatch>

Accesses a string literal value.

This only succeeds if the item is a single text string on the CBOR level, no matter how many EDN concatenations or even chunks. The EDN standard byte encodings (hex, base64 etc.) are tolerated in subsequent items as required for expressing otherwise hard to read parts.

let item = cbor_edn::StandaloneItem::parse(
    r#" (_ "hello" h'20' "world" ) "#
).unwrap();
let item = item.item();
assert_eq!("hello world", &item.get_string().unwrap());
Source

pub fn get_tag(&self) -> Result<u64, TypeMismatch>

Access the tag number

This only succeeds if the item is a tagged item. Use Self::get_tagged() to get the corresponding tagged item.

Source

pub fn get_tagged(&self) -> Result<&StandaloneItem<'a>, TypeMismatch>

Access the inner item of a tag

This only succeeds if the item is a tagged item. Use Self::get_tag() to get the corresponding tag number.

Source

pub fn get_tagged_mut( &mut self, ) -> Result<&mut StandaloneItem<'a>, TypeMismatch>

Mutably ccess the inner item of a tag

This only succeeds if the item is a tagged item. Use Self::get_tag() to get the corresponding tag number.

Source

pub fn get_integer(&self) -> Result<i128, TypeMismatch>

Access the integer value of an item

This only succeeds if the item is integer valued; the returned range is an i65 (expressed as an i128 for simplicity).

Source

pub fn get_float(&self) -> Result<f64, TypeMismatch>

Access the float value of an item

This only succeeds if the item is float valued.

Source

pub fn get_array_items( &self, ) -> Result<impl Iterator<Item = &Item<'a>>, TypeMismatch>

Access the items inside an array

This only succeeds if the item is an array.

Source

pub fn get_array_items_mut( &mut self, ) -> Result<impl Iterator<Item = &mut Item<'a>>, TypeMismatch>

Mutably access the items inside an array

This only succeeds if the item is an array.

Source

pub fn get_map_items( &self, ) -> Result<impl Iterator<Item = (&Item<'a>, &Item<'a>)>, TypeMismatch>

Access the items inside a map

This only succeeds if the item is a map.

Source

pub fn get_map_items_mut( &mut self, ) -> Result<impl Iterator<Item = (&mut Item<'a>, &mut Item<'a>)>, TypeMismatch>

Access the items inside a map

This only succeeds if the item is a map.

Source

pub fn discard_encoding_indicators(&mut self)

Removes any encoding indicators present in the item.

This does not affect space or comments; in particular, an item containing only the necessary space may be left with extraneous (but harmless) space that was previously needed to set an encoding indicator apart from a value.

Source

pub fn set_delimiters(&mut self, policy: DelimiterPolicy)

Alters how space and comments are placed inside the item.

Being a plain Item, this only affects inner space; it can not have any around itself.

See the policy values for details.

Source

pub fn with_comment(self, comment: &str) -> StandaloneItem<'a>

Turn the item into a StandaloneItem and add a single new comment

Source

pub fn visit_map_elements<F>(&mut self, f: &mut F) -> Result<(), TypeMismatch>
where F: FnMut(&mut Item<'a>, &mut Item<'a>) -> Result<(Option<String>, Result<Option<String>, String>), String> + ?Sized,

Calls a callback on any key item inside the map.

Calling this on a non-map item returns a type mismatch error.

An error string returned by the callback is stored in the tree as a comment next to the key. A successful result may also contain text that gets placed next to the key, and may contain a callback that gets applied in the same fashion to the value after the key.

§Example

The application::comment_ccs method is an exampel of a callback function.

§Future development

Once feature(try_trait) is usable, those return types can be simplified; until then, using a Result enables easy propagation of errors out of the callbacks.

Source

pub fn visit_array_elements<F>(&mut self, f: &mut F) -> Result<(), TypeMismatch>
where F: FnMut(&mut Item<'a>) -> Result<Option<String>, String> + ?Sized,

Calls a callback on any key item inside the array.

Calling this on a non-array item returns a type mismatch error.

An error string returned by the callback is stored in the tree as a comment next to the item, as is the string in the successful variant.

§Example

The application::comment_lang_tag method is an exampel of a callback function. It is relatively complex (see below).

§Future development

Once feature(try_trait) is usable, those return types can be simplified; until then, using a Result enables easy propagation of errors out of the callbacks.

This function is relatively impractical to use: When a callback needs to know its position in the array (which is a frequent occurrence in inhomogenous arrays), it needs to use internal state to count up; in doing so it needs to be a closure rather than a function, and due to suboptimal lifetimes that means that the callback may easily need to be boxed.

Trait Implementations§

Source§

impl<'a> Clone for Item<'a>

Source§

fn clone(&self) -> Item<'a>

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<'a> Debug for Item<'a>

Source§

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

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

impl<'a> From<Item<'a>> for StandaloneItem<'a>

Source§

fn from(inner: Item<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> PartialEq for Item<'a>

Source§

fn eq(&self, other: &Item<'a>) -> bool

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

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

Inequality operator !=. Read more
Source§

impl<'a> StructuralPartialEq for Item<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Item<'a>

§

impl<'a> RefUnwindSafe for Item<'a>

§

impl<'a> Send for Item<'a>

§

impl<'a> Sync for Item<'a>

§

impl<'a> Unpin for Item<'a>

§

impl<'a> UnsafeUnpin for Item<'a>

§

impl<'a> UnwindSafe for Item<'a>

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, 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.