From c1de2d417389c1478bab4798b7cde6cbb08bba87 Mon Sep 17 00:00:00 2001 From: HampusM Date: Fri, 28 Mar 2025 14:29:32 +0100 Subject: feat: add immutable field slice iter --- src/lib.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 9e25467..fc7179d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -245,7 +245,11 @@ impl MultiVec ) }; - FieldSlice { bytes, field_metadata } + FieldSlice { + bytes, + len: self.len(), + field_metadata, + } } /// Returns a slice containing the specified field of all items. @@ -485,6 +489,7 @@ impl Drop for MultiVec pub struct FieldSlice<'mv> { bytes: &'mv [MaybeUninit], + len: usize, field_metadata: &'mv FieldMetadata, } @@ -496,6 +501,65 @@ impl FieldSlice<'_> unsafe { self.bytes.cast::() } } + + pub fn iter(&self) -> FieldSliceIter<'_> + { + FieldSliceIter { + bytes: self.bytes, + index: 0, + len: self.len, + field_metadata: self.field_metadata, + } + } +} + +pub struct FieldSliceIter<'mv> +{ + bytes: &'mv [MaybeUninit], + index: usize, + len: usize, + field_metadata: &'mv FieldMetadata, +} + +impl<'mv> Iterator for FieldSliceIter<'mv> +{ + type Item = Field<'mv>; + + fn next(&mut self) -> Option + { + let start_off = self.index * self.field_metadata.size; + + if self.index >= self.len { + return None; + } + + let field_bytes = self + .bytes + .get(start_off..start_off + self.field_metadata.size)?; + + self.index += 1; + + Some(Field { + bytes: field_bytes, + field_metadata: self.field_metadata, + }) + } +} + +pub struct Field<'mv> +{ + bytes: &'mv [MaybeUninit], + field_metadata: &'mv FieldMetadata, +} + +impl Field<'_> +{ + pub fn cast(&mut self) -> &T + { + assert_eq!(TypeId::of::(), self.field_metadata.type_id); + + unsafe { &*self.bytes.as_ptr().cast::() } + } } pub struct FieldSliceMut<'mv> -- cgit v1.2.3-18-g5258