From 180228337d4696281778da53ae8a10e7f2f57c9a Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Tue, 21 Dec 2021 14:17:22 +0100 Subject: [PATCH] start iter --- src/iter.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 8 ++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/iter.rs diff --git a/src/iter.rs b/src/iter.rs new file mode 100644 index 0000000..de95fe6 --- /dev/null +++ b/src/iter.rs @@ -0,0 +1,51 @@ +use crate::Vechonk; +use core::marker::PhantomData; +use core::ptr::NonNull; + +/// An iterator over the elements of a [`Vechonk`] +pub struct Iter<'a, T: ?Sized> { + /// A pointer to the first element + ptr: NonNull, + /// How many elements the Vechonk has + len: usize, + /// How much memory the Vechonk owns + cap: usize, + /// How much memory has been used by the elements, where the next element starts + elem_size: usize, + /// The next element the iterator will return + current_index: usize, + _marker: PhantomData<&'a T>, +} + +impl<'a, T: ?Sized> Iter<'a, T> { + pub(super) fn new(chonk: &'a Vechonk) -> Iter<'a, T> { + Self { + ptr: chonk.ptr, + len: chonk.len, + cap: chonk.cap, + elem_size: chonk.elem_size, + current_index: 0, + _marker: PhantomData, + } + } +} + +impl<'a, T: ?Sized> Iterator for Iter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + todo!() + } + + fn size_hint(&self) -> (usize, Option) { + let count = self.len - self.current_index; + + (count, Some(count)) + } +} + +impl<'a, T: ?Sized> ExactSizeIterator for Iter<'a, T> { + fn len(&self) -> usize { + self.len - self.current_index + } +} diff --git a/src/lib.rs b/src/lib.rs index cd47fa2..86f647b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ #![no_std] #![feature(ptr_metadata)] +#![feature(unsize)] #![deny(unsafe_op_in_unsafe_fn)] //! @@ -34,6 +35,7 @@ //! ╰─────────────────────────────────────────╯ //! ``` +mod iter; mod test; extern crate alloc; @@ -46,6 +48,8 @@ use core::ops::{Index, IndexMut}; use core::ptr::{NonNull, Pointee}; use core::{mem, ptr}; +pub use iter::Iter; + /// chonky af /// /// note: it does not run destructors for now, thankfully that is 100% safe :)))) @@ -235,6 +239,10 @@ impl Vechonk { Some(return_box) } + pub fn iter(&self) -> Iter { + Iter::new(self) + } + /// Get a reference to an element at the index. Returns `None` if the index is out of bounds pub fn get(&self, index: usize) -> Option<&T> { if index < self.len {