Struct zenoh_protocol::io::ZBuf
source · pub struct ZBuf { /* private fields */ }Expand description
A zenoh buffer.
ZBuf is a buffer that contains one or more ZSlices. It is used
to efficiently send and receive data in zenoh. It provides transparent usage for
both network and shared memory operations through a simple API.
By storing a set of ZSlice, it is possible to compose the target payload
starting from a set of non-contiguous memory regions. This provides a twofold benefit:
(1) the user can compose the payload in an incremental manner without requiring reallocations
and (2) the payload is received and recomposed as it arrives from the network without reallocating
any receiving buffer.
Example for creating a data buffer:
use zenoh_buffers::{ZBuf, ZSlice, traits::SplitBuffer, traits::buffer::InsertBuffer};
// Create a ZBuf containing a newly allocated vector of bytes.
let zbuf: ZBuf = vec![0_u8; 16].into();
assert_eq!(&vec![0_u8; 16], zbuf.contiguous().as_ref());
// Create a ZBuf containing twice a newly allocated vector of bytes.
// Allocate first a vectore of bytes and convert it into a ZSlice.
let zslice: ZSlice = vec![0_u8; 16].into();
let mut zbuf = ZBuf::default();
zbuf.append(zslice.clone()).unwrap(); // Cloning a ZSlice does not allocate
zbuf.append(zslice).unwrap();
assert_eq!(&vec![0_u8; 32], zbuf.contiguous().as_ref());Calling contiguous() allows to acces to the whole payload as a contiguous &[u8] via the
ZSlice type. However, this operation has a drawback when the original message was large
enough to cause network fragmentation. Because of that, the actual message payload may have
been received in multiple fragments (i.e. ZSlice) which are non-contiguous in memory.
use zenoh_buffers::{ZBuf, ZSlice, traits::SplitBuffer, traits::buffer::InsertBuffer};
// Create a ZBuf containing twice a newly allocated vector of bytes.
let zslice: ZSlice = vec![0_u8; 16].into();
let mut zbuf = ZBuf::default();
zbuf.append(zslice.clone());
// contiguous() does not allocate since zbuf contains only one slice
assert_eq!(&vec![0_u8; 16], zbuf.contiguous().as_ref());
// Add a second slice to zbuf
zbuf.append(zslice.clone());
// contiguous() allocates since zbuf contains two slices
assert_eq!(&vec![0_u8; 32], zbuf.contiguous().as_ref());zslices_num() returns the number of ZSlices the ZBuf is composed of. If
the returned value is greater than 1, then contiguous() will allocate. In order to retrieve the
content of the ZBuf without allocating, it is possible to loop over its ZSlices.