Skip to content

Commit

Permalink
Merge pull request #1361 from eclipse-zenoh/dev/zbytes_slice_iterator
Browse files Browse the repository at this point in the history
Encapsulate ZBufSliceIterator in ZBytesSliceIterator
  • Loading branch information
Mallets authored Sep 5, 2024
2 parents 60af274 + 1d3be7e commit 46185bc
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions zenoh/src/api/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl From<OptionZBytes> for Option<ZBytes> {
}
}

/// Trait to encode a type `T` into a [`Value`].
/// Trait to encode a type `T` into a [`ZBytes`].
pub trait Serialize<T> {
type Output;

Expand Down Expand Up @@ -345,8 +345,8 @@ impl ZBytes {
/// assert_eq!(buf1.as_slice(), iter.next().unwrap());
/// assert_eq!(buf2.as_slice(), iter.next().unwrap());
/// ```
pub fn slices(&self) -> impl Iterator<Item = &[u8]> {
self.0.slices()
pub fn slices(&self) -> ZBytesSliceIterator<'_> {
ZBytesSliceIterator(self.0.slices())
}

/// Serialize an object of type `T` as a [`ZBytes`] using the [`ZSerde`].
Expand Down Expand Up @@ -649,6 +649,23 @@ impl std::io::Write for ZBytesWriter<'_> {
}
}

/// An iterator that implements [`std::iter::Iterator`] trait to iterate on [`&[u8]`].
#[repr(transparent)]
#[derive(Debug)]
pub struct ZBytesSliceIterator<'a>(ZBytesSliceIteratorInner<'a>);

// Typedef to make clippy happy about complex type. Encapsulate inner `ZBufSliceOperator`.
type ZBytesSliceIteratorInner<'a> =
std::iter::Map<core::slice::Iter<'a, ZSlice>, fn(&'a ZSlice) -> &'a [u8]>;

impl<'a> Iterator for ZBytesSliceIterator<'a> {
type Item = &'a [u8];

fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}

/// An iterator that implements [`std::iter::Iterator`] trait to iterate on values `T` in a [`ZBytes`].
/// Note that [`ZBytes`] contains a serialized version of `T` and iterating over a [`ZBytes`] performs lazy deserialization.
#[repr(transparent)]
Expand Down

0 comments on commit 46185bc

Please sign in to comment.