Skip to main content

ZBytes

Struct ZBytes 

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

ZBytes contains the raw bytes data.

This type is intended to represent the data payload with minimized copying. Zenoh may construct a single ZBytes instance from pointers to multiple buffers in cases where data is received fragmented from the network.

To directly access raw data as a contiguous slice, it is preferable to convert ZBytes into a [std::borrow::Cow<[u8]>] using to_bytes. If ZBytes contains all the data in a single memory location, this is guaranteed to be zero-copy. This is the common case for small messages. If ZBytes contains data scattered in different memory regions, this operation will do an allocation and a copy. This is the common case for large messages.

It is also possible to iterate over the raw data that may be scattered across different memory regions using slices.

Another way to access raw data is to use a ZBytesReader obtained from reader that implements the standard std::io::Read trait. This is useful when deserializing data using libraries that operate on std::io::Read.

The creation of a ZBytes instance using the std::io::Write trait is also possible using the static writer method that creates a ZBytesWriter.

§Examples

ZBytes can be converted from/to raw bytes:

use std::borrow::Cow;
use zenoh::bytes::ZBytes;

let buf = b"some raw bytes";
let payload = ZBytes::from(buf);
assert_eq!(payload.to_bytes(), buf.as_slice());

Create a ZBytes with a writer and read it back with a reader:

use std::io::{Read, Write};
use zenoh::bytes::ZBytes;

let mut writer = ZBytes::writer();
writer.write_all(b"some raw bytes").unwrap();
let payload = writer.finish();
let mut reader = payload.reader();
let mut buf = [0; 14];
reader.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"some raw bytes");

Implementations§

Source§

impl ZBytes

Source

pub const fn new() -> Self

Create an empty ZBytes.

Source

pub fn is_empty(&self) -> bool

Returns whether the ZBytes is empty or not.

Source

pub fn len(&self) -> usize

Returns the total number of bytes in the ZBytes.

Source

pub fn to_bytes(&self) -> Cow<'_, [u8]>

Access raw bytes contained in the ZBytes.

In the case ZBytes contains non-contiguous regions of memory, an allocation and a copy will be done; that’s why the method returns a Cow. It’s also possible to use ZBytes::slices instead to avoid this copy.

Source

pub fn try_to_string(&self) -> Result<Cow<'_, str>, Utf8Error>

Tries to access a string contained in the ZBytes, and fails if it contains non-UTF-8 bytes.

In the case ZBytes contains non-contiguous regions of memory, an allocation and a copy will be done; that’s why the method returns a Cow. It’s also possible to use ZBytes::slices instead to avoid this copy, but then the UTF-8 check has to be done manually.

Source

pub fn reader(&self) -> ZBytesReader<'_>

Get a ZBytesReader implementing the std::io::Read trait.

See ZBytesWriter on how to chain the deserialization of different types from a single ZBytes.

Source

pub fn from_reader<R>(reader: R) -> Result<Self, Error>
where R: Read,

Build a ZBytes from a generic reader implementing std::io::Read. This operation copies data from the reader.

Source

pub fn writer() -> ZBytesWriter

Get a ZBytesWriter implementing std::io::Write trait.

See ZBytesWriter on how to chain the serialization of different types into a single ZBytes.

Source

pub fn slices(&self) -> ZBytesSliceIterator<'_>

Return an iterator over raw byte slices contained in the ZBytes.

ZBytes may store data in non-contiguous regions of memory; this iterator then allows accessing raw data directly without any attempt at deserializing it. Please note that no guarantee is provided on the internal memory layout of ZBytes. The only provided guarantee is that the byte order is preserved.

use std::io::Write;
use zenoh::bytes::ZBytes;

let buf1: Vec<u8> = vec![1, 2, 3];
let buf2: Vec<u8> = vec![4, 5, 6, 7, 8];
let mut writer = ZBytes::writer();
writer.write(&buf1);
writer.write(&buf2);
let zbytes = writer.finish();

// Access the raw content
for slice in zbytes.slices() {
    println!("{:02x?}", slice);
}

// Concatenate input in a single vector
let buf: Vec<u8> = buf1.into_iter().chain(buf2.into_iter()).collect();
// Concatenate raw bytes in a single vector
let out: Vec<u8> = zbytes.slices().fold(Vec::new(), |mut b, x| { b.extend_from_slice(x); b });
// The previous line is the equivalent of
// let out: Vec<u8> = zbs.into();
assert_eq!(buf, out);

The example below shows how the ZBytesWriter::append simply appends the slices of one ZBytes to another and how those slices can be iterated over to access the raw data.

use std::io::Write;
use zenoh::bytes::ZBytes;

let buf1: Vec<u8> = vec![1, 2, 3];
let buf2: Vec<u8> = vec![4, 5, 6, 7, 8];

let mut writer = ZBytes::writer();
writer.append(ZBytes::from(buf1.clone()));
writer.append(ZBytes::from(buf2.clone()));
let zbytes = writer.finish();

let mut iter = zbytes.slices();
assert_eq!(buf1.as_slice(), iter.next().unwrap());
assert_eq!(buf2.as_slice(), iter.next().unwrap());
Source§

