make raw vec to share code

This commit is contained in:
nora 2021-12-21 19:49:25 +01:00
parent 180228337d
commit 0550582d03
4 changed files with 362 additions and 320 deletions

View file

@ -1,18 +1,9 @@
use crate::Vechonk;
use crate::{RawVechonk, 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<u8>,
/// 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
raw: RawVechonk<T>,
current_index: usize,
_marker: PhantomData<&'a T>,
}
@ -20,10 +11,7 @@ pub struct Iter<'a, T: ?Sized> {
impl<'a, T: ?Sized> Iter<'a, T> {
pub(super) fn new(chonk: &'a Vechonk<T>) -> Iter<'a, T> {
Self {
ptr: chonk.ptr,
len: chonk.len,
cap: chonk.cap,
elem_size: chonk.elem_size,
raw: chonk.raw.copy(),
current_index: 0,
_marker: PhantomData,
}
@ -34,11 +22,21 @@ impl<'a, T: ?Sized> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
todo!()
if self.current_index == self.raw.len {
return None;
}
// SAFETY: We just did a bounds check above
let ptr = unsafe { self.raw.get_unchecked_ptr(self.current_index) };
self.current_index += 1;
// SAFETY: We rely on `get_unchecked_ptr` returning a valid pointer, which is does, see its SAFETY comments
unsafe { Some(&*ptr) }
}
fn size_hint(&self) -> (usize, Option<usize>) {
let count = self.len - self.current_index;
let count = self.raw.len - self.current_index;
(count, Some(count))
}
@ -46,6 +44,6 @@ impl<'a, T: ?Sized> Iterator for Iter<'a, T> {
impl<'a, T: ?Sized> ExactSizeIterator for Iter<'a, T> {
fn len(&self) -> usize {
self.len - self.current_index
self.raw.len - self.current_index
}
}