impl ZBytes

Source

pub fn as_shm(&self) -> Option<&zshm>

Available on crate features unstable and shared-memory only.
Source

pub fn as_shm_mut(&mut self) -> Option<&mut zshm>

Available on crate features unstable and shared-memory only.

Trait Implementations§

Source§

impl Clone for ZBytes

Source§

fn clone(&self) -> ZBytes

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ZBytes

Source§

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

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

impl Default for ZBytes

Source§

fn default() -> ZBytes

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

impl From<&[u8]> for ZBytes

Source§

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

Converts to this type from the input type.
Source§

impl<const N: usize> From<&[u8; N]> for ZBytes

Source§

fn from(value: &[u8; N]) -> Self

Converts to this type from the input type.
Source§

impl From<&Cow<'_, [u8]>> for ZBytes

Source§

fn from(value: &Cow<'_, [u8]>) -> Self

Converts to this type from the input type.
Source§

impl From<&Cow<'_, str>> for ZBytes

Source§

fn from(value: &Cow<'_, str>) -> Self

Converts to this type from the input type.
Source§

impl From<&String> for ZBytes

Source§

fn from(value: &String) -> Self

Converts to this type from the input type.
Source§

impl From<&Vec<u8>> for ZBytes

Source§

fn from(value: &Vec<u8>) -> Self

Converts to this type from the input type.
Source§

impl From<&str> for ZBytes

Source§

fn from(value: &str) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize> From<[u8; N]> for ZBytes

Source§

fn from(value: [u8; N]) -> Self

Converts to this type from the input type.
Source§

impl<const ID: u8> From<AttachmentType<ID>> for ZBytes

Source§

fn from(this: AttachmentType<ID>) -> Self

Converts to this type from the input type.
Source§

impl From<Bytes> for ZBytes

Source§

fn from(value: Bytes) -> Self

Converts to this type from the input type.
Source§

impl From<Cow<'_, [u8]>> for ZBytes

Source§

fn from(value: Cow<'_, [u8]>) -> Self

Converts to this type from the input type.
Source§

impl From<Cow<'_, str>> for ZBytes

Source§

fn from(value: Cow<'_, str>) -> Self

Converts to this type from the input type.
Source§

impl From<String> for ZBytes

Source§

fn from(value: String) -> Self

Converts to this type from the input type.
Source§

impl<T, Buf: Into<ZBytes>> From<Typed<T, Buf>> for ZBytes

Available on crate features unstable and shared-memory only.
Source§

fn from(value: Typed<T, Buf>) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for ZBytes

Source§

fn from(value: Vec<u8>) -> Self

Converts to this type from the input type.
Source§

impl From<ZBuf> for ZBytes

Source§

fn from(value: ZBuf) -> Self

Converts to this type from the input type.
Source§

impl<const ID: u8> From<ZBytes> for AttachmentType<ID>

Source§

fn from(this: ZBytes) -> Self

Converts to this type from the input type.
Source§

impl From<ZBytes> for ZBuf

Source§

fn from(value: ZBytes) -> Self

Converts to this type from the input type.
Source§

impl From<ZBytesWriter> for ZBytes

Source§

fn from(value: ZBytesWriter) -> Self

Converts to this type from the input type.
Source§

impl From<ZShm> for ZBytes

Available on crate features unstable and shared-memory only.
Source§

fn from(value: ZShm) -> Self

Converts to this type from the input type.
Source§

impl From<ZShmMut> for ZBytes

Available on crate features unstable and shared-memory only.
Source§

fn from(value: ZShmMut) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for ZBytes

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for ZBytes

Source§

impl StructuralPartialEq for ZBytes

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<Source> AccessAs for Source

Source§

fn ref_as<T>(&self) -> <Source as IGuardRef<T>>::Guard<'_>
where Source: IGuardRef<T>, T: ?Sized,

Provides immutable access to a type as if it were its ABI-unstable equivalent.
Source§

fn mut_as<T>(&mut self) -> <Source as IGuardMut<T>>::GuardMut<'_>
where Source: IGuardMut<T>, T: ?Sized,

Provides mutable access to a type as if it were its ABI-unstable equivalent.
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> AsNode<T> for T

Source§

fn as_node(&self) -> &T

Source§

impl<T> AsNodeMut<T> for T

Source§

fn as_node_mut(&mut self) -> &mut T

Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, As> IGuardMut<As> for T
where T: Into<As>, As: Into<T>,

Source§

type GuardMut<'a> = MutAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary after applying its changes to the original.
Source§

fn guard_mut_inner(&mut self) -> <T as IGuardMut<As>>::GuardMut<'_>

Construct the temporary and guard it through a mutable reference.
Source§

impl<T, As> IGuardRef<As> for T
where T: Into<As>, As: Into<T>,

Source§

type Guard<'a> = RefAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary.
Source§

fn guard_ref_inner(&self) -> <T as IGuardRef<As>>::Guard<'_>

Construct the temporary and guard it through an immutable reference.
Source§

impl<T> Includes<End> for T

Source§

type Output = End

The result
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